hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e094665fe6ff61c27f7675e0d5a208a71d7f02a
3,948
java
Java
aws-java-sdk-route53recoveryreadiness/src/main/java/com/amazonaws/services/route53recoveryreadiness/model/DeleteCrossAccountAuthorizationRequest.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
3,372
2015-01-03T00:35:43.000Z
2022-03-31T15:56:24.000Z
aws-java-sdk-route53recoveryreadiness/src/main/java/com/amazonaws/services/route53recoveryreadiness/model/DeleteCrossAccountAuthorizationRequest.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
2,391
2015-01-01T12:55:24.000Z
2022-03-31T08:01:50.000Z
aws-java-sdk-route53recoveryreadiness/src/main/java/com/amazonaws/services/route53recoveryreadiness/model/DeleteCrossAccountAuthorizationRequest.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
2,876
2015-01-01T14:38:37.000Z
2022-03-29T19:53:10.000Z
34.034483
150
0.68997
3,918
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.route53recoveryreadiness.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/route53-recovery-readiness-2019-12-02/DeleteCrossAccountAuthorization" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteCrossAccountAuthorizationRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** The cross account authorization */ private String crossAccountAuthorization; /** * The cross account authorization * * @param crossAccountAuthorization * The cross account authorization */ public void setCrossAccountAuthorization(String crossAccountAuthorization) { this.crossAccountAuthorization = crossAccountAuthorization; } /** * The cross account authorization * * @return The cross account authorization */ public String getCrossAccountAuthorization() { return this.crossAccountAuthorization; } /** * The cross account authorization * * @param crossAccountAuthorization * The cross account authorization * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteCrossAccountAuthorizationRequest withCrossAccountAuthorization(String crossAccountAuthorization) { setCrossAccountAuthorization(crossAccountAuthorization); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getCrossAccountAuthorization() != null) sb.append("CrossAccountAuthorization: ").append(getCrossAccountAuthorization()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteCrossAccountAuthorizationRequest == false) return false; DeleteCrossAccountAuthorizationRequest other = (DeleteCrossAccountAuthorizationRequest) obj; if (other.getCrossAccountAuthorization() == null ^ this.getCrossAccountAuthorization() == null) return false; if (other.getCrossAccountAuthorization() != null && other.getCrossAccountAuthorization().equals(this.getCrossAccountAuthorization()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCrossAccountAuthorization() == null) ? 0 : getCrossAccountAuthorization().hashCode()); return hashCode; } @Override public DeleteCrossAccountAuthorizationRequest clone() { return (DeleteCrossAccountAuthorizationRequest) super.clone(); } }
3e094668d85591d22e09cdcc4872d4ec5ca8b3ad
2,050
java
Java
plugins/pi4j-plugin-raspberrypi/src/main/java/com/pi4j/plugin/raspberrypi/provider/gpio/digital/RpiDigitalOutputProviderImpl.java
mheath/pi4j-v2
54164ef1167fbc7ed20f404a48d99efb19c5591c
[ "Apache-2.0" ]
null
null
null
plugins/pi4j-plugin-raspberrypi/src/main/java/com/pi4j/plugin/raspberrypi/provider/gpio/digital/RpiDigitalOutputProviderImpl.java
mheath/pi4j-v2
54164ef1167fbc7ed20f404a48d99efb19c5591c
[ "Apache-2.0" ]
null
null
null
plugins/pi4j-plugin-raspberrypi/src/main/java/com/pi4j/plugin/raspberrypi/provider/gpio/digital/RpiDigitalOutputProviderImpl.java
mheath/pi4j-v2
54164ef1167fbc7ed20f404a48d99efb19c5591c
[ "Apache-2.0" ]
null
null
null
35.344828
113
0.66439
3,919
package com.pi4j.plugin.raspberrypi.provider.gpio.digital; /* * #%L * ********************************************************************** * ORGANIZATION : Pi4J * PROJECT : Pi4J :: PLUGIN :: RaspberryPi Platform & Providers * FILENAME : RpiDigitalOutputProviderImpl.java * * This file is part of the Pi4J project. More information about * this project can be found here: https://pi4j.com/ * ********************************************************************** * %% * Copyright (C) 2012 - 2021 Pi4J * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ import com.pi4j.io.gpio.digital.DigitalOutput; import com.pi4j.io.gpio.digital.DigitalOutputConfig; import com.pi4j.io.gpio.digital.DigitalOutputProviderBase; /** * <p>RpiDigitalOutputProviderImpl class.</p> * * @author Robert Savage (<a href="http://www.savagehomeautomation.com">http://www.savagehomeautomation.com</a>) * @version $Id: $Id */ public class RpiDigitalOutputProviderImpl extends DigitalOutputProviderBase implements RpiDigitalOutputProvider { /** * <p>Constructor for RpiDigitalOutputProviderImpl.</p> */ public RpiDigitalOutputProviderImpl(){ this.id = ID; this.name = NAME; } /** {@inheritDoc} */ @Override public DigitalOutput create(DigitalOutputConfig config) throws Exception { return new RpiDigitalOutput(this, config); } }
3e0946e255e9d4f58e96e660271aba49a88ad1d0
6,897
java
Java
transport-native-unix-common/src/main/java/io/netty/channel/unix/IovArray.java
misamatti/netty
ed46c4ed00ec8260d64eda19ae05aae03fcdaa20
[ "Apache-2.0" ]
4
2018-03-03T03:09:01.000Z
2020-03-26T10:58:31.000Z
transport-native-unix-common/src/main/java/io/netty/channel/unix/IovArray.java
jane-great/netty
d1055e06658838a8667fca6e6d601150ccb86837
[ "Apache-2.0" ]
null
null
null
transport-native-unix-common/src/main/java/io/netty/channel/unix/IovArray.java
jane-great/netty
d1055e06658838a8667fca6e6d601150ccb86837
[ "Apache-2.0" ]
3
2018-05-31T03:42:00.000Z
2020-06-01T15:04:03.000Z
35.551546
120
0.640278
3,920
/* * Copyright 2014 The Netty Project * * The Netty Project 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 io.netty.channel.unix; import io.netty.buffer.ByteBuf; import io.netty.buffer.CompositeByteBuf; import io.netty.channel.ChannelOutboundBuffer.MessageProcessor; import io.netty.util.internal.PlatformDependent; import java.nio.ByteBuffer; import static io.netty.channel.unix.Limits.IOV_MAX; import static io.netty.channel.unix.Limits.SSIZE_MAX; import static io.netty.util.internal.ObjectUtil.checkPositive; import static io.netty.util.internal.PlatformDependent.allocateMemory; import static io.netty.util.internal.PlatformDependent.directBufferAddress; import static io.netty.util.internal.PlatformDependent.freeMemory; import static io.netty.util.internal.PlatformDependent.putInt; import static io.netty.util.internal.PlatformDependent.putLong; import static java.lang.Math.min; /** * Represent an array of struct array and so can be passed directly over via JNI without the need to do any more * array copies. * * The buffers are written out directly into direct memory to match the struct iov. See also {@code man writev}. * * <pre> * struct iovec { * void *iov_base; * size_t iov_len; * }; * </pre> * * See also * <a href="http://rkennke.wordpress.com/2007/07/30/efficient-jni-programming-iv-wrapping-native-data-objects/" * >Efficient JNI programming IV: Wrapping native data objects</a>. */ public final class IovArray implements MessageProcessor { /** The size of an address which should be 8 for 64 bits and 4 for 32 bits. */ private static final int ADDRESS_SIZE = PlatformDependent.addressSize(); /** * The size of an {@code iovec} struct in bytes. This is calculated as we have 2 entries each of the size of the * address. */ private static final int IOV_SIZE = 2 * ADDRESS_SIZE; /** * The needed memory to hold up to {@code IOV_MAX} iov entries, where {@code IOV_MAX} signified * the maximum number of {@code iovec} structs that can be passed to {@code writev(...)}. */ private static final int CAPACITY = IOV_MAX * IOV_SIZE; private final long memoryAddress; private int count; private long size; private long maxBytes = SSIZE_MAX; public IovArray() { memoryAddress = allocateMemory(CAPACITY); } public void clear() { count = 0; size = 0; } /** * Add a {@link ByteBuf} to this {@link IovArray}. * @param buf The {@link ByteBuf} to add. * @return {@code true} if the entire {@link ByteBuf} has been added to this {@link IovArray}. Note in the event * that {@link ByteBuf} is a {@link CompositeByteBuf} {@code false} may be returned even if some of the components * have been added. */ public boolean add(ByteBuf buf) { if (count == IOV_MAX) { // No more room! return false; } else if (buf.nioBufferCount() == 1) { final int len = buf.readableBytes(); return len == 0 || add(buf.memoryAddress(), buf.readerIndex(), len); } else { ByteBuffer[] buffers = buf.nioBuffers(); for (ByteBuffer nioBuffer : buffers) { final int len = nioBuffer.remaining(); if (len != 0 && (!add(directBufferAddress(nioBuffer), nioBuffer.position(), len) || count == IOV_MAX)) { return false; } } return true; } } private boolean add(long addr, int offset, int len) { final long baseOffset = memoryAddress(count); final long lengthOffset = baseOffset + ADDRESS_SIZE; // If there is at least 1 entry then we enforce the maximum bytes. We want to accept at least one entry so we // will attempt to write some data and make progress. if (maxBytes - len < size && count > 0) { // If the size + len will overflow SSIZE_MAX we stop populate the IovArray. This is done as linux // not allow to write more bytes then SSIZE_MAX with one writev(...) call and so will // return 'EINVAL', which will raise an IOException. // // See also: // - http://linux.die.net/man/2/writev return false; } size += len; ++count; if (ADDRESS_SIZE == 8) { // 64bit putLong(baseOffset, addr + offset); putLong(lengthOffset, len); } else { assert ADDRESS_SIZE == 4; putInt(baseOffset, (int) addr + offset); putInt(lengthOffset, len); } return true; } /** * Returns the number if iov entries. */ public int count() { return count; } /** * Returns the size in bytes */ public long size() { return size; } /** * Set the maximum amount of bytes that can be added to this {@link IovArray} via {@link #add(ByteBuf)}. * <p> * This will not impact the existing state of the {@link IovArray}, and only applies to subsequent calls to * {@link #add(ByteBuf)}. * <p> * In order to ensure some progress is made at least one {@link ByteBuf} will be accepted even if it's size exceeds * this value. * @param maxBytes the maximum amount of bytes that can be added to this {@link IovArray} via {@link #add(ByteBuf)}. */ public void maxBytes(long maxBytes) { this.maxBytes = min(SSIZE_MAX, checkPositive(maxBytes, "maxBytes")); } /** * Get the maximum amount of bytes that can be added to this {@link IovArray} via {@link #add(ByteBuf)}. * @return the maximum amount of bytes that can be added to this {@link IovArray} via {@link #add(ByteBuf)}. */ public long maxBytes() { return maxBytes; } /** * Returns the {@code memoryAddress} for the given {@code offset}. */ public long memoryAddress(int offset) { return memoryAddress + IOV_SIZE * offset; } /** * Release the {@link IovArray}. Once release further using of it may crash the JVM! */ public void release() { freeMemory(memoryAddress); } @Override public boolean processMessage(Object msg) throws Exception { return (msg instanceof ByteBuf) && add((ByteBuf) msg); } }
3e0949654c92c8fdf13dab0fbe3d44ddf0c4bcbf
682
java
Java
api/src/main/java/org/reactivestreams/Publisher.java
rkuhn/reactive-streams
ae4b75ab0f8b6164552603c68fa1b52959750428
[ "CC0-1.0" ]
1
2019-11-02T11:02:21.000Z
2019-11-02T11:02:21.000Z
api/src/main/java/org/reactivestreams/Publisher.java
rkuhn/reactive-streams
ae4b75ab0f8b6164552603c68fa1b52959750428
[ "CC0-1.0" ]
null
null
null
api/src/main/java/org/reactivestreams/Publisher.java
rkuhn/reactive-streams
ae4b75ab0f8b6164552603c68fa1b52959750428
[ "CC0-1.0" ]
1
2020-11-25T15:14:18.000Z
2020-11-25T15:14:18.000Z
32.47619
114
0.640762
3,921
package org.reactivestreams; public interface Publisher<T> { /** * Request {@link Publisher} to start streaming data. * <p> * This is a "factory method" and can be called multiple times, each time starting a new {@link Subscription}. * <p> * Each {@link Subscription} will work for only a single {@link Subscriber}. * <p> * A {@link Subscriber} should only subscribe once to a single {@link Publisher}. * <p> * If the {@link Publisher} rejects the subscription attempt or otherwise fails it will * signal the error via {@link Subscriber#onError}. * * @param s */ public void subscribe(Subscriber<T> s); }
3e094a9f538f60b333bf2ba6526780b0d3e7161c
4,630
java
Java
winterwell.bob/src/com/winterwell/bob/tasks/WinterwellProjectFinder.java
good-loop/open-code
3a5b9f49d22778db8b87eb6b59543fea6f7e61a9
[ "MIT" ]
2
2016-12-13T15:12:41.000Z
2017-05-04T08:00:23.000Z
winterwell.bob/src/com/winterwell/bob/tasks/WinterwellProjectFinder.java
anitawoodruff/open-code
5d8f66ce318838fb4c305b20c187864b483ae6ec
[ "MIT" ]
11
2017-06-09T17:16:42.000Z
2021-03-10T13:59:57.000Z
winterwell.bob/src/com/winterwell/bob/tasks/WinterwellProjectFinder.java
anitawoodruff/open-code
5d8f66ce318838fb4c305b20c187864b483ae6ec
[ "MIT" ]
5
2017-06-09T11:27:23.000Z
2022-02-25T22:47:57.000Z
31.868966
107
0.696819
3,922
package com.winterwell.bob.tasks; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.winterwell.utils.IFn; import com.winterwell.utils.containers.ArrayMap; import com.winterwell.utils.io.FileUtils; import com.winterwell.utils.log.Log; /** * TODO find the dir for a WW Eclipse or node project. * This is a place for WW specific hacks * TODO use this in e.g. EclipseClassPath * @author daniel * */ public class WinterwellProjectFinder implements IFn<String, File> { private static volatile boolean initFlag; public WinterwellProjectFinder() { init(); } /** * Just spit out some debug info (once) */ private void init() { if (initFlag) return; initFlag = true; // Where are we looking? File wdir = FileUtils.getWinterwellDir(); Log.d("ProjectFinder", "WINTERWELL_HOME: "+wdir); Log.d("ProjectFinder", "bobwarehouse: "+new File(wdir, "bobwarehouse")); } /** * @return null on failure */ @Override public File apply(String _projectName) { // HACK portal is in adserver if ("portal".equals(_projectName)) { _projectName = "adserver"; } List<File> possDirs = new ArrayList(); // are we in the project dir? if (FileUtils.getWorkingDirectory().getName().equals(_projectName)) { possDirs.add(FileUtils.getWorkingDirectory()); } // ...also check the Eclipse project file try { // This will likely fail on a "strange" computer as it uses winterwell-home :( EclipseClasspath ec = new EclipseClasspath(FileUtils.getWorkingDirectory()); String pname = ec.getProjectName(); if (_projectName.equals(pname)) { possDirs.add(FileUtils.getWorkingDirectory()); } } catch(Exception ex) { // oh well } try { File wdir = FileUtils.getWinterwellDir(); // prefer the warehouse possDirs.add(new File(wdir, "bobwarehouse/"+_projectName)); possDirs.add(new File(wdir, "bobwarehouse/open-code/"+_projectName)); // NB: winterwell-code is typically cloned as code, so let's check both options possDirs.add(new File(wdir, "bobwarehouse/code/"+_projectName)); possDirs.add(new File(wdir, "bobwarehouse/winterwell-code/"+_projectName)); // only the warehouse? For robustly repeatable builds // possDirs.add(new File(wdir, "open-code/"+_projectName)); // possDirs.add(new File(wdir, "code/"+_projectName)); // possDirs.add(new File(wdir, _projectName)); } catch(Exception ex) { // no WINTERWELL_HOME Log.w("BuildWinterwellProject", "No WINTERWELL_HOME found "+ex); } // Bug seen May 2020: beware of basically empty dirs for (File pd : possDirs) { if ( ! pd.exists()) continue; // HACK look for some file to confirm its valid for(String f : "src .classpath .project config".split(" ")) { if (new File(pd, f).exists()) { return pd; } } } // failed Log.e("BuildWinterwellProject", "Could not find project directory for "+_projectName+" Tried "+possDirs); return null; } /** * HACK for deploying WW libs * {project-name: "repo_url repo_folder sub_folder"} */ static final Map<String,String> KNOWN_PROJECTS = new ArrayMap( "winterwell.utils", "https://github.com/good-loop/open-code open-code winterwell.utils", "winterwell.web", "https://github.com/good-loop/open-code open-code winterwell.web", "winterwell.webappbase", "https://github.com/good-loop/open-code open-code winterwell.webappbase", "winterwell.nlp", "https://github.com/good-loop/open-code open-code winterwell.nlp", "winterwell.maths", "https://github.com/good-loop/open-code open-code winterwell.maths", "winterwell.datalog", "https://github.com/good-loop/open-code open-code winterwell.datalog", "winterwell.depot", "https://github.com/good-loop/open-code open-code winterwell.depot", "winterwell.bob", "https://github.com/good-loop/open-code open-code winterwell.bob", "youagain-java-client", "https://github.com/good-loop/open-code open-code youagain-java-client", "elasticsearch-java-client", "https://github.com/good-loop/elasticsearch-java-client.git", "juice", "https://github.com/good-loop/juice", "play.good-loop.com", "https://github.com/good-loop/play.good-loop.com.git", "jtwitter", "https://github.com/winterstein/JTwitter.git", "flexi-gson", "https://github.com/winterstein/flexi-gson.git", "dataloader", "nnheo@example.com:/good-loop/code code dataloader", "youagain-server", "nnheo@example.com:/good-loop/code code youagain-server", "winterwell.demographics", "nnheo@example.com:/good-loop/code code winterwell.demographics" ); }
3e094b19663e0964b10617ba87577253db2b7a92
1,012
java
Java
amadeus-framework-model/src/main/java/com/amadeus/framework/domain/course/CourseImage.java
CreamColored/amadeus
3bb7b8b0fcf015f4a6b975cab44c66d1c198273e
[ "MIT" ]
2
2020-02-15T15:25:03.000Z
2020-02-15T15:25:05.000Z
amadeus-framework-model/src/main/java/com/amadeus/framework/domain/course/CourseImage.java
CreamColored/amadeus
3bb7b8b0fcf015f4a6b975cab44c66d1c198273e
[ "MIT" ]
2
2021-07-02T18:38:17.000Z
2021-08-09T20:46:17.000Z
amadeus-framework-model/src/main/java/com/amadeus/framework/domain/course/CourseImage.java
CreamColored/amadeus
3bb7b8b0fcf015f4a6b975cab44c66d1c198273e
[ "MIT" ]
null
null
null
23.534884
71
0.773715
3,923
package com.amadeus.framework.domain.course; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.springframework.boot.actuate.audit.listener.AuditListener; import javax.persistence.*; import javax.validation.constraints.Size; import java.io.Serializable; @Setter @Getter @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "course_image", schema = "amadeus") @EntityListeners(AuditListener.class) public class CourseImage implements Serializable { private static final long serialVersionUID = -8780661118036039773L; @Id @Size(min = 32,max = 32,message = "id为32位") private String imageId; private String smallImage; private String mediumImage; private String bigImage; private String banner; private int isBanner; @OneToOne @JoinColumn(name = "course_id",referencedColumnName = "courseId") private CourseInfo courseInfo; }
3e094baa1669a109d082a39b7b11c891ec0f8442
4,556
java
Java
adminSDK/directory/quickstart/src/main/java/AdminSDKDirectoryQuickstart.java
adrianodib/java-samples
3be4e96bc61ad515d46f42717b3f704b9339752f
[ "Apache-2.0" ]
null
null
null
adminSDK/directory/quickstart/src/main/java/AdminSDKDirectoryQuickstart.java
adrianodib/java-samples
3be4e96bc61ad515d46f42717b3f704b9339752f
[ "Apache-2.0" ]
null
null
null
adminSDK/directory/quickstart/src/main/java/AdminSDKDirectoryQuickstart.java
adrianodib/java-samples
3be4e96bc61ad515d46f42717b3f704b9339752f
[ "Apache-2.0" ]
null
null
null
47.957895
120
0.732002
3,924
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START admin_sdk_directory_quickstart] import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.admin.directory.Directory; import com.google.api.services.admin.directory.DirectoryScopes; import com.google.api.services.admin.directory.model.User; import com.google.api.services.admin.directory.model.Users; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.List; public class AdminSDKDirectoryQuickstart { private static final String APPLICATION_NAME = "Google Admin SDK Directory API Java Quickstart"; private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static final String TOKENS_DIRECTORY_PATH = "tokens"; /** * Global instance of the scopes required by this quickstart. * If modifying these scopes, delete your previously saved credentials folder at /secret. */ private static final List<String> SCOPES = Collections.singletonList(DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY); private static final String CREDENTIALS_FILE_PATH = "credentials.json"; /** * Creates an authorized Credential object. * @param HTTP_TRANSPORT The network HTTP Transport. * @return An authorized Credential object. * @throws IOException If the credentials.json file cannot be found. */ private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { // Load client secrets. InputStream in = AdminSDKDirectoryQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); // Build flow and trigger user authorization request. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH))) .setAccessType("offline") .build(); return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); } public static void main(String... args) throws IOException, GeneralSecurityException { // Build a new authorized API client service. final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); Directory service = new Directory.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) .setApplicationName(APPLICATION_NAME) .build(); // Print the first 10 users in the domain. Users result = service.users().list() .setCustomer("my_customer") .setMaxResults(10) .setOrderBy("email") .execute(); List<User> users = result.getUsers(); if (users == null || users.size() == 0) { System.out.println("No users found."); } else { System.out.println("Users:"); for (User user : users) { System.out.println(user.getName().getFullName()); } } } } // [END admin_sdk_directory_quickstart]
3e094c219dfc74e896d0b471ee3108295a88947d
337
java
Java
chao-cloud-micro-consumer/src/main/java/com/chao/cloud/micro/consumer/service/TblService.java
chaojunzi/chao-cloud-micro
06b65adba1a35aa5e5b7c01e5a40a5123dbfabd2
[ "ECL-2.0", "Apache-2.0" ]
5
2019-08-28T18:41:11.000Z
2021-04-26T07:47:01.000Z
chao-cloud-micro-consumer/src/main/java/com/chao/cloud/micro/consumer/service/TblService.java
chaojunzi/chao-cloud-micro
06b65adba1a35aa5e5b7c01e5a40a5123dbfabd2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
chao-cloud-micro-consumer/src/main/java/com/chao/cloud/micro/consumer/service/TblService.java
chaojunzi/chao-cloud-micro
06b65adba1a35aa5e5b7c01e5a40a5123dbfabd2
[ "ECL-2.0", "Apache-2.0" ]
5
2020-01-07T13:59:10.000Z
2021-12-14T08:27:54.000Z
16.85
59
0.718101
3,925
package com.chao.cloud.micro.consumer.service; import com.baomidou.mybatisplus.extension.service.IService; import com.chao.cloud.micro.consumer.dal.entity.XcTbl; /** * * @author 薛超 * @since 2019年8月26日 * @version 1.0.7 */ public interface TblService extends IService<XcTbl> { /** * 业务测试 */ Integer test(Integer userId); }
3e094cc2bdcb623df40400b3bd7db37d4c9f7064
8,571
java
Java
evaluation/github_authmreloaded_unsafe/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java
RuiDTLima/diffuzz
8a6e9603fa3bdb155f15211b8fc90e57e958c000
[ "Apache-2.0" ]
32
2019-02-21T21:10:05.000Z
2022-02-03T20:04:11.000Z
evaluation/github_authmreloaded_unsafe/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java
RuiDTLima/diffuzz
8a6e9603fa3bdb155f15211b8fc90e57e958c000
[ "Apache-2.0" ]
null
null
null
evaluation/github_authmreloaded_unsafe/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java
RuiDTLima/diffuzz
8a6e9603fa3bdb155f15211b8fc90e57e958c000
[ "Apache-2.0" ]
6
2019-02-17T07:02:43.000Z
2021-08-24T09:02:31.000Z
45.834225
137
0.714852
3,926
package fr.xephi.authme.service; import ch.jalu.injector.testing.BeforeInjecting; import ch.jalu.injector.testing.DelayedInjectionRunner; import ch.jalu.injector.testing.InjectDelayed; import com.google.common.io.Files; import fr.xephi.authme.TestHelper; import fr.xephi.authme.command.CommandInitializer; import fr.xephi.authme.command.help.HelpMessage; import fr.xephi.authme.command.help.HelpMessagesService; import fr.xephi.authme.command.help.HelpSection; import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.message.HelpMessagesFileHandler; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.mockito.Mock; import java.io.File; import java.io.IOException; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; /** * Integration test for {@link HelpTranslationGenerator}. */ @RunWith(DelayedInjectionRunner.class) public class HelpTranslationGeneratorIntegrationTest { @InjectDelayed private HelpTranslationGenerator helpTranslationGenerator; @InjectDelayed private HelpMessagesService helpMessagesService; @InjectDelayed private HelpMessagesFileHandler helpMessagesFileHandler; @InjectDelayed private CommandInitializer commandInitializer; @DataFolder private File dataFolder; private File helpMessagesFile; @Mock private Settings settings; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @BeforeClass public static void setUpLogger() { TestHelper.setupLogger(); } @BeforeInjecting public void setUpClasses() throws IOException { dataFolder = temporaryFolder.newFolder(); File messagesFolder = new File(dataFolder, "messages"); messagesFolder.mkdir(); helpMessagesFile = new File(messagesFolder, "help_test.yml"); Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "message/help_test.yml"), helpMessagesFile); given(settings.getProperty(PluginSettings.MESSAGES_LANGUAGE)).willReturn("test"); } @Test public void shouldUpdateCurrentHelpFile() throws IOException { // given / when helpTranslationGenerator.updateHelpFile(); // then FileConfiguration configuration = YamlConfiguration.loadConfiguration(helpMessagesFile); checkCommonEntries(configuration); checkSections(configuration); checkCommands(configuration); } private void checkCommonEntries(FileConfiguration configuration) { // Entries that were already present assertThat(configuration.getString(HelpMessage.HEADER.getKey()), equalTo("My custom help header")); assertThat(configuration.getString(HelpMessage.OPTIONAL.getKey()), equalTo("t-opt")); assertThat(configuration.getString("common.defaultPermissions.notAllowed"), equalTo("t-noperm")); assertThat(configuration.getString("common.defaultPermissions.allowed"), equalTo("t-allperm")); // Entries that were added from the default assertThat(configuration.getString(HelpMessage.DEFAULT.getKey()), equalTo("Default")); assertThat(configuration.getString("common.defaultPermissions.opOnly"), equalTo("OP's only")); } private void checkSections(FileConfiguration configuration) { // Entries that were already present assertThat(configuration.getString(HelpSection.COMMAND.getKey()), equalTo("my command translation")); assertThat(configuration.getString(HelpSection.SHORT_DESCRIPTION.getKey()), equalTo("")); assertThat(configuration.getString(HelpSection.CHILDREN.getKey()), equalTo("")); // Entries that were added from the default assertThat(configuration.getString(HelpSection.DETAILED_DESCRIPTION.getKey()), equalTo("Detailed description")); assertThat(configuration.getString(HelpSection.ARGUMENTS.getKey()), equalTo("Arguments")); assertThat(configuration.getString(HelpSection.COMMAND.getKey()), equalTo("my command translation")); } private void checkCommands(FileConfiguration configuration) { // Check /authme and /authme register entries: full text was available checkDescription(configuration.get("commands.authme"), "test auth desc", "test auth long desc"); checkDescription(configuration.get("commands.authme.register"), "test reg desc", "test reg long desc"); checkArgs(configuration.get("commands.authme.register"), arg("test reg arg1", "test reg arg1 text"), arg("test reg arg2", "test reg arg2 text")); // Check /unregister: only had detailed description checkDescription(configuration.get("commands.authme.unregister"), "Unregister a player", "Detailed description for unregister."); // Check /email add checkDescription(configuration.get("commands.email.add"), "email add desc", "email add long desc"); checkArgs(configuration.get("commands.email.add"), arg("add arg1", "add arg1 text"), arg("add arg2", "add arg2 text")); // Check /login checkDescription(configuration.get("commands.login"), "Login command", "/login detailed desc."); checkArgs(configuration.get("commands.login"), arg("loginArg", "Login password")); // Check /unregister checkDescription(configuration.get("commands.unregister"), "unreg_desc", "unreg_detail_desc"); checkArgs(configuration.get("commands.unregister"), arg("unreg_arg_label", "unreg_arg_desc")); // Check /changepassword: had tons of invalid stuff, just expect it to be taken from defaults checkDescription(configuration.get("commands.changepassword"), "[a list, instead of text]", "1337"); assertThat(configuration.get("commands.changepassword.arg1.label"), equalTo("true")); assertThat(configuration.get("commands.changepassword.arg1.description"), equalTo("[]")); // We have a whole object as arg2.label, for which the toString() is generated. Not very useful, so just test a portion... assertThat((String) configuration.get("commands.changepassword.arg2.label"), containsString("MemorySection")); assertThat(configuration.get("commands.changepassword.arg2.description"), equalTo("New password")); assertThat(configuration.get("commands.changepassword.arg3"), nullValue()); // Check /captcha, with empty arg text checkArgs(configuration.get("commands.captcha"), arg("", "")); } private static void checkDescription(Object memorySection, String description, String detailedDescription) { if (memorySection instanceof MemorySection) { MemorySection memSection = (MemorySection) memorySection; assertThat(memSection.getString("description"), equalTo(description)); assertThat(memSection.getString("detailedDescription"), equalTo(detailedDescription)); } else { fail("Expected MemorySection, got '" + memorySection + "'"); } } private static void checkArgs(Object memorySection, Argument... arguments) { if (memorySection instanceof MemorySection) { MemorySection memSection = (MemorySection) memorySection; int i = 1; for (Argument arg : arguments) { assertThat(memSection.getString("arg" + i + ".label"), equalTo(arg.label)); assertThat(memSection.getString("arg" + i + ".description"), equalTo(arg.description)); ++i; } assertThat(memSection.get("arg" + i), nullValue()); } else { fail("Expected MemorySection, got '" + memorySection + "'"); } } private static Argument arg(String label, String description) { return new Argument(label, description); } private static final class Argument { final String label; final String description; Argument(String label, String description) { this.label = label; this.description = description; } } }
3e094d2b5814578d4c1c90935d8d84bf752040d3
3,069
java
Java
app/src/main/java/com/example/debuggertest/listview/MyListAdapter.java
Fangtian89/DebuggerTest
0269632a8fbc94a5e9b749d16278f54dee9ac27e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/debuggertest/listview/MyListAdapter.java
Fangtian89/DebuggerTest
0269632a8fbc94a5e9b749d16278f54dee9ac27e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/debuggertest/listview/MyListAdapter.java
Fangtian89/DebuggerTest
0269632a8fbc94a5e9b749d16278f54dee9ac27e
[ "Apache-2.0" ]
null
null
null
37.888889
232
0.570218
3,927
package com.example.debuggertest.listview; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.debuggertest.R; public class MyListAdapter extends BaseAdapter { //创建映射 private Context mContext; private LayoutInflater mLayoutInflator; public MyListAdapter(Context context) { //constructor 转如context this.mContext=context; mLayoutInflator=LayoutInflater.from(context); Log.d("news","it runs in constructor "); } @Override public int getCount() { //获取数据的总的数量,返回 int 类型的结果; Log.d("news","it runs in getCount "); return 15; } @Override public long getItemId(int position) { //获取指定位置数据的id,返回该数据的id,一般以数据所在的位置作为它的id; Log.d("news","it runs in getItemID"); return 0; } @Override public Object getItem(int position) { //获取指定位置的数据,返回该数据; Log.d("news","it runs in getItem"); return null; } static class ViewHolder{ //定义holder public ImageView imageView; //里面内容 public TextView tv_Title,tv_Time,tv_Content; } @Override public View getView(int position, View convertView, ViewGroup parent) { //返回每行样式 ViewHolder holder=null ; if(convertView==null) { convertView = mLayoutInflator.inflate(R.layout.layout_list_item, null); //inflator 里面传入布局,得到一个view holder = new ViewHolder(); holder.imageView = convertView.findViewById(R.id.iv); holder.tv_Title = convertView.findViewById(R.id.tv_title); holder.tv_Time = convertView.findViewById(R.id.tv_time); holder.tv_Content = convertView.findViewById(R.id.tv_content); convertView.setTag(holder); }else { holder= (ViewHolder) convertView.getTag(); //重新获取viewholder } holder.tv_Title.setText("This is the caption"); holder.tv_Time.setText("2020-10-31"); holder.tv_Content.setText("this is our content"); Glide.with(mContext).load("https://bilder.t-online.de/b/88/04/90/46/id_88049046/610/tid_da/grillen-einige-lebensmittel-koennen-durch-das-grillen-zur-gefahr-fuer-die-gesundheit-werden-symbolbild-.jpg").into(holder.imageView); Log.d("news","it runs in getView"); return convertView; } }
3e094e4652580587c095735ff6bcc74f9aaa667e
648
java
Java
identity-service/src/main/java/com/hashmapinc/haf/requests/ActivateUserRequest.java
hashmapinc/HashmapAnalyticsFramework
98c0cf58dce57bc2a6a3cf2d112bbf7c7dd9f7ce
[ "Apache-2.0" ]
5
2018-05-28T03:00:54.000Z
2021-01-26T02:52:29.000Z
identity-service/src/main/java/com/hashmapinc/haf/requests/ActivateUserRequest.java
hashmapinc/HashmapAnalyticsFramework
98c0cf58dce57bc2a6a3cf2d112bbf7c7dd9f7ce
[ "Apache-2.0" ]
9
2018-03-28T19:56:22.000Z
2019-01-21T09:37:23.000Z
identity-service/src/main/java/com/hashmapinc/haf/requests/ActivateUserRequest.java
hashmapinc/HashmapAnalyticsFramework
98c0cf58dce57bc2a6a3cf2d112bbf7c7dd9f7ce
[ "Apache-2.0" ]
3
2018-10-20T20:13:58.000Z
2021-01-26T02:52:30.000Z
25.92
83
0.692901
3,928
package com.hashmapinc.haf.requests; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class ActivateUserRequest { private String activateToken; private String password; @JsonCreator public ActivateUserRequest(@JsonProperty("activateToken") String activateToken, @JsonProperty("password") String password) { this.activateToken = activateToken; this.password = password; } public String getActivateToken() { return activateToken; } public String getPassword() { return password; } }
3e0950ea9b52847c4a7a40fd12aa77a6e5a5a34d
3,894
java
Java
src/main/java/com/pr/sepp/sep/testing/controller/TestExecController.java
purang-fintech/seppb
971481c8ca7a662b4167503db3691d4cb3c1e63f
[ "MIT" ]
135
2019-12-13T01:35:26.000Z
2022-03-13T14:54:31.000Z
src/main/java/com/pr/sepp/sep/testing/controller/TestExecController.java
MrWuJeff/seppb
eb0c3ff23120d62cdd0981f1772a368db97e065c
[ "MIT" ]
4
2019-12-19T03:11:27.000Z
2021-12-27T02:35:39.000Z
src/main/java/com/pr/sepp/sep/testing/controller/TestExecController.java
MrWuJeff/seppb
eb0c3ff23120d62cdd0981f1772a368db97e065c
[ "MIT" ]
51
2019-12-13T06:51:10.000Z
2022-03-13T14:54:18.000Z
38.176471
98
0.778891
3,929
package com.pr.sepp.sep.testing.controller; import com.pr.sepp.common.constants.CommonParameter; import com.pr.sepp.sep.testing.model.CaseResult; import com.pr.sepp.sep.testing.model.TestRun; import com.pr.sepp.sep.testing.model.TestScenario; import com.pr.sepp.sep.testing.service.TestExecService; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @ResponseBody public class TestExecController { @Autowired private TestExecService testExecService; @RequestMapping(value = "/scenario/query", method = RequestMethod.POST) public List<TestScenario> testScenarioQuery(HttpServletRequest request) { Map<String, Object> dataMap = new HashMap<>(); dataMap.put(CommonParameter.ID, request.getParameter(CommonParameter.ID)); dataMap.put(CommonParameter.REL_ID, request.getParameter(CommonParameter.REL_ID)); dataMap.put("planId", request.getParameter("planId")); dataMap.put("planType", request.getParameter("planType")); return testExecService.testScenarioQuery(dataMap); } @RequestMapping(value = "/scenario/create", method = RequestMethod.POST) public int testScenarioCreate(@RequestBody TestScenario scenario) { return testExecService.testScenarioCreate(scenario); } @RequestMapping(value = "/scenario/update", method = RequestMethod.POST) public int testScenarioUpdate(@RequestBody TestScenario scenario) throws IllegalAccessException { return testExecService.testScenarioUpdate(scenario); } @RequestMapping(value = "/scenario/delete/{id}", method = RequestMethod.POST) public int testScenarioDelete(@PathVariable(CommonParameter.ID) Integer id) { return testExecService.testScenarioDelete(id); } @RequestMapping(value = "/scenario/case_query/{scenarioId}", method = RequestMethod.POST) public List<Map<String, Object>> scenarioCaseQuery(@PathVariable Integer scenarioId) { if (null == scenarioId) { return null; } Map<String, Object> scenarioMap = new HashMap<>(); scenarioMap.put(CommonParameter.ID, scenarioId); List<TestScenario> scenarios = testExecService.testScenarioQuery(scenarioMap); if (null == scenarios || scenarios.size() == 0) { return null; } if (StringUtils.isEmpty(scenarios.get(0).getCases())) { return null; } Map<String, Object> dataMap = new HashMap<>(); dataMap.put("cases", Arrays.asList(scenarios.get(0).getCases().split(","))); dataMap.put("scenarioId", scenarioId); return testExecService.scenarioCaseQuery(dataMap); } @RequestMapping(value = "/exec/history/{caseId}", method = RequestMethod.POST) public List<Map<String, Object>> caseRunHisQuery(@PathVariable("caseId") Integer caseId) { return testExecService.caseRunHisQuery(caseId); } @RequestMapping(value = "/exec/begin", method = RequestMethod.POST) public int testRunBegin(@RequestBody TestRun testRun) { return testExecService.testRunBegin(testRun); } @RequestMapping(value = "/exec/cancel", method = RequestMethod.POST) public int stepRunCancel(@RequestBody TestRun testRun) { return testExecService.testRunCancel(testRun); } @RequestMapping(value = "/exec/record_case_result", method = RequestMethod.POST) public int caseResultRecord(@RequestBody CaseResult caseResult) { return testExecService.caseResultRecord(caseResult); } @RequestMapping(value = "/exec/record_case_cancel", method = RequestMethod.POST) public int caseRunCancel(@RequestBody CaseResult caseResult) { return testExecService.caseRunCancel(caseResult); } @RequestMapping(value = "/exec/record_step_result", method = RequestMethod.POST) public int stepResultRecord(@RequestBody CaseResult caseResult) { return testExecService.stepResultRecord(caseResult); } }
3e095180ec8dd4ceee781912c90d09e875f39b6b
729
java
Java
header/src/main/java/org/zstack/header/network/l2/BatchCheckNetworkPhysicalInterfaceMsg.java
MatheMatrix/zstack
8da3508c624c0bd8f819da91eb28f7ebf34b8cba
[ "ECL-2.0", "Apache-2.0" ]
879
2017-02-16T02:01:44.000Z
2022-03-31T15:44:28.000Z
header/src/main/java/org/zstack/header/network/l2/BatchCheckNetworkPhysicalInterfaceMsg.java
MatheMatrix/zstack
8da3508c624c0bd8f819da91eb28f7ebf34b8cba
[ "ECL-2.0", "Apache-2.0" ]
482
2017-02-13T09:57:37.000Z
2022-03-31T07:17:29.000Z
header/src/main/java/org/zstack/header/network/l2/BatchCheckNetworkPhysicalInterfaceMsg.java
MatheMatrix/zstack
8da3508c624c0bd8f819da91eb28f7ebf34b8cba
[ "ECL-2.0", "Apache-2.0" ]
306
2017-02-13T08:31:29.000Z
2022-03-14T07:58:46.000Z
25.137931
100
0.736626
3,930
package org.zstack.header.network.l2; import org.zstack.header.host.HostMessage; import org.zstack.header.message.NeedReplyMessage; import java.util.List; public class BatchCheckNetworkPhysicalInterfaceMsg extends NeedReplyMessage implements HostMessage { private List<String> physicalInterfaces; private String hostUuid; public List<String> getPhysicalInterfaces() { return physicalInterfaces; } public void setPhysicalInterfaces(List<String> physicalInterfaces) { this.physicalInterfaces = physicalInterfaces; } public void setHostUuid(String hostUuid) { this.hostUuid = hostUuid; } @Override public String getHostUuid() { return hostUuid; } }
3e0951b738c82e9c1babc7a11637a2ad1947ca19
268
java
Java
core/src/test/java/org/femtoframework/coin/ext/SimpleCoinReloaderTest.java
femtoframework/femto-coin
bc4ce9f9bd2209bc94afbf754297b30b9fac8c2f
[ "Apache-2.0" ]
null
null
null
core/src/test/java/org/femtoframework/coin/ext/SimpleCoinReloaderTest.java
femtoframework/femto-coin
bc4ce9f9bd2209bc94afbf754297b30b9fac8c2f
[ "Apache-2.0" ]
2
2019-11-19T17:26:13.000Z
2019-11-20T18:41:51.000Z
core/src/test/java/org/femtoframework/coin/ext/SimpleCoinReloaderTest.java
femtoframework/femto-coin
bc4ce9f9bd2209bc94afbf754297b30b9fac8c2f
[ "Apache-2.0" ]
null
null
null
13.4
37
0.626866
3,931
package org.femtoframework.coin.ext; import org.junit.Test; import static org.junit.Assert.*; public class SimpleCoinReloaderTest { @Test public void reload() { } @Test public void reload1() { } @Test public void doRun() { } }
3e0951b96dfd59943db96ba38751040f84777f80
2,765
java
Java
app/controllers/AccessControl.java
jtony123/CoachCentral
e9c0c786302af2de74b5b0ac6819952d10d68c91
[ "Apache-2.0" ]
null
null
null
app/controllers/AccessControl.java
jtony123/CoachCentral
e9c0c786302af2de74b5b0ac6819952d10d68c91
[ "Apache-2.0" ]
null
null
null
app/controllers/AccessControl.java
jtony123/CoachCentral
e9c0c786302af2de74b5b0ac6819952d10d68c91
[ "Apache-2.0" ]
null
null
null
31.067416
96
0.646293
3,932
package controllers; import java.util.Date; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import javax.inject.Inject; import models.Category; import models.User; import play.data.DynamicForm; import play.data.Form; import play.data.FormFactory; import play.i18n.Messages; import play.mvc.Controller; import play.mvc.Result; public class AccessControl extends Controller { @Inject FormFactory formFactory; public CompletionStage<Result> login() { System.out.println("login called"); User user = formFactory.form(User.class).bindFromRequest().get(); DynamicForm form = Form.form().bindFromRequest(); User userDB; if(user.email != null){ if (user.password != null) { userDB = User.findByEmail(user.email); if(userDB != null){ //if(userDB.password.equalsIgnoreCase(user.password)){ if(userDB.checkPassword(form.get("password"))){ System.out.println("authenticated user"); session("connected", userDB.email); String time = Long.toString(new Date().getTime()); session("sessiontime", time); } else { System.out.println("password mismatch"); // return to user with message about mismatched password flash("error", Messages.get("login.passwordmismatch")); return CompletableFuture.completedFuture(redirect(routes.Application.index())); } } else { // user not in database System.out.println("user not in db"); flash("error", Messages.get("login.usernamenotrecognised")); return CompletableFuture.completedFuture(redirect(routes.Application.index())); } } else { // return to user requesting password to be entered System.out.println("password not entered"); flash("error", Messages.get("login.nopassword")); return CompletableFuture.completedFuture(redirect(routes.Application.index())); } } else { //return to user asking for username System.out.println("username not entered"); flash("error", Messages.get("login.nousername")); return CompletableFuture.completedFuture(redirect(routes.Application.index())); } //Category category = Category.findByName("All"); return CompletableFuture.completedFuture(redirect(routes.Application.dashboard(0, "All"))); } public CompletionStage<Result> logout() { session().remove("connected"); flash("success", Messages.get("logout.success")); return CompletableFuture.completedFuture(redirect(routes.Application.index())); } }
3e09521e046d3203be3372c6e543c6819d00c411
6,017
java
Java
spring-reactive/src/test/java/com/baeldung/reactive/webclientrequests/WebClientRequestsWithParametersUnitTest.java
thibaultfaure/tutorials
5f8a1c69ca6a2feceef3521f815a979af729e090
[ "MIT" ]
null
null
null
spring-reactive/src/test/java/com/baeldung/reactive/webclientrequests/WebClientRequestsWithParametersUnitTest.java
thibaultfaure/tutorials
5f8a1c69ca6a2feceef3521f815a979af729e090
[ "MIT" ]
10
2021-12-15T08:39:48.000Z
2022-03-22T18:04:26.000Z
spring-reactive/src/test/java/com/baeldung/reactive/webclientrequests/WebClientRequestsWithParametersUnitTest.java
thibaultfaure/tutorials
5f8a1c69ca6a2feceef3521f815a979af729e090
[ "MIT" ]
null
null
null
31.338542
102
0.627223
3,933
package com.baeldung.reactive.webclientrequests; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.web.reactive.function.client.ClientRequest; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.ExchangeFunction; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.util.DefaultUriBuilderFactory; import reactor.core.publisher.Mono; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @WebFluxTest class WebClientRequestsWithParametersUnitTest { private static final String BASE_URL = "https://example.com"; private WebClient webClient; @Captor private ArgumentCaptor<ClientRequest> argumentCaptor; @Mock private ExchangeFunction exchangeFunction; @BeforeEach void init() { ClientResponse mockResponse = mock(ClientResponse.class); when(mockResponse.bodyToMono(String.class)).thenReturn(Mono.just("test")); when(exchangeFunction.exchange(argumentCaptor.capture())).thenReturn(Mono.just(mockResponse)); webClient = WebClient .builder() .baseUrl(BASE_URL) .exchangeFunction(exchangeFunction) .build(); } @Test void whenCallSimpleURI_thenURIMatched() { webClient.get() .uri("/products") .retrieve() .bodyToMono(String.class) .block(); verifyCalledUrl("/products"); } @Test void whenCallSinglePathSegmentUri_thenURIMatched() { webClient.get() .uri(uriBuilder -> uriBuilder .path("/products/{id}") .build(2)) .retrieve() .bodyToMono(String.class) .block(); verifyCalledUrl("/products/2"); } @Test void whenCallMultiplePathSegmentsUri_thenURIMatched() { webClient.get() .uri(uriBuilder -> uriBuilder .path("/products/{id}/attributes/{attributeId}") .build(2, 13)) .retrieve() .bodyToMono(String.class) .block(); verifyCalledUrl("/products/2/attributes/13"); } @Test void whenCallSingleQueryParams_thenURIMatched() { webClient.get() .uri(uriBuilder -> uriBuilder .path("/products/") .queryParam("name", "AndroidPhone") .queryParam("color", "black") .queryParam("deliveryDate", "13/04/2019") .build()) .retrieve() .bodyToMono(String.class) .block(); verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13/04/2019"); } @Test void whenCallSingleQueryParamsPlaceholders_thenURIMatched() { webClient.get() .uri(uriBuilder -> uriBuilder .path("/products/") .queryParam("name", "{title}") .queryParam("color", "{authorId}") .queryParam("deliveryDate", "{date}") .build("AndroidPhone", "black", "13/04/2019")) .retrieve() .bodyToMono(String.class) .block(); verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13%2F04%2F2019"); } @Test void whenCallArrayQueryParamsBrackets_thenURIMatched() { webClient.get() .uri(uriBuilder -> uriBuilder .path("/products/") .queryParam("tag[]", "Snapdragon", "NFC") .build()) .retrieve() .bodyToMono(String.class) .block(); verifyCalledUrl("/products/?tag%5B%5D=Snapdragon&tag%5B%5D=NFC"); } @Test void whenCallArrayQueryParams_thenURIMatched() { webClient.get() .uri(uriBuilder -> uriBuilder .path("/products/") .queryParam("category", "Phones", "Tablets") .build()) .retrieve() .bodyToMono(String.class) .block(); verifyCalledUrl("/products/?category=Phones&category=Tablets"); } @Test void whenCallArrayQueryParamsComma_thenURIMatched() { webClient.get() .uri(uriBuilder -> uriBuilder .path("/products/") .queryParam("category", String.join(",", "Phones", "Tablets")) .build()) .retrieve() .bodyToMono(String.class) .block(); verifyCalledUrl("/products/?category=Phones,Tablets"); } @Test void whenUriComponentEncoding_thenQueryParamsNotEscaped() { DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(BASE_URL); factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT); webClient = WebClient .builder() .uriBuilderFactory(factory) .baseUrl(BASE_URL) .exchangeFunction(exchangeFunction) .build(); webClient.get() .uri(uriBuilder -> uriBuilder .path("/products/") .queryParam("name", "AndroidPhone") .queryParam("color", "black") .queryParam("deliveryDate", "13/04/2019") .build()) .retrieve() .bodyToMono(String.class) .block(); verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13/04/2019"); } private void verifyCalledUrl(String relativeUrl) { ClientRequest request = argumentCaptor.getValue(); assertEquals(String.format("%s%s", BASE_URL, relativeUrl), request.url().toString()); verify(exchangeFunction).exchange(request); verifyNoMoreInteractions(exchangeFunction); } }
3e09526de07c156da3e650422493514818b49851
602
java
Java
cat-core/src/main/java/com/dianping/cat/configuration/business/transform/IParser.java
ljj18/cat
7396910b1b3b37f027a1c5bd306b0d03e759cca6
[ "Apache-2.0" ]
null
null
null
cat-core/src/main/java/com/dianping/cat/configuration/business/transform/IParser.java
ljj18/cat
7396910b1b3b37f027a1c5bd306b0d03e759cca6
[ "Apache-2.0" ]
null
null
null
cat-core/src/main/java/com/dianping/cat/configuration/business/transform/IParser.java
ljj18/cat
7396910b1b3b37f027a1c5bd306b0d03e759cca6
[ "Apache-2.0" ]
null
null
null
43
110
0.820598
3,934
package com.dianping.cat.configuration.business.transform; import com.dianping.cat.configuration.business.entity.BusinessItemConfig; import com.dianping.cat.configuration.business.entity.BusinessReportConfig; import com.dianping.cat.configuration.business.entity.CustomConfig; public interface IParser<T> { public BusinessReportConfig parse(IMaker<T> maker, ILinker linker, T node); public void parseForBusinessItemConfig(IMaker<T> maker, ILinker linker, BusinessItemConfig parent, T node); public void parseForCustomConfig(IMaker<T> maker, ILinker linker, CustomConfig parent, T node); }
3e095359f536cee6934242003f33f8d5c5de2c21
1,860
java
Java
polygenesis-generators/polygenesis-generator-java/src/main/java/io/polygenesis/generators/java/domain/aggregateentityid/AggregateEntityIdMethodTransformer.java
polygenesis-projects/polygenesis-platform
68467e6c51314d370e93b26ccb65431818acfa37
[ "Apache-2.0" ]
7
2019-07-17T21:45:21.000Z
2021-01-26T06:35:31.000Z
polygenesis-generators/polygenesis-generator-java/src/main/java/io/polygenesis/generators/java/domain/aggregateentityid/AggregateEntityIdMethodTransformer.java
polygenesis-projects/polygenesis-platform
68467e6c51314d370e93b26ccb65431818acfa37
[ "Apache-2.0" ]
null
null
null
polygenesis-generators/polygenesis-generator-java/src/main/java/io/polygenesis/generators/java/domain/aggregateentityid/AggregateEntityIdMethodTransformer.java
polygenesis-projects/polygenesis-platform
68467e6c51314d370e93b26ccb65431818acfa37
[ "Apache-2.0" ]
2
2020-07-25T17:46:40.000Z
2021-12-17T15:31:30.000Z
39.574468
100
0.572043
3,935
/*- * ==========================LICENSE_START================================= * PolyGenesis Platform * ======================================================================== * Copyright (C) 2015 - 2019 Christos Tsakostas, OREGOR LTD * ======================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ===========================LICENSE_END================================== */ package io.polygenesis.generators.java.domain.aggregateentityid; import io.polygenesis.abstraction.thing.Function; import io.polygenesis.core.DataTypeTransformer; import io.polygenesis.transformers.java.AbstractMethodTransformer; /** * The type Aggregate entity id method transformer. * * @author Christos Tsakostas */ public class AggregateEntityIdMethodTransformer extends AbstractMethodTransformer<Function> { // =============================================================================================== // CONSTRUCTOR(S) // =============================================================================================== /** * Instantiates a new Aggregate entity id method transformer. * * @param dataTypeTransformer the data type transformer */ public AggregateEntityIdMethodTransformer(DataTypeTransformer dataTypeTransformer) { super(dataTypeTransformer); } }
3e0953927b7d99c23a69083dbda392da4254e0a8
6,495
java
Java
src/java/org/apache/cassandra/utils/StreamingHistogram.java
yuvalk/cassandra
5fc9111b6e846093f3f58fc8542dbe8893a46ce6
[ "Apache-2.0" ]
1
2021-11-03T21:13:44.000Z
2021-11-03T21:13:44.000Z
src/java/org/apache/cassandra/utils/StreamingHistogram.java
yuvalk/cassandra
5fc9111b6e846093f3f58fc8542dbe8893a46ce6
[ "Apache-2.0" ]
null
null
null
src/java/org/apache/cassandra/utils/StreamingHistogram.java
yuvalk/cassandra
5fc9111b6e846093f3f58fc8542dbe8893a46ce6
[ "Apache-2.0" ]
null
null
null
32.153465
101
0.564126
3,936
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.utils; import org.apache.cassandra.db.TypeSizes; import org.apache.cassandra.io.ISerializer; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.*; /** * Histogram that can be constructed from streaming of data. * * The algorithm is taken from following paper: * Yael Ben-Haim and Elad Tom-Tov, "A Streaming Parallel Decision Tree Algorithm" (2010) * http://jmlr.csail.mit.edu/papers/volume11/ben-haim10a/ben-haim10a.pdf */ public class StreamingHistogram { public static final StreamingHistogramSerializer serializer = new StreamingHistogramSerializer(); // TreeMap to hold bins of histogram. private final TreeMap<Double, Long> bin; // maximum bin size for this histogram private final int maxBinSize; /** * Creates a new histogram with max bin size of maxBinSize * @param maxBinSize maximum number of bins this histogram can have */ public StreamingHistogram(int maxBinSize) { this.maxBinSize = maxBinSize; bin = new TreeMap<Double, Long>(); } private StreamingHistogram(int maxBinSize, Map<Double, Long> bin) { this.maxBinSize = maxBinSize; this.bin = new TreeMap<Double, Long>(bin); } /** * Adds new point p to this histogram. * @param p */ public void update(double p) { update(p, 1); } /** * Adds new point p with value m to this histogram. * @param p * @param m */ public void update(double p, long m) { Long mi = bin.get(p); if (mi != null) { // we found the same p so increment that counter bin.put(p, mi + m); } else { bin.put(p, m); // if bin size exceeds maximum bin size then trim down to max size while (bin.size() > maxBinSize) { // find points p1, p2 which have smallest difference Iterator<Double> keys = bin.keySet().iterator(); double p1 = keys.next(); double p2 = keys.next(); double smallestDiff = p2 - p1; double q1 = p1, q2 = p2; while (keys.hasNext()) { p1 = p2; p2 = keys.next(); double diff = p2 - p1; if (diff < smallestDiff) { smallestDiff = diff; q1 = p1; q2 = p2; } } // merge those two long k1 = bin.remove(q1); long k2 = bin.remove(q2); bin.put((q1 * k1 + q2 * k2) / (k1 + k2), k1 + k2); } } } /** * Merges given histogram with this histogram. * * @param other histogram to merge */ public void merge(StreamingHistogram other) { if (other == null) return; for (Map.Entry<Double, Long> entry : other.getAsMap().entrySet()) update(entry.getKey(), entry.getValue()); } /** * Calculates estimated number of points in interval [-inf,b]. * * @param b upper bound of a interval to calculate sum * @return estimated number of points in a interval [-inf,b]. */ public double sum(double b) { double sum = 0; // find the points pi, pnext which satisfy pi <= b < pnext Map.Entry<Double, Long> pnext = bin.higherEntry(b); if (pnext == null) { // if b is greater than any key in this histogram, // just count all appearance and return for (Long value : bin.values()) sum += value; } else { Map.Entry<Double, Long> pi = bin.floorEntry(b); if (pi == null) return 0; // calculate estimated count mb for point b double weight = (b - pi.getKey()) / (pnext.getKey() - pi.getKey()); double mb = pi.getValue() + (pnext.getValue() - pi.getValue()) * weight; sum += (pi.getValue() + mb) * weight / 2; sum += pi.getValue() / 2.0; for (Long value : bin.headMap(pi.getKey(), false).values()) sum += value; } return sum; } public Map<Double, Long> getAsMap() { return Collections.unmodifiableMap(bin); } public static class StreamingHistogramSerializer implements ISerializer<StreamingHistogram> { public void serialize(StreamingHistogram histogram, DataOutput dos) throws IOException { dos.writeInt(histogram.maxBinSize); Map<Double, Long> entries = histogram.getAsMap(); dos.writeInt(entries.size()); for (Map.Entry<Double, Long> entry : entries.entrySet()) { dos.writeDouble(entry.getKey()); dos.writeLong(entry.getValue()); } } public StreamingHistogram deserialize(DataInput dis) throws IOException { int maxBinSize = dis.readInt(); int size = dis.readInt(); Map<Double, Long> tmp = new HashMap<Double, Long>(size); for (int i = 0; i < size; i++) { tmp.put(dis.readDouble(), dis.readLong()); } return new StreamingHistogram(maxBinSize, tmp); } public long serializedSize(StreamingHistogram histogram, TypeSizes typeSizes) { throw new UnsupportedOperationException(); } } }
3e09543a441c76f5518c011f8a0c64af8cda1ba3
2,807
java
Java
admin-demo-spring-boot-gradle/shower-application-21/src/main/java/com/example/application/goods/service/impl/AdminGoodsInfoServiceImpl.java
yuan50697105/my-admin-test
62234531ff0913d54783017164382dd85b70e249
[ "Apache-2.0" ]
null
null
null
admin-demo-spring-boot-gradle/shower-application-21/src/main/java/com/example/application/goods/service/impl/AdminGoodsInfoServiceImpl.java
yuan50697105/my-admin-test
62234531ff0913d54783017164382dd85b70e249
[ "Apache-2.0" ]
14
2021-03-10T12:52:37.000Z
2022-03-02T07:58:12.000Z
admin-demo-spring-boot-maven/shower-application-21/src/main/java/com/example/application/goods/service/impl/AdminGoodsInfoServiceImpl.java
yuan50697105/my-admin-test
62234531ff0913d54783017164382dd85b70e249
[ "Apache-2.0" ]
null
null
null
33.416667
87
0.741361
3,937
package com.example.application.goods.service.impl; import cn.hutool.core.util.ObjectUtil; import com.example.application.goods.pojo.info.GoodsInfoSaveRequestBody; import com.example.application.goods.pojo.info.GoodsInfoUpdateRequestBody; import com.example.application.goods.service.AdminGoodsInfoService; import com.example.commons.db.mybatis.plus.pagehelper.module.pojo.GoodsInfo; import com.example.commons.db.mybatis.plus.pagehelper.module.pojo.query.GoodsInfoQuery; import com.example.commons.db.mybatis.plus.pagehelper.module.service.GoodsInfoService; import com.example.commons.web.base.exception.ResultRuntimeException; import com.example.commons.web.base.pojo.Result; import com.example.commons.web.base.utils.ResultUtils; import com.example.commons.db.pojo.IPageResult; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @program: admin-demo-gradle * @description: * @author: yuane * @create: 2020-04-11 12:54 */ @Service @AllArgsConstructor public class AdminGoodsInfoServiceImpl implements AdminGoodsInfoService { private final GoodsInfoService goodsInfoService; @Override public Result data(GoodsInfoQuery query) { IPageResult<GoodsInfo> goodsInfos = goodsInfoService.selectPageByQuery(query); return ResultUtils.data(goodsInfos); } @Override public Result list(GoodsInfoQuery query) { List<GoodsInfo> list = goodsInfoService.selectByQuery(query); return ResultUtils.data("list", list); } @Override public Result get(Long id) { GoodsInfo goodsInfo = goodsInfoService.getById(id); return ResultUtils.data("goodsInfo", goodsInfo); } @Override @Transactional public Result save(GoodsInfoSaveRequestBody requestBody) { GoodsInfo goodsInfo = new GoodsInfo(); goodsInfo.copyFrom(requestBody); goodsInfoService.save(goodsInfo); return ResultUtils.saveOk(); } @Override @Transactional public Result update(GoodsInfoUpdateRequestBody requestBody) { GoodsInfo goodsInfo = goodsInfoService.getById(requestBody.getId()); if (ObjectUtil.isEmpty(goodsInfo)) { throw new ResultRuntimeException(ResultUtils.infoNotExistError()); } goodsInfo.copyFrom(requestBody); goodsInfoService.updateById(goodsInfo); return ResultUtils.updateOk(); } @Override @Transactional public Result delete(Long id) { goodsInfoService.removeById(id); return ResultUtils.deleteOk(); } @Override @Transactional public Result delete(List<Long> ids) { goodsInfoService.removeByIds(ids); return ResultUtils.deleteOk(); } }
3e095457c303fe16ff794e516dfda58a2654e131
5,467
java
Java
aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/transform/MethodJsonUnmarshaller.java
ericvincent83/aws-sdk-java
c491416f3ea9411a04d9bafedee6c6874a79e48d
[ "Apache-2.0" ]
3,372
2015-01-03T00:35:43.000Z
2022-03-31T15:56:24.000Z
aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/transform/MethodJsonUnmarshaller.java
ericvincent83/aws-sdk-java
c491416f3ea9411a04d9bafedee6c6874a79e48d
[ "Apache-2.0" ]
2,391
2015-01-01T12:55:24.000Z
2022-03-31T08:01:50.000Z
aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/transform/MethodJsonUnmarshaller.java
ericvincent83/aws-sdk-java
c491416f3ea9411a04d9bafedee6c6874a79e48d
[ "Apache-2.0" ]
2,876
2015-01-01T14:38:37.000Z
2022-03-29T19:53:10.000Z
45.558333
159
0.615694
3,938
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.apigateway.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.apigateway.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * Method JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class MethodJsonUnmarshaller implements Unmarshaller<Method, JsonUnmarshallerContext> { public Method unmarshall(JsonUnmarshallerContext context) throws Exception { Method method = new Method(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("httpMethod", targetDepth)) { context.nextToken(); method.setHttpMethod(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("authorizationType", targetDepth)) { context.nextToken(); method.setAuthorizationType(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("authorizerId", targetDepth)) { context.nextToken(); method.setAuthorizerId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("apiKeyRequired", targetDepth)) { context.nextToken(); method.setApiKeyRequired(context.getUnmarshaller(Boolean.class).unmarshall(context)); } if (context.testExpression("requestValidatorId", targetDepth)) { context.nextToken(); method.setRequestValidatorId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("operationName", targetDepth)) { context.nextToken(); method.setOperationName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("requestParameters", targetDepth)) { context.nextToken(); method.setRequestParameters(new MapUnmarshaller<String, Boolean>(context.getUnmarshaller(String.class), context .getUnmarshaller(Boolean.class)).unmarshall(context)); } if (context.testExpression("requestModels", targetDepth)) { context.nextToken(); method.setRequestModels(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context.getUnmarshaller(String.class)) .unmarshall(context)); } if (context.testExpression("methodResponses", targetDepth)) { context.nextToken(); method.setMethodResponses(new MapUnmarshaller<String, MethodResponse>(context.getUnmarshaller(String.class), MethodResponseJsonUnmarshaller .getInstance()).unmarshall(context)); } if (context.testExpression("methodIntegration", targetDepth)) { context.nextToken(); method.setMethodIntegration(IntegrationJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("authorizationScopes", targetDepth)) { context.nextToken(); method.setAuthorizationScopes(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)) .unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return method; } private static MethodJsonUnmarshaller instance; public static MethodJsonUnmarshaller getInstance() { if (instance == null) instance = new MethodJsonUnmarshaller(); return instance; } }
3e09547ef4ce2b8c995ffc6622ef35e5c0ecf56f
1,503
java
Java
BingoServer/src/bingoserver/repositories/RepositoryManager.java
ValmirJ/Projeto-Integrado-3---Bingo
1fca94d2ed73d927fcfd26ff9e854a5eadda1e10
[ "MIT" ]
null
null
null
BingoServer/src/bingoserver/repositories/RepositoryManager.java
ValmirJ/Projeto-Integrado-3---Bingo
1fca94d2ed73d927fcfd26ff9e854a5eadda1e10
[ "MIT" ]
null
null
null
BingoServer/src/bingoserver/repositories/RepositoryManager.java
ValmirJ/Projeto-Integrado-3---Bingo
1fca94d2ed73d927fcfd26ff9e854a5eadda1e10
[ "MIT" ]
null
null
null
27.833333
93
0.676647
3,939
/* * 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 bingoserver.repositories; import java.sql.Connection; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author 15096134 */ public class RepositoryManager { private final RoomRepository roomRepo = new RoomRepository(); private final UserRepository userRepo = new UserRepository(); private final UserCardRepository userCardRepo = new UserCardRepository(); private final CardRepository cardRepository; private final Connection dbConnection; public RepositoryManager() throws Exception { dbConnection = DbConnectionBuilder.getNewConnection(); cardRepository = new CardRepository(dbConnection); } public RoomRepository getRoomRepository() { return roomRepo; } public CardRepository getCardRepository() { return cardRepository; } public UserCardRepository getUserCardRepository() { return userCardRepo; } public UserRepository getUserRepository() { return userRepo; } public void close() { try { dbConnection.close(); } catch (SQLException ex) { Logger.getLogger(RepositoryManager.class.getName()).log(Level.SEVERE, null, ex); } } }
3e0954915b9dca3663133f716783797804d344b5
927
java
Java
src/main/java/ch/so/agi/oereb/webclient/client/SearchResult.java
edigonzales/oereb-client-gwt
44bc621fc0122d7e51062e72388a90a01451721d
[ "MIT" ]
null
null
null
src/main/java/ch/so/agi/oereb/webclient/client/SearchResult.java
edigonzales/oereb-client-gwt
44bc621fc0122d7e51062e72388a90a01451721d
[ "MIT" ]
15
2019-09-24T13:45:18.000Z
2020-01-03T15:28:22.000Z
src/main/java/ch/so/agi/oereb/webclient/client/SearchResult.java
edigonzales/oereb-client-gwt
44bc621fc0122d7e51062e72388a90a01451721d
[ "MIT" ]
null
null
null
23.769231
56
0.659115
3,940
package ch.so.agi.oereb.webclient.client; import java.io.Serializable; public class SearchResult implements Serializable { private String display; private String dataproductId; private String featureId; private String idFieldName; public String getDisplay() { return display; } public void setDisplay(String display) { this.display = display; } public String getDataproductId() { return dataproductId; } public void setDataproductId(String dataproductId) { this.dataproductId = dataproductId; } public String getFeatureId() { return featureId; } public void setFeatureId(String featureId) { this.featureId = featureId; } public String getIdFieldName() { return idFieldName; } public void setIdFieldName(String idFieldName) { this.idFieldName = idFieldName; } }
3e09549467158707eca3f2ab708b878c6898d5e7
213
java
Java
app/src/main/java/com/example/wanghaishu/coolweather/util/HttpCallbackListener.java
Developerwhs/CoolWeather
1799ebf645a097daa1a72a717782a5f894cf5ff0
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/wanghaishu/coolweather/util/HttpCallbackListener.java
Developerwhs/CoolWeather
1799ebf645a097daa1a72a717782a5f894cf5ff0
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/wanghaishu/coolweather/util/HttpCallbackListener.java
Developerwhs/CoolWeather
1799ebf645a097daa1a72a717782a5f894cf5ff0
[ "Apache-2.0" ]
null
null
null
16.384615
48
0.694836
3,941
package com.example.wanghaishu.coolweather.util; /** * @创建者 WHS * @创建时间 2017/06/29 18:02 * @描述 */ public interface HttpCallbackListener { void onFinish(String response); void onError(Exception e); }
3e095647aedc5d967758a4a29bc4a179b1e62d0d
4,351
java
Java
src/test/java/org/apache/ibatis/submitted/flush_statement_npe/FlushStatementNpeTest.java
boooluo/mybatis
0483a1dcbe92e2d226ab045420f41a85e01d6c04
[ "Apache-2.0" ]
4,200
2015-01-30T09:44:15.000Z
2022-03-31T14:57:14.000Z
src/test/java/org/apache/ibatis/submitted/flush_statement_npe/FlushStatementNpeTest.java
duanyu1106/mybatis
682b435453a7694328ad3064685470e16a72d284
[ "Apache-2.0" ]
14
2017-03-20T10:10:47.000Z
2021-12-14T21:09:34.000Z
src/test/java/org/apache/ibatis/submitted/flush_statement_npe/FlushStatementNpeTest.java
duanyu1106/mybatis
682b435453a7694328ad3064685470e16a72d284
[ "Apache-2.0" ]
2,357
2015-01-30T09:44:57.000Z
2022-03-31T08:16:34.000Z
35.958678
122
0.631349
3,942
/* * Copyright 2009-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.submitted.flush_statement_npe; import java.io.Reader; import java.sql.Connection; import java.sql.DriverManager; import org.apache.ibatis.io.Resources; import org.apache.ibatis.jdbc.ScriptRunner; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.BeforeClass; import org.junit.Test; public class FlushStatementNpeTest { private static SqlSessionFactory sqlSessionFactory; @BeforeClass public static void initDatabase() throws Exception { Connection conn = null; try { Class.forName("org.hsqldb.jdbcDriver"); conn = DriverManager.getConnection("jdbc:hsqldb:mem:flush_statement_npe", "sa", ""); Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/flush_statement_npe/CreateDB.sql"); ScriptRunner runner = new ScriptRunner(conn); runner.setLogWriter(null); runner.setErrorLogWriter(null); runner.runScript(reader); conn.commit(); reader.close(); reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/flush_statement_npe/ibatisConfig.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); reader.close(); } finally { if (conn != null) { conn.close(); } } } @Test public void testSameUpdateAfterCommitSimple() { SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.SIMPLE); try { PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class); Person person = personMapper.selectById(1); person.setFirstName("Simone"); // Execute first update then commit. personMapper.update(person); sqlSession.commit(); // Execute same update a second time. This used to raise an NPE. personMapper.update(person); sqlSession.commit(); } finally { sqlSession.close(); } } @Test public void testSameUpdateAfterCommitReuse() { SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.REUSE); try { PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class); Person person = personMapper.selectById(1); person.setFirstName("Simone"); // Execute first update then commit. personMapper.update(person); sqlSession.commit(); // Execute same update a second time. This used to raise an NPE. personMapper.update(person); sqlSession.commit(); } finally { sqlSession.close(); } } @Test public void testSameUpdateAfterCommitBatch() { SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH); try { PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class); Person person = personMapper.selectById(1); person.setFirstName("Simone"); // Execute first update then commit. personMapper.update(person); sqlSession.commit(); // Execute same update a second time. This used to raise an NPE. personMapper.update(person); sqlSession.commit(); } finally { sqlSession.close(); } } }
3e09568c089461563978070d9683bcc11b184103
276
java
Java
backendyeb/yeb-server/src/main/java/com/xxxx/server/service/IMailLogService.java
OriginalCoder0/endyeb
eb5e3b891f8cd88c0f7e52ae72153d1a374f6e6b
[ "Apache-2.0" ]
null
null
null
backendyeb/yeb-server/src/main/java/com/xxxx/server/service/IMailLogService.java
OriginalCoder0/endyeb
eb5e3b891f8cd88c0f7e52ae72153d1a374f6e6b
[ "Apache-2.0" ]
null
null
null
backendyeb/yeb-server/src/main/java/com/xxxx/server/service/IMailLogService.java
OriginalCoder0/endyeb
eb5e3b891f8cd88c0f7e52ae72153d1a374f6e6b
[ "Apache-2.0" ]
null
null
null
16.235294
60
0.717391
3,943
package com.xxxx.server.service; import com.baomidou.mybatisplus.extension.service.IService; import com.xxxx.server.pojo.MailLog; /** * <p> * 服务类 * </p> * * @author OriginalCoder * @since 2021-02-03 */ public interface IMailLogService extends IService<MailLog> { }
3e09586e494594151024802b86e4926dac34dec2
3,590
java
Java
main/plugins/org.talend.repository/src/main/java/org/talend/repository/model/migration/SetDefaultValue4tWriteJSONFieldGroupByOutput.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
114
2015-03-05T15:34:59.000Z
2022-02-22T03:48:44.000Z
main/plugins/org.talend.repository/src/main/java/org/talend/repository/model/migration/SetDefaultValue4tWriteJSONFieldGroupByOutput.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
1,137
2015-03-04T01:35:42.000Z
2022-03-29T06:03:17.000Z
main/plugins/org.talend.repository/src/main/java/org/talend/repository/model/migration/SetDefaultValue4tWriteJSONFieldGroupByOutput.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
219
2015-01-21T10:42:18.000Z
2022-02-17T07:57:20.000Z
43.780488
130
0.649304
3,944
package org.talend.repository.model.migration; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import org.eclipse.emf.common.util.EList; import org.talend.commons.exception.ExceptionHandler; import org.talend.commons.exception.PersistenceException; import org.talend.core.model.components.ComponentUtilities; import org.talend.core.model.components.ModifyComponentsAction; import org.talend.core.model.components.conversions.IComponentConversion; import org.talend.core.model.components.filters.IComponentFilter; import org.talend.core.model.components.filters.NameComponentFilter; import org.talend.core.model.migration.AbstractJobMigrationTask; import org.talend.core.model.properties.Item; import org.talend.core.model.repository.ERepositoryObjectType; import org.talend.designer.core.model.utils.emf.talendfile.ElementValueType; import org.talend.designer.core.model.utils.emf.talendfile.NodeType; import org.talend.designer.core.model.utils.emf.talendfile.ProcessType; import org.talend.designer.core.model.utils.emf.talendfile.TalendFileFactory; public class SetDefaultValue4tWriteJSONFieldGroupByOutput extends AbstractJobMigrationTask { public List<ERepositoryObjectType> getTypes() { List<ERepositoryObjectType> toReturn = new ArrayList<ERepositoryObjectType>(); ERepositoryObjectType mrtype = ERepositoryObjectType.getType("PROCESS_MR"); //$NON-NLS-1$ ERepositoryObjectType ditype = ERepositoryObjectType.getType("PROCESS"); //$NON-NLS-1$ if (mrtype != null) { toReturn.add(mrtype); } if (ditype != null) { toReturn.add(ditype); } return toReturn; } @Override public Date getOrder() { return new GregorianCalendar(2014, 9, 23, 16, 0, 0).getTime(); } @Override public ExecutionResult execute(Item item) { ProcessType processType = getProcessType(item); IComponentFilter filter = new NameComponentFilter("tWriteJSONField"); try { ModifyComponentsAction.searchAndModify(item, processType, filter, Arrays.<IComponentConversion> asList(new IComponentConversion() { public void transform(NodeType node) { EList<ElementValueType> list = ComponentUtilities.getNodeProperty(node, "GROUPBYS").getElementValue(); ElementValueType outputColumnPropertyElement = null; int size = list.size(); if (list != null && size > 0) { String outputFieldValue = ComponentUtilities.getNodeProperty(node, "JSONFIELD").getValue(); for (int i = 0, j = 0; i < size; i++) { outputColumnPropertyElement = TalendFileFactory.eINSTANCE.createElementValueType(); outputColumnPropertyElement.setElementRef("OUTPUT_COLUMN"); //$NON-NLS-1$ outputColumnPropertyElement.setValue(outputFieldValue); list.add(j, outputColumnPropertyElement); j = j + 2; } } } })); } catch (PersistenceException e) { ExceptionHandler.process(e); return ExecutionResult.FAILURE; } return ExecutionResult.SUCCESS_NO_ALERT; } }
3e095881212bdd34360047fcf0b05488c02a6a76
188
java
Java
library/src/main/java/com/tmlab/amalgamj/Version.java
amalgam-blockchain/amalgam-java
49a99a2664dac447c93890938e0950cfa35aea51
[ "MIT" ]
null
null
null
library/src/main/java/com/tmlab/amalgamj/Version.java
amalgam-blockchain/amalgam-java
49a99a2664dac447c93890938e0950cfa35aea51
[ "MIT" ]
null
null
null
library/src/main/java/com/tmlab/amalgamj/Version.java
amalgam-blockchain/amalgam-java
49a99a2664dac447c93890938e0950cfa35aea51
[ "MIT" ]
null
null
null
18.8
37
0.755319
3,945
package com.tmlab.amalgamj; public class Version { public String blockchain_version; public String amalgam_revision; public String fc_revision; public String chain_id; }
3e0958f2c3640e792865fbe9d9315c4207425286
1,072
java
Java
src/main/java/com/kissthinker/coder/JMSCoder.java
davidainslie/java-kissthinker
c8a29e95a110197c40bd09b1891bf918da1c357a
[ "MIT" ]
null
null
null
src/main/java/com/kissthinker/coder/JMSCoder.java
davidainslie/java-kissthinker
c8a29e95a110197c40bd09b1891bf918da1c357a
[ "MIT" ]
null
null
null
src/main/java/com/kissthinker/coder/JMSCoder.java
davidainslie/java-kissthinker
c8a29e95a110197c40bd09b1891bf918da1c357a
[ "MIT" ]
null
null
null
26.8
155
0.648321
3,946
package com.kissthinker.coder; /** * A {@link Coder} for the publish/subscribe paradigm. * * This {@link Coder} is specifically for interactions via Publisher which uses, as part of its "subscribe" methods, Function for callbacks. * Appropriate implementation regarding pub/sub is JMS. * @author David Ainslie * */ @Deprecated // TODO Only at the moment because I want to implement JMS and had an idea with this and class JMSRegistry, but the idea has currently left me. public class JMSCoder extends JsonCoder { /** */ public JMSCoder() { super(); } /** * @see com.kissthinker.coder.JsonCoder#decode(byte[]) */ @SuppressWarnings("unchecked") @Override public <O> O decode(byte[] bytes) { // TODO Auto-generated method stub return (O)super.decode(bytes); } /** * @see com.kissthinker.coder.JsonCoder#encode(java.lang.Object) */ @Override public <O> byte[] encode(O object) { // TODO Auto-generated method stub return super.encode(object); } }
3e095a434d16df5c0a96516aa3a1b73554094d85
1,628
java
Java
google-api-grpc/proto-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/OriginalDetectIntentRequestOrBuilder.java
charlesliqlogic/google-cloud-java
2aa9d803ed532d91a5f430368f1ec4fd21f3dd24
[ "Apache-2.0" ]
1
2017-07-13T19:33:17.000Z
2017-07-13T19:33:17.000Z
google-api-grpc/proto-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/OriginalDetectIntentRequestOrBuilder.java
charlesliqlogic/google-cloud-java
2aa9d803ed532d91a5f430368f1ec4fd21f3dd24
[ "Apache-2.0" ]
null
null
null
google-api-grpc/proto-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/OriginalDetectIntentRequestOrBuilder.java
charlesliqlogic/google-cloud-java
2aa9d803ed532d91a5f430368f1ec4fd21f3dd24
[ "Apache-2.0" ]
1
2019-02-01T22:12:05.000Z
2019-02-01T22:12:05.000Z
23.941176
105
0.632064
3,947
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/v2/webhook.proto package com.google.cloud.dialogflow.v2; public interface OriginalDetectIntentRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.dialogflow.v2.OriginalDetectIntentRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The source of this request, e.g., `google`, `facebook`, `slack`. It is set * by Dialogflow-owned servers. * </pre> * * <code>string source = 1;</code> */ java.lang.String getSource(); /** * * * <pre> * The source of this request, e.g., `google`, `facebook`, `slack`. It is set * by Dialogflow-owned servers. * </pre> * * <code>string source = 1;</code> */ com.google.protobuf.ByteString getSourceBytes(); /** * * * <pre> * Optional. This field is set to the value of `QueryParameters.payload` field * passed in the request. * </pre> * * <code>.google.protobuf.Struct payload = 3;</code> */ boolean hasPayload(); /** * * * <pre> * Optional. This field is set to the value of `QueryParameters.payload` field * passed in the request. * </pre> * * <code>.google.protobuf.Struct payload = 3;</code> */ com.google.protobuf.Struct getPayload(); /** * * * <pre> * Optional. This field is set to the value of `QueryParameters.payload` field * passed in the request. * </pre> * * <code>.google.protobuf.Struct payload = 3;</code> */ com.google.protobuf.StructOrBuilder getPayloadOrBuilder(); }
3e095a534d31d6b9df50d83ed0c46cc031fe49b7
14,193
java
Java
JavaSource/org/unitime/timetable/onlinesectioning/OnlineSectioningLogger.java
avilaton/unitime
e2daa8d78fa3175c9ae507d9c16607926245da84
[ "Apache-2.0" ]
3
2016-02-12T07:09:03.000Z
2021-04-02T13:24:34.000Z
JavaSource/org/unitime/timetable/onlinesectioning/OnlineSectioningLogger.java
avilaton/unitime
e2daa8d78fa3175c9ae507d9c16607926245da84
[ "Apache-2.0" ]
null
null
null
JavaSource/org/unitime/timetable/onlinesectioning/OnlineSectioningLogger.java
avilaton/unitime
e2daa8d78fa3175c9ae507d9c16607926245da84
[ "Apache-2.0" ]
null
null
null
41.5
219
0.652364
3,948
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation 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.unitime.timetable.onlinesectioning; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.Hashtable; import java.util.List; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.CacheMode; import org.unitime.localization.impl.Localization; import org.unitime.timetable.defaults.ApplicationProperty; import org.unitime.timetable.gwt.resources.StudentSectioningConstants; import org.unitime.timetable.gwt.server.DayCode; import org.unitime.timetable.model.Session; import org.unitime.timetable.model.Student; import org.unitime.timetable.model.dao.OnlineSectioningLogDAO; import org.unitime.timetable.model.dao.SessionDAO; import org.unitime.timetable.model.dao.StudentDAO; /** * @author Tomas Muller */ public class OnlineSectioningLogger extends Thread { private static Log sLog = LogFactory.getLog(OnlineSectioningLogger.class); protected static StudentSectioningConstants CONST = Localization.create(StudentSectioningConstants.class); private List<OnlineSectioningLog.Action> iActions = new Vector<OnlineSectioningLog.Action>(); private boolean iActive = false; private boolean iEnabled = false; private int iLogLimit = -1; private PrintWriter iOut = null; private static OnlineSectioningLogger sInstance = null; public static OnlineSectioningLogger getInstance() { if (sInstance == null) startLogger(); return sInstance; } public static void startLogger() { if (sInstance == null) { sInstance = new OnlineSectioningLogger(); sInstance.start(); } } public static void stopLogger() { if (sInstance != null) { sInstance.iActive = false; sInstance.interrupt(); try { sInstance.join(); } catch (InterruptedException e) {} sInstance = null; } } private OnlineSectioningLogger() { super("OnlineSectioningLogger"); setDaemon(true); iEnabled = ApplicationProperty.OnlineSchedulingLoggingEnabled.isTrue(); iLogLimit = ApplicationProperty.OnlineSchedulingLogLimit.intValue(); try { if (ApplicationProperty.OnlineSchedulingLogFile.value() != null) iOut = new PrintWriter(new FileWriter(new File(ApplicationProperty.OnlineSchedulingLogFile.value()), true)); } catch (IOException e) { sLog.warn("Unable to create sectioning log: " + e.getMessage(), e); } } public boolean isEnabled() { return iEnabled; } public void setEnabled(boolean enabled) { iEnabled = enabled; } public boolean isActive() { return iActive; } public void record(OnlineSectioningLog.Log log) { if (log == null || !isEnabled() || !isActive()) return; for (OnlineSectioningLog.Action action: log.getActionList()) { if (action.hasStartTime() && action.hasStudent() && action.hasOperation() && action.hasSession() && ApplicationProperty.OnlineSchedulingLogOperation.isTrue(action.getOperation()) && ApplicationProperty.OnlineSchedulingLogOperation.isTrue(action.getOperation() + "." + (action.hasResult() ? action.getResult().name() : "NULL"))) { synchronized (iActions) { if (iLogLimit <= 0 || iActions.size() < iLogLimit) iActions.add(action); } if (iOut != null) { synchronized (iOut) { iOut.print(OnlineSectioningLog.Log.newBuilder().addAction(action).build().toString()); iOut.flush(); } } } } } protected static String getRequestMessage(OnlineSectioningLog.Action action) { String request = ""; int notAlt = 0, lastFT = -1; for (OnlineSectioningLog.Request r: (action.getRequestCount() > 0 ? action.getRequestList() : action.getRecommendationList())) { if (!r.getAlternative()) notAlt = r.getPriority() + 1; int idx = 0; for (OnlineSectioningLog.Time f: r.getFreeTimeList()) { if (idx == 0) { request += (lastFT == r.getPriority() ? ", " : (request.isEmpty() ? "" : "\n") + (r.getAlternative() ? "A" + (1 + r.getPriority() - notAlt) : String.valueOf(1 + r.getPriority())) + ". " + CONST.freePrefix() + " "); } else { request += ", "; } idx++; request += DayCode.toString(f.getDays()) + " " + time(f.getStart()) + " - " + time(f.getStart() + f.getLength()); lastFT = r.getPriority(); } if (r.getFreeTimeList().isEmpty()) { for (OnlineSectioningLog.Entity e: r.getCourseList()) { if (idx == 0) { request += (request.isEmpty() ? "" : "\n") + (r.getAlternative() ? "A" + (1 + r.getPriority() - notAlt) : String.valueOf(1 + r.getPriority())) + ". "; } else { request += ", "; } idx++; request += e.getName(); } if (r.getWaitList()) request += " (w)"; else if (r.getNoSubs()) request += " (s)"; } } return request; } protected static String getSelectedMessage(OnlineSectioningLog.Action action) { String selected = ""; for (OnlineSectioningLog.Request r: action.getRequestList()) { for (OnlineSectioningLog.Section s: r.getSectionList()) { if (s.getPreference() == OnlineSectioningLog.Section.Preference.SELECTED) { if (!selected.isEmpty()) selected += "\n"; String loc = ""; for (OnlineSectioningLog.Entity e: s.getLocationList()) { if (!loc.isEmpty()) loc += ", "; loc += e.getName(); } String instr = ""; for (OnlineSectioningLog.Entity e: s.getInstructorList()) { if (!instr.isEmpty()) instr += ", "; instr += e.getName(); } selected += s.getCourse().getName() + " " + s.getSubpart().getName() + " " + s.getClazz().getName() + " " + (s.hasTime() ? DayCode.toString(s.getTime().getDays()) + " " + time(s.getTime().getStart()) + " - " + time(s.getTime().getStart() + s.getTime().getLength()) : "") + " " + loc; } } } return selected; } protected static String getEnrollmentMessage(OnlineSectioningLog.Action action) { OnlineSectioningLog.Enrollment enrl = null; for (OnlineSectioningLog.Enrollment e: action.getEnrollmentList()) { enrl = e; if ("check-offering".equals(action.getOperation()) && e.getType() == OnlineSectioningLog.Enrollment.EnrollmentType.COMPUTED) break; if ("reload-offering".equals(action.getOperation()) && e.getType() == OnlineSectioningLog.Enrollment.EnrollmentType.COMPUTED) break; if (e.getType() == OnlineSectioningLog.Enrollment.EnrollmentType.REQUESTED) break; } String enrollment = ""; if (enrl != null) for (OnlineSectioningLog.Section s: enrl.getSectionList()) { if (!s.hasCourse()) continue; if (!enrollment.isEmpty()) enrollment += "\n"; String loc = ""; for (OnlineSectioningLog.Entity r: s.getLocationList()) { if (!loc.isEmpty()) loc += ", "; loc += r.getName(); } String instr = ""; for (OnlineSectioningLog.Entity r: s.getInstructorList()) { if (!instr.isEmpty()) instr += ", "; instr += r.getName(); } enrollment += s.getCourse().getName() + " " + s.getSubpart().getName() + " " + s.getClazz().getName() + " " + (s.hasTime() ? DayCode.toString(s.getTime().getDays()) + " " + time(s.getTime().getStart()) : "") + " " + loc; } return enrollment; } public static String getMessage(OnlineSectioningLog.Action action) { String message = ""; int level = 1; for (OnlineSectioningLog.Message m: action.getMessageList()) { if (!m.hasLevel()) continue; // skip messages with no level if (!message.isEmpty() && level > m.getLevel().getNumber()) continue; // if we have a message, ignore messages with lower level if (m.hasText()) { message = (level != m.getLevel().getNumber() || message.isEmpty() ? "" : message + "\n") + m.getText(); level = m.getLevel().getNumber(); } else if (m.hasException()) { message = (level != m.getLevel().getNumber() || message.isEmpty() ? "" : message + "\n") + m.getException(); level = m.getLevel().getNumber(); } } if (action.hasResult() && OnlineSectioningLog.Action.ResultType.FAILURE.equals(action.getResult()) && !message.isEmpty()) { return message; } else if ("suggestions".equals(action.getOperation())) { String selected = getSelectedMessage(action); return (selected.isEmpty() ? message : selected); } else if ("section".equals(action.getOperation())) { String request = getRequestMessage(action); return (request.isEmpty() ? message : request); } else if ("check-offering".equals(action.getOperation()) && action.hasResult() && !OnlineSectioningLog.Action.ResultType.SUCCESS.equals(action.getResult()) && !message.isEmpty()) { return message; } else if ("reload-offering".equals(action.getOperation()) && action.hasResult() && !OnlineSectioningLog.Action.ResultType.SUCCESS.equals(action.getResult()) && !message.isEmpty()) { return message; } else { String enrollment = getEnrollmentMessage(action); if (!enrollment.isEmpty()) return enrollment; String request = getRequestMessage(action); return (request.isEmpty() ? message : request); } } protected static String time(int slot) { int h = slot / 12; int m = 5 * (slot % 12); if (CONST.useAmPm()) return (h > 12 ? h - 12 : h) + ":" + (m < 10 ? "0" : "") + m + (h == 24 ? "a" : h >= 12 ? "p" : "a"); else return h + ":" + (m < 10 ? "0" : "") + m; } public void run() { sLog.info("Online Sectioning Logger is up."); try { iActive = true; while (true) { try { sleep(60000); } catch (InterruptedException e) { } List<OnlineSectioningLog.Action> actionsToSave = null; synchronized (iActions) { if (!iActions.isEmpty()) { actionsToSave = new ArrayList<OnlineSectioningLog.Action>(iActions); iActions.clear(); } } try { if (actionsToSave != null) { sLog.debug("Persisting " + actionsToSave.size() + " actions..."); if (iLogLimit > 0 && actionsToSave.size() >= iLogLimit) sLog.warn("The limit of " + iLogLimit + " unpersisted log messages was reached, some messages have been dropped."); org.hibernate.Session hibSession = OnlineSectioningLogDAO.getInstance().createNewSession(); hibSession.setCacheMode(CacheMode.IGNORE); try { Hashtable<Long, Session> sessions = new Hashtable<Long, Session>(); for (OnlineSectioningLog.Action q: actionsToSave) { org.unitime.timetable.model.OnlineSectioningLog log = new org.unitime.timetable.model.OnlineSectioningLog(); log.setAction(q.toByteArray()); log.setOperation(q.getOperation()); String studentExternalId = (q.getStudent().hasExternalId() ? q.getStudent().getExternalId() : null); if (studentExternalId == null || studentExternalId.isEmpty()) { Student student = StudentDAO.getInstance().get(q.getStudent().getUniqueId(), hibSession); if (student == null) continue; studentExternalId = student.getExternalUniqueId(); } log.setStudent(studentExternalId); log.setTimeStamp(new Date(q.getStartTime())); if (q.hasResult()) log.setResult(q.getResult().getNumber()); if (q.hasUser() && q.getUser().hasExternalId()) log.setUser(q.getUser().getExternalId()); if (q.hasCpuTime()) log.setCpuTime(q.getCpuTime()); if (q.hasStartTime() && q.hasEndTime()) log.setWallTime(q.getEndTime() - q.getStartTime()); if (q.hasApiGetTime()) log.setApiGetTime(q.getApiGetTime()); if (q.hasApiPostTime()) log.setApiPostTime(q.getApiPostTime()); if (q.hasApiException()) log.setApiException(q.getApiException() != null && q.getApiException().length() > 255 ? q.getApiException().substring(0, 255) : q.getApiException()); try { String message = getMessage(q); if (message != null && !message.isEmpty()) log.setMessage(message.length() > 255 ? message.substring(0, 252) + "..." : message); } catch (Exception e) { if (!q.getMessageList().isEmpty()) { String message = null; int level = 0; for (OnlineSectioningLog.Message m: q.getMessageList()) { if (message != null && !message.isEmpty() && (!m.hasLevel() || level > m.getLevel().getNumber())) continue; if (m.hasText()) { message = m.getText(); level = m.getLevel().getNumber(); } else if (m.hasException()) { message = m.getException(); level = m.getLevel().getNumber(); } } if (message != null && !message.isEmpty()) log.setMessage(message.length() > 255 ? message.substring(0, 252) + "..." : message); } } Long sessionId = q.getSession().getUniqueId(); Session session = sessions.get(sessionId); if (session == null) { session = SessionDAO.getInstance().get(sessionId, hibSession); sessions.put(sessionId, session); } log.setSession(session); hibSession.save(log); } hibSession.flush(); } finally { hibSession.close(); } } } catch (Throwable t) { sLog.warn("Failed to save " + actionsToSave.size() + " log actions: " + t.getMessage(), t); } if (!iActive) break; } } catch (Throwable t) { sLog.error("Online Sectioning Logger failed: " + t.getMessage(), t); } finally { iActive = false; if (iOut != null) { iOut.flush(); iOut.close(); } } sLog.info("Online Sectioning Logger is down."); } }
3e095ac1e27512c23da2771e2970ee59fae99db2
1,979
java
Java
net/arikia/dev/drpc/DiscordEventHandlers.java
kisman2000/RailHack-Ratted-
6e9854b45e95a2b97534958a91193e07e1690059
[ "MIT" ]
3
2021-10-16T12:53:20.000Z
2022-02-02T16:02:40.000Z
net/arikia/dev/drpc/DiscordEventHandlers.java
kisman2000/RailHack-Ratted-
6e9854b45e95a2b97534958a91193e07e1690059
[ "MIT" ]
2
2021-11-07T12:23:26.000Z
2022-02-08T18:32:17.000Z
net/arikia/dev/drpc/DiscordEventHandlers.java
kisman2000/RailHack-Ratted-
6e9854b45e95a2b97534958a91193e07e1690059
[ "MIT" ]
2
2021-10-16T12:53:21.000Z
2022-02-08T05:45:55.000Z
29.537313
177
0.623042
3,949
//Deobfuscated with https://github.com/SimplyProgrammer/Minecraft-Deobfuscator3000 using mappings "C:\Users\Admin\Desktop\Minecraft-Deobfuscator3000-1.2.2\1.12 stable mappings"! //Decompiled by Procyon! package net.arikia.dev.drpc; import com.sun.jna.*; import net.arikia.dev.drpc.callbacks.*; import java.util.*; public class DiscordEventHandlers extends Structure { public ReadyCallback ready; public DisconnectedCallback disconnected; public ErroredCallback errored; public JoinGameCallback joinGame; public SpectateGameCallback spectateGame; public JoinRequestCallback joinRequest; public List<String> getFieldOrder() { return Arrays.asList("ready", "disconnected", "errored", "joinGame", "spectateGame", "joinRequest"); } public static class Builder { DiscordEventHandlers h; public Builder() { this.h = new DiscordEventHandlers(); } public Builder setReadyEventHandler(final ReadyCallback r) { this.h.ready = r; return this; } public Builder setDisconnectedEventHandler(final DisconnectedCallback d) { this.h.disconnected = d; return this; } public Builder setErroredEventHandler(final ErroredCallback e) { this.h.errored = e; return this; } public Builder setJoinGameEventHandler(final JoinGameCallback j) { this.h.joinGame = j; return this; } public Builder setSpectateGameEventHandler(final SpectateGameCallback s) { this.h.spectateGame = s; return this; } public Builder setJoinRequestEventHandler(final JoinRequestCallback j) { this.h.joinRequest = j; return this; } public DiscordEventHandlers build() { return this.h; } } }
3e095b577383a8fa46ab72c20bf2ac17e4b1b73c
3,168
java
Java
waltz-jobs/src/main/java/org/finos/waltz/jobs/generators/EndUserAppInvolvmentGenerator.java
jgiannuzzi/waltz
06968e5b424e3dae233390c8657469b0705fd6c3
[ "Apache-2.0" ]
77
2016-06-17T11:01:16.000Z
2020-02-28T04:00:31.000Z
waltz-jobs/src/main/java/org/finos/waltz/jobs/generators/EndUserAppInvolvmentGenerator.java
jgiannuzzi/waltz
06968e5b424e3dae233390c8657469b0705fd6c3
[ "Apache-2.0" ]
2,778
2016-01-21T20:44:52.000Z
2020-03-09T13:27:07.000Z
waltz-jobs/src/main/java/org/finos/waltz/jobs/generators/EndUserAppInvolvmentGenerator.java
ljubon/waltz
b21aa79f025e906635ccaf69e20e208107816fc3
[ "Apache-2.0" ]
42
2016-01-21T21:54:58.000Z
2020-03-05T21:06:46.000Z
35.595506
88
0.686237
3,950
/* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project * See README.md for more information * * 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 * */ package org.finos.waltz.jobs.generators; import org.finos.waltz.common.ListUtilities; import org.finos.waltz.model.EntityKind; import org.finos.waltz.schema.tables.records.InvolvementRecord; import org.jooq.DSLContext; import org.springframework.context.ApplicationContext; import java.util.List; import java.util.Map; import static org.finos.waltz.common.RandomUtilities.randomPick; import static org.finos.waltz.schema.tables.EndUserApplication.END_USER_APPLICATION; import static org.finos.waltz.schema.tables.Involvement.INVOLVEMENT; import static org.finos.waltz.schema.tables.InvolvementKind.INVOLVEMENT_KIND; import static org.finos.waltz.schema.tables.Person.PERSON; import static org.finos.waltz.schema.tables.PersonHierarchy.PERSON_HIERARCHY; public class EndUserAppInvolvmentGenerator implements SampleDataGenerator { @Override public Map<String, Integer> create(ApplicationContext ctx) { DSLContext dsl = getDsl(ctx); List<Long> appIds = dsl.select(END_USER_APPLICATION.ID) .from(END_USER_APPLICATION) .fetch(END_USER_APPLICATION.ID); List<String> empIds = dsl.select(PERSON.EMPLOYEE_ID) .from(PERSON) .innerJoin(PERSON_HIERARCHY) .on(PERSON.EMPLOYEE_ID.eq(PERSON_HIERARCHY.EMPLOYEE_ID)) .where(PERSON_HIERARCHY.LEVEL.lt(4)) .fetch(PERSON.EMPLOYEE_ID); List<Long> invKinds = dsl .select(INVOLVEMENT_KIND.ID) .from(INVOLVEMENT_KIND) .fetch(INVOLVEMENT_KIND.ID); List<InvolvementRecord> records = ListUtilities.map(appIds, id -> { InvolvementRecord record = dsl.newRecord(INVOLVEMENT); record.setProvenance(SAMPLE_DATA_PROVENANCE); record.setEmployeeId(randomPick(empIds)); record.setEntityId(id); record.setEntityKind(EntityKind.END_USER_APPLICATION.name()); record.setKindId(randomPick(invKinds)); return record; }); log("---saving: "+records.size()); dsl.batchInsert(records).execute(); log("---done"); return null; } @Override public boolean remove(ApplicationContext ctx) { getDsl(ctx) .deleteFrom(INVOLVEMENT) .where(INVOLVEMENT.PROVENANCE.eq(SAMPLE_DATA_PROVENANCE)) .and(INVOLVEMENT.ENTITY_KIND.eq(EntityKind.END_USER_APPLICATION.name())) .execute(); return true; } }
3e095b94ccdbd7cb329fbbba90a76e25e72df3fd
4,363
java
Java
src/SudokuRenderer/UtilityPanes/LoadMenu.java
BLovegrove/P3-Sudoku
2310eb282dafa8f0f774ef6e7f5520db89fe784f
[ "Apache-2.0" ]
null
null
null
src/SudokuRenderer/UtilityPanes/LoadMenu.java
BLovegrove/P3-Sudoku
2310eb282dafa8f0f774ef6e7f5520db89fe784f
[ "Apache-2.0" ]
null
null
null
src/SudokuRenderer/UtilityPanes/LoadMenu.java
BLovegrove/P3-Sudoku
2310eb282dafa8f0f774ef6e7f5520db89fe784f
[ "Apache-2.0" ]
null
null
null
29.680272
121
0.554435
3,951
package SudokuRenderer.UtilityPanes; import SudokuRenderer.ViewRenderer; import java.util.ArrayList; /*** * Makes a paginated ASCII-graphic menu to load previously saved sudoku boards from - all automatically generated */ public class LoadMenu { /*** * An array of all the file names excluding extensions in the saves folder */ private ArrayList<String> fileNames; /*** * Holds the current page position to display every time the menu redraws */ private int pageNumber; /*** * The max number of pages that can be viewed based on the number of saves in the folder */ private int maxPages; /*** * Each individual line of the menu's pane stored as an array */ private String[] menuLines = new String[20]; /*** * standard constructor to initialise the menu page to 1 and get file list / prep default menu state */ public LoadMenu(ArrayList<String> fileNames) { this.pageNumber = 1; updateFiles(fileNames); assemble(); } /*** * Construct and empty list as a starting point for the menu */ private void assemble() { drawPageIndicator(); this.menuLines[1] = " ╔═══════════════════════════════════╗"; for (int i = 0; i < 9; i++) { updateListItem(i, ""); if (i != 8) { this.menuLines[((i + 1)* 2) + 1] = " ╠═══════════════════════════════════╣"; } } this.menuLines[19] = " ╚═══════════════════════════════════╝"; } /*** * Draws / re-draws the 'page: x of y' text on top of the menu based on {@link #pageNumber} and {@link #maxPages}<br> * respectively */ private void drawPageIndicator() { this.menuLines[0] = String.format( " %-36s", " Page: " + this.pageNumber + " of " + this.maxPages ); } /*** * Used to call the (__FILE IO CLASS#METHOD LINK__) method, fetching a list of filenames to be displayed in the list */ public void updateFiles(ArrayList<String> fileNames) { // names can be at max 30 characters this.fileNames = fileNames; this.maxPages = (int) Math.ceil((1.0 * this.fileNames.size()) / 9.0); } /*** * Updates an individual line of the graphical list based on its relative position in said list (0-8) * @param itemIndex The position of the graphical list item you want to change * @param fileName The new file name (- extension) to replace the old one currently in-list */ private void updateListItem(int itemIndex, String fileName) { int absIndex = (itemIndex + 1) * 2; if (fileName.equals("")) { this.menuLines[absIndex] = String.format(" ║%-35s║", " "); } else { this.menuLines[absIndex] = String.format(" ║%-35s║", " "+(itemIndex+1)+") "+fileName); } } /*** * Get the current maximum number of pages available * @return Integer value as boundary for range 0 -> maxPages */ public int getMaxPages() { return this.maxPages; } /*** * Get the current selected page number * @return Integer value as current set of 9 files being viewed */ public int getPage() { return this.pageNumber; } /*** * Updates the current page value with the new one and redraws the list accordingly * @param pageNumber the page number in range 0 < {@link #maxPages} */ public void setPage(int pageNumber) { // pageNumber has to be between 0 and maxPages(excl.) this.pageNumber = pageNumber; drawPageIndicator(); } /*** * Draws / re-draws all the current list items and constructs it into a String[] array * @return The String[] array representing the LoadMenu's pane for use in a {@link ViewRenderer} */ public String[] draw() { for (int i = 0; i < 9; i++) { int absIndex = (9 * (this.pageNumber - 1)) + i; if (absIndex < this.fileNames.size()) { updateListItem(i, this.fileNames.get(absIndex)); } else { updateListItem(i, ""); } } return this.menuLines; } }
3e095c4e52d1548b66549fe1be9420136f338d49
4,951
java
Java
src/main/java/com/book/dao/SellDao.java
Alexlingl/BookManagement
617fd09e0d015e9fcb0ae7480303b1039c221c87
[ "Apache-2.0" ]
1
2019-06-23T07:00:10.000Z
2019-06-23T07:00:10.000Z
src/main/java/com/book/dao/SellDao.java
Alexlingl/online_bookstore
617fd09e0d015e9fcb0ae7480303b1039c221c87
[ "Apache-2.0" ]
null
null
null
src/main/java/com/book/dao/SellDao.java
Alexlingl/online_bookstore
617fd09e0d015e9fcb0ae7480303b1039c221c87
[ "Apache-2.0" ]
null
null
null
41.957627
164
0.623308
3,952
package com.book.dao; import com.book.domain.Sell; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.stereotype.Repository; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; @Repository public class SellDao { private JdbcTemplate jdbcTemplate; @Autowired public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } private final static String MY_BUY_LIST_SQL="SELECT * FROM sell_info WHERE reader_id = ? "; private final static String ADD_BUY_SQL="INSERT INTO sell_info (date,reader_id,price,book_id,state,number) VALUES(?,?,?,?,?,?) "; private final static String SELL_LIST_SQL="SELECT * FROM sell_info"; private final static String GET_SELL_SQL="SELECT * FROM sell_info where serial_number = ?"; private final static String EDIT_SELL_SQL="UPDATE sell_info SET date = ?, reader_id = ?, price = ?, book_id = ?, state = ?,number = ? where serial_number = ?;"; private final static String DELETE_SELL_SQL="DELETE FROM sell_info WHERE serial_number = ?;"; public ArrayList<Sell> myBuyList(int readerId){ final ArrayList<Sell> list=new ArrayList<Sell>(); jdbcTemplate.query(MY_BUY_LIST_SQL, new Object[]{readerId},new RowCallbackHandler() { public void processRow(ResultSet resultSet) throws SQLException { resultSet.beforeFirst(); while (resultSet.next()){ Sell sell=new Sell(); sell.setSerialNumber(resultSet.getInt("serial_number")); sell.setBookId(resultSet.getLong("book_id")); sell.setDate(resultSet.getDate("date")); sell.setPrice(resultSet.getBigDecimal("price")); sell.setReaderId(resultSet.getInt("reader_id")); sell.setState(resultSet.getInt("state")); sell.setNumber(resultSet.getInt("number")); list.add(sell); } } }); return list; } public int addBuy(Sell sell){ Date date = sell.getDate(); int readerId = sell.getReaderId(); BigDecimal price = sell.getPrice(); long bookId = sell.getBookId(); int number = sell.getNumber(); int state = sell.getState(); return jdbcTemplate.update(ADD_BUY_SQL,new Object[]{date,readerId,price,bookId,state,number}); } public ArrayList<Sell> sellList(){ final ArrayList<Sell> list=new ArrayList<Sell>(); jdbcTemplate.query(SELL_LIST_SQL, new RowCallbackHandler() { public void processRow(ResultSet resultSet) throws SQLException { resultSet.beforeFirst(); while (resultSet.next()){ Sell sell=new Sell(); sell.setSerialNumber(resultSet.getInt("serial_number")); sell.setBookId(resultSet.getLong("book_id")); sell.setPrice(resultSet.getBigDecimal("price")); sell.setDate(resultSet.getDate("date")); sell.setReaderId(resultSet.getInt("reader_id")); sell.setState(resultSet.getInt("state")); sell.setNumber(resultSet.getInt("number")); list.add(sell); } } }); return list; } public Sell getSell(int serialNumber){ Sell sell = new Sell(); jdbcTemplate.query(GET_SELL_SQL,new Object[]{serialNumber},new RowCallbackHandler(){ @Override public void processRow(ResultSet resultSet) throws SQLException { sell.setSerialNumber(resultSet.getInt("serial_number")); sell.setPrice(resultSet.getBigDecimal("price")); sell.setDate(resultSet.getDate("date")); sell.setState(resultSet.getInt("state")); sell.setBookId(resultSet.getLong("book_id")); sell.setReaderId(resultSet.getInt("reader_id")); sell.setNumber(resultSet.getInt("number")); } }); return sell; } public int editSell(Sell sell){ int serialNumber = sell.getSerialNumber(); Date date = sell.getDate(); int readerId = sell.getReaderId(); BigDecimal price = sell.getPrice(); long bookId = sell.getBookId(); int state = sell.getState(); int number = sell.getNumber(); int x=jdbcTemplate.update(EDIT_SELL_SQL,new Object[]{date,readerId,price,bookId,state,number,serialNumber}); return x; } public int deleteSell(int serialNumber){ return jdbcTemplate.update(DELETE_SELL_SQL,new Object[]{serialNumber}); } }
3e095e8e438883f531d32dd07d3f695a1e71bc39
1,224
java
Java
src/pasa/cbentley/jpasc/pcore/filter/predicates/PPredicate.java
cpbentley/pasa_cbentley_jpasc_pcore
34fb71e30cbaddd4c351004062eb596749fff2fb
[ "MIT" ]
1
2019-08-09T02:32:13.000Z
2019-08-09T02:32:13.000Z
src/pasa/cbentley/jpasc/pcore/filter/predicates/PPredicate.java
cpbentley/pasa_cbentley_jpasc_pcore
34fb71e30cbaddd4c351004062eb596749fff2fb
[ "MIT" ]
null
null
null
src/pasa/cbentley/jpasc/pcore/filter/predicates/PPredicate.java
cpbentley/pasa_cbentley_jpasc_pcore
34fb71e30cbaddd4c351004062eb596749fff2fb
[ "MIT" ]
null
null
null
21.103448
73
0.64134
3,953
/* * (c) 2018-2019 Charles-Philip Bentley * This code is licensed under MIT license (see LICENSE.txt for details) */ package pasa.cbentley.jpasc.pcore.filter.predicates; import pasa.cbentley.core.src4.ctx.UCtx; import pasa.cbentley.core.src4.logging.Dctx; import pasa.cbentley.core.src4.logging.IDLog; import pasa.cbentley.core.src4.logging.IStringable; import pasa.cbentley.jpasc.pcore.ctx.PCoreCtx; public abstract class PPredicate implements IStringable { protected final PCoreCtx pc; public PPredicate(PCoreCtx pc) { this.pc = pc; } //#mdebug public IDLog toDLog() { return toStringGetUCtx().toDLog(); } public String toString() { return Dctx.toString(this); } public void toString(Dctx dc) { dc.root(this, "PPredicate"); toStringPrivate(dc); } public String toString1Line() { return Dctx.toString1Line(this); } private void toStringPrivate(Dctx dc) { } public void toString1Line(Dctx dc) { dc.root1Line(this, "PPredicate"); toStringPrivate(dc); } public UCtx toStringGetUCtx() { return pc.getUCtx(); } //#enddebug }
3e095eba489926b932d87501c3d2208f86e841c3
8,798
java
Java
TradeToday/src/nl/m4jit/tradetoday/domainlogic/members/MemberModule.java
jorisdgff/Trade-Today
7cb42666691f06a7c4bf8b737bf3b131a3ae5870
[ "Unlicense" ]
null
null
null
TradeToday/src/nl/m4jit/tradetoday/domainlogic/members/MemberModule.java
jorisdgff/Trade-Today
7cb42666691f06a7c4bf8b737bf3b131a3ae5870
[ "Unlicense" ]
null
null
null
TradeToday/src/nl/m4jit/tradetoday/domainlogic/members/MemberModule.java
jorisdgff/Trade-Today
7cb42666691f06a7c4bf8b737bf3b131a3ae5870
[ "Unlicense" ]
null
null
null
35.475806
158
0.643214
3,954
package nl.m4jit.tradetoday.domainlogic.members; import java.awt.Desktop; import java.io.*; import java.text.*; import java.util.*; import nl.m4jit.framework.*; import nl.m4jit.framework.io.poi.excel.ExcelWriter; import nl.m4jit.tradetoday.dataaccess.custom.*; import nl.m4jit.tradetoday.dataaccess.members.*; import nl.m4jit.tradetoday.dataaccess.users.*; import nl.m4jit.tradetoday.domainlogic.Application; import nl.m4jit.tradetoday.domainlogic.UIMethods; import nl.m4jit.tradetoday.domainlogic.transactions.*; public class MemberModule { private final MemberTable table; private int startpoints; private static MemberModule instance; private MemberModule() { table = MemberTable.getInstance(); startpoints = Integer.parseInt(PropertyTable.getInstance().retreive("startpoints").getValue()); } private void validate(String sex, String initials, String lastname, String street, String housenumber, String postalcode, String place, Date birthdate, Date registrationdate, HeardOfTypeGateway heardOfType, RefferingInstanceGateway refferingInstance) { Date today = new Date(); if (sex.equals("U")) { throw new ValidationException("no sex"); } else if (initials.isEmpty()) { throw new ValidationException("no initials"); } else if (lastname.isEmpty()) { throw new ValidationException("no lastname"); } else if (street.isEmpty()) { throw new ValidationException("no street"); } else if (housenumber.isEmpty()) { throw new ValidationException("no housenumber"); } else if (postalcode.isEmpty()) { throw new ValidationException("no postalcode"); } else if (place.isEmpty()) { throw new ValidationException("no place"); } else if (birthdate == null) { throw new ValidationException("no birthdate"); } else if (birthdate.after(today)) { throw new ValidationException("future birthdate"); } else if (registrationdate.after(today)) { throw new ValidationException("future registrationdate"); } else if (heardOfType != null && heardOfType.getRefferingInstanceNeeded() && refferingInstance == null) { throw new ValidationException("refferinginstance mandatory"); } } public MemberGateway create(int number, String initials, String firstname, String prefix, String lastname, String sex, String street, String housenumber, String postalcode, String place, String telephoneHome, String telephoneMobile, String email, Date birthdate, Date registrationdate, IncomeTypeGateway incomeType, ParticipationLevelGateway participationLevel, HeardOfTypeGateway heardOfType, RefferingInstanceGateway refferingInstance, boolean idChecked, boolean newsletter, boolean agree, String extra) { validate(sex, initials, lastname, street, housenumber, postalcode, place, birthdate, registrationdate, heardOfType, refferingInstance); UseraccountGateway controller = Application.getInstance().getAccount(); UseraccountGateway processor = Application.getInstance().getAccount(); MemberGateway member = new MemberGateway(); member.setInitials(initials); member.setFirstname(firstname); member.setPrefix(prefix); member.setLastname(lastname); member.setSex(sex); member.setStreet(street); member.setHousenumber(housenumber); member.setPostalcode(postalcode); member.setPlace(place); member.setTelephoneHome(telephoneHome); member.setTelephoneMobile(telephoneMobile); member.setEmail(email); member.setBirthdate(birthdate); member.setNumber(number); member.setRegistrationdate(registrationdate); member.setIncomeType(incomeType); member.setParticipationLevel(participationLevel); member.setHeardOfType(heardOfType); member.setRefferingInstance(refferingInstance); member.setIdChecked(idChecked); member.setNewsletter(newsletter); member.setAgree(agree); member.setController(controller); member.setProcessor(processor); member.setExtra(extra); table.insert(member); TransactionModule.getInstance().makeSimpleTransaction(null, member, startpoints, "O", "Startpunten", registrationdate); return member; } public void update(MemberGateway member, String initials, String firstname, String prefix, String lastname, String sex, String street, String housenumber, String postalcode, String place, String telephoneHome, String telephoneMobile, String email, Date birthdate, Date registrationdate, Date deregistrationdate, IncomeTypeGateway incomeType, ParticipationLevelGateway participationLevel, HeardOfTypeGateway heardOfType, RefferingInstanceGateway refferingInstance, boolean idChecked, boolean newsletter, boolean agree, String extra) { validate(sex, initials, lastname, street, housenumber, postalcode, place, birthdate, registrationdate, heardOfType, refferingInstance); member.setInitials(initials); member.setFirstname(firstname); member.setPrefix(prefix); member.setLastname(lastname); member.setSex(sex); member.setStreet(street); member.setHousenumber(housenumber); member.setPostalcode(postalcode); member.setPlace(place); member.setTelephoneHome(telephoneHome); member.setTelephoneMobile(telephoneMobile); member.setEmail(email); member.setBirthdate(birthdate); member.setRegistrationdate(registrationdate); member.setDeregistrationdate(deregistrationdate); member.setIncomeType(incomeType); member.setParticipationLevel(participationLevel); member.setHeardOfType(heardOfType); member.setRefferingInstance(refferingInstance); member.setIdChecked(idChecked); member.setNewsletter(newsletter); member.setAgree(agree); member.setExtra(extra); table.update(member); } public int getStartpoints() { return startpoints; } public static String getFullname(MemberGateway member) { String initials = member.getInitials(); String firstname = member.getFirstname(); String prefix = member.getPrefix(); String lastname = member.getLastname(); if (firstname != null && !firstname.equals("")) { if (prefix == null) { return firstname + " " + lastname; } else { return firstname + " " + prefix + " " + lastname; } } else { if (prefix == null) { return initials + " " + lastname; } else { return initials + " " + prefix + " " + lastname; } } } public static void findMember(String input, UIMethods gui) { if (Util.isInt(input)) { int number = Integer.parseInt(input); MemberGateway member = MemberTable.getInstance().retreive(number); if(member != null){ gui.showMember(member); }else{ gui.showMessage("Lid niet gevonden"); } } else { List<MemberGateway> members; if(Util.isDate(input)){ Date date = Util.getDateFromString(input); members = MemberTable.getInstance().findByBirthdate(date); }else{ members = MemberTable.getInstance().findByName(input); } if (members.isEmpty()) { gui.showMessage("Geen leden gevonden"); } else if (members.size() == 1) { gui.showMember(members.get(0)); } else { gui.showMemberResult(members); } } } public static void exportMembers(File file, UIMethods gui) { String filename = file.toString() + ".xls"; MemberModel model = new MemberModel(); try { ExcelWriter writer = new ExcelWriter(); writer.addTableSheet(model, "Leden"); writer.write(filename); Desktop desktop = Desktop.getDesktop(); desktop.open(new File(filename)); } catch (IOException ex) { gui.showMessage("Bestand kon niet worden weggeschreven\n" + ex); } } public static MemberModule getInstance() { if (instance == null) { instance = new MemberModule(); } return instance; } }
3e095f6db0e6ee7f8ac26da88b1eeaf3c8a01bf1
20,726
java
Java
src/main/java/sketch/compiler/codegenerators/SNodesToFortran.java
dolphingarlic/sketch-frontend
e646b7d51405e8a693f45472aa3cc6991a6f38af
[ "X11" ]
1
2020-12-06T03:40:53.000Z
2020-12-06T03:40:53.000Z
src/main/java/sketch/compiler/codegenerators/SNodesToFortran.java
ruijiefang/sketch-frontend
c8c25e0ec8193361854ff8e1e5539b092442dfcf
[ "X11" ]
null
null
null
src/main/java/sketch/compiler/codegenerators/SNodesToFortran.java
ruijiefang/sketch-frontend
c8c25e0ec8193361854ff8e1e5539b092442dfcf
[ "X11" ]
null
null
null
29.191549
107
0.676349
3,955
package sketch.compiler.codegenerators; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import sketch.compiler.ast.core.FEContext; import sketch.compiler.ast.core.FENode; import sketch.compiler.ast.core.FENullVisitor; import sketch.compiler.ast.core.FEReplacer; import sketch.compiler.ast.core.FieldDecl; import sketch.compiler.ast.core.Function; import sketch.compiler.ast.core.Package; import sketch.compiler.ast.core.Parameter; import sketch.compiler.ast.core.Program; import sketch.compiler.ast.core.exprs.*; import sketch.compiler.ast.core.exprs.regens.ExprAlt; import sketch.compiler.ast.core.exprs.regens.ExprChoiceBinary; import sketch.compiler.ast.core.exprs.regens.ExprChoiceSelect; import sketch.compiler.ast.core.exprs.regens.ExprChoiceUnary; import sketch.compiler.ast.core.exprs.regens.ExprParen; import sketch.compiler.ast.core.exprs.regens.ExprRegen; import sketch.compiler.ast.core.stmts.*; import sketch.compiler.ast.core.typs.Type; import sketch.compiler.ast.core.typs.TypeArray; import sketch.compiler.ast.core.typs.TypePrimitive; import sketch.compiler.ast.core.typs.StructDef; import sketch.compiler.ast.core.typs.TypeStructRef; import sketch.compiler.ast.promela.stmts.StmtFork; import sketch.compiler.ast.promela.stmts.StmtJoin; /** * FORTRAN 77 code generator. * TODO: need a pass before this to "pull up" declarations and break apart * assignments from complex initializers (note: exclude loop index vars) * * @author liviu */ public class SNodesToFortran extends FENullVisitor { private static class VarCollector extends FEReplacer { private final List<String> ret; public VarCollector(List<String> list) { ret=list; } public Object visitExprVar(ExprVar exp) { String name=exp.getName(); if(!ret.contains(name)) ret.add(name); return exp; } } private static class ReturnFinder extends FEReplacer { private final List<String> ret; public ReturnFinder() { ret=new ArrayList<String>(); } public Object visitStmtReturn(StmtReturn stmt) { Expression rval=stmt.getValue(); assert rval instanceof ExprVar; String name=((ExprVar)rval).getName(); if(!ret.contains(name)) ret.add(name); return stmt; } public String getReturnVarName() { if(ret.size()==1) return ret.get(0); return null; } } private static final int MAX_LINE_LEN=72; private final String filename; /** line prefix (6 spaces) */ private String lp=" "; private String cline="c "; private String indentStr=""; private int lineCounter; private Function curFunc; private Map<String,Type> varTypes; private String outvar; private boolean returnsArray; private boolean isProcedure; private int indent=0; public SNodesToFortran(String filename) { this.filename=filename; lineCounter=1; varTypes=new HashMap<String,Type>(); } protected int getNewLabel() { return (lineCounter++)*10; } protected String labeledLP(int lbl) { String ret=" "+lbl; return ret+lp.substring(ret.length()); } private String getIndent() { if(indent*2!=indentStr.length()) { indentStr=""; for(int i=0;i<indent;i++) indentStr+=" "; } return indentStr; } /** * Takes in a line of code (without \n at the end) and returns * either the same line (with \n appended) or a concatenation of * several lines capped at 72 characters as per Fortran spec. */ private String lineSplit(String s) { if(s.length()<=MAX_LINE_LEN) return s+"\n"; return s.substring(0,MAX_LINE_LEN)+"\n"+lineSplit(" +"+s.substring(MAX_LINE_LEN)); } /** * Returns Fortran-formatted code for the statement encoded in s. * Indentation is added based on the value of the indent field. */ protected String line(String s) { return lineSplit(lp+getIndent()+s); } /** * Returns Fortran-formatted code for the statement encoded in s and * labeled with lbl. * Indentation is added based on the value of the indent field. */ protected String line(int lbl,String s) { return lineSplit(labeledLP(lbl)+getIndent()+s); } protected String newline() { return "\n"; } protected String getDefaultReturnVar() { return "out_"; } protected String getArrayDataType() { return "real"; } public Object visitProgram(Program prog) { String ret=line("program "+filename); ret+=line("end"); ret+=newline(); for (Iterator iter = prog.getPackages().iterator(); iter.hasNext(); ) ret += (String)((Package)iter.next()).accept(this); return ret; } public Object visitPackage(Package spec){ String ret = ""; for (Iterator iter = spec.getFuncs().iterator(); iter.hasNext(); ) { Function func = (Function)iter.next(); ret += (String)func.accept(this); } return ret; } private void doFindSizeParams(Type t, List<String> list) { if(t instanceof TypeArray) { VarCollector vc=new VarCollector(list); for(Expression e :((TypeArray)t).getDimensions()) { e.accept(vc); } } } protected List<String> getSizeParams(Function f) { List<String> ret=new ArrayList<String>(); doFindSizeParams(f.getReturnType(), ret); for(Iterator it=f.getParams().iterator();it.hasNext();) { Parameter p=(Parameter)it.next(); if(p.isParameterOutput()) continue; doFindSizeParams(p.getType(),ret); } return ret; } protected String getReturnVar(Function f) { ReturnFinder rf=new ReturnFinder(); f.getBody().accept(rf); String ret=rf.getReturnVarName(); if(ret!=null) return ret; return getDefaultReturnVar(); } private String makeParamCSL(List<Parameter> list) { String ret=""; boolean first=true; for(Parameter p:list) { if(first) first=false; else ret+=","; ret+=p.getName(); } return ret; } protected String makeDeclaration(Type type, String name) { String bounds=""; String typestr; if(type instanceof TypeArray) { TypeArray ta=(TypeArray) type; typestr=getArrayDataType(); for(Expression dim:ta.getDimensions()) { String expr=(String) dim.accept(this); if(bounds.length()>0) bounds+=", "; bounds+="0:"+expr+"-1"; } bounds="("+bounds+")"; } else { typestr=convertType(type); } return line(typestr+" "+name+bounds); } protected String declareParams(List<Parameter> list) { String ret=""; for(Parameter p: list) { ret+=makeDeclaration(p.getType(), p.getName()); } return ret; } public Object visitFunction(Function func) { curFunc=func; returnsArray=(func.getReturnType() instanceof TypeArray); isProcedure=returnsArray || (func.getReturnType()==TypePrimitive.voidtype); outvar=getReturnVar(func); String ret=""; List<Parameter> params=new ArrayList<Parameter>(); for(Iterator it=func.getParams().iterator();it.hasNext();) { Parameter p=(Parameter)it.next(); varTypes.put(p.getName(), p.getType()); //if(p.isParameterOutput()) continue; params.add(p); } if(returnsArray) { params.add(new Parameter(func, func.getReturnType(), outvar)); } for(String sizeArg: getSizeParams(func)) { params.add(new Parameter(func, TypePrimitive.inttype, sizeArg)); } String paramlist="("+makeParamCSL(params)+")"; if(isProcedure) { ret+=line("subroutine "+func.getName()+paramlist); } else { String rettype=convertType(func.getReturnType()); ret+=line(rettype+" function "+func.getName()+paramlist); } ret+=declareParams(params); ret+=func.getBody().accept(this); ret+=line("end"); ret+=newline(); return ret; } public Object visitStmtBlock(StmtBlock stmt) { String ret=""; for(Iterator it=stmt.getStmts().iterator();it.hasNext();) { Statement child=(Statement) it.next(); ret+=child.accept(this); } return ret; } public Object visitStmtVarDecl(StmtVarDecl stmt) { assert stmt.getNumVars()==1:"multiple variable declarations are not allowed "+stmt+" "+stmt; Type type = stmt.getType(0); String name=stmt.getName(0); assert (stmt.getInit(0)==null):"declaration initializers are not allowed "+stmt+" "+stmt; varTypes.put(name, type); //don't declare the output variable again (it is an argument to the function) if(name.equals(outvar)) return ""; return makeDeclaration(type, name); } public Object visitExprFunCall(ExprFunCall exp) { assert false: "function calls not supported yet"; //TODO return null; } public Object visitStmtLoop(StmtLoop stmt) { assert false: "loop construct not supported yet"; //TODO return null; } private ExprVar genLoopVar(int idx) { return new ExprVar((FEContext) null,"i_"+idx); } private String generateZeroCode(String name,TypeArray type) { String ret=""; List<Expression> dims=type.getDimensions(); Expression arr=new ExprVar((FEContext) null,name); for(int i=0;i<dims.size();i++) { arr=new ExprArrayRange(arr,genLoopVar(i)); } Statement body=new StmtAssign(arr,ExprConstInt.zero); for(int i=dims.size()-1;i>=0;i--) { ExprVar loopVar=genLoopVar(i); body=new StmtFor((FEContext) null, new StmtVarDecl((FEContext) null, TypePrimitive.inttype, loopVar.getName(), ExprConstInt.zero), new ExprBinary(loopVar, "<", dims.get(i)), new StmtExpr(new ExprUnary(loopVar, ExprUnary.UNOP_POSTINC, loopVar)), body, true ); } return (String) body.accept(this); } public Object visitStmtAssign(StmtAssign stmt) { while(stmt.getLHS() instanceof ExprVar) { ExprVar var=(ExprVar) stmt.getLHS(); Type varType=varTypes.get(var.getName()); if(varType instanceof TypeArray) { if(stmt.getRHS() instanceof ExprConstInt) { ExprConstInt zero=(ExprConstInt) stmt.getRHS(); assert zero.getVal()==0: "Can't assign arbitrary stuff to an array"; return generateZeroCode(var.getName(),(TypeArray) varType); } else if(stmt.getRHS() instanceof ExprVar) { ExprVar rvar=(ExprVar) stmt.getRHS(); Type rvarType=varTypes.get(rvar.getName()); assert rvarType instanceof TypeArray: "Can't assign arbitrary stuff to an array"; //TODO: implement array copy //for now just use the default handler which outputs a simple "a=b" break; } else { assert false: "Can't assign arbitrary stuff to an array"; } return null; } break; } String lhs=(String)stmt.getLHS().accept(this); String rhs=(String)stmt.getRHS().accept(this); String op; switch(stmt.getOp()) { case 0: return line(lhs+" = "+rhs); case ExprBinary.BINOP_ADD: op="+"; break; case ExprBinary.BINOP_SUB: op="-"; break; case ExprBinary.BINOP_MUL: op="*"; break; case ExprBinary.BINOP_DIV: op="/"; break; case ExprBinary.BINOP_BOR: case ExprBinary.BINOP_BAND: case ExprBinary.BINOP_BXOR: assert false; return null; default: throw new IllegalStateException(stmt.toString()+" opcode="+stmt.getOp()); } return line(lhs+" = "+lhs+" "+op+" "+rhs); } public Object visitStmtReturn(StmtReturn stmt) { String ret=""; if(returnsArray) { assert stmt.getValue() instanceof ExprVar; ExprVar var=(ExprVar) stmt.getValue(); if(var.getName().equals(outvar)) { //no need to do anything } else { //TODO: copy the return value into outvar assert false: "array copy not implemented yet"; } } else if(isProcedure) { assert stmt.getValue()==null; } else { //function: set the return value (assign to function name) StmtAssign assign=new StmtAssign(new ExprVar((FEContext) null,curFunc.getName()),stmt.getValue()); ret+=assign.accept(this); } ret+=line("return"); return ret; } public Object visitExprArrayRange(ExprArrayRange exp) { String ret=""; String base=(String) exp.getAbsoluteBase().accept(this); for(Expression idx: exp.getArrayIndices()) { if(ret.length()>0) ret+=", "; ret+=idx.accept(this); } return base+"("+ret+")"; } public Object visitExprBinary(ExprBinary exp) { String op; switch(exp.getOp()) { case ExprBinary.BINOP_ADD: op = "+"; break; case ExprBinary.BINOP_SUB: op = "-"; break; case ExprBinary.BINOP_MUL: op = "*"; break; case ExprBinary.BINOP_DIV: op = "/"; break; case ExprBinary.BINOP_AND: op = ".AND."; break; case ExprBinary.BINOP_OR: op = ".OR."; break; case ExprBinary.BINOP_EQ: op = ".EQ."; break; case ExprBinary.BINOP_NEQ: op = ".NE."; break; case ExprBinary.BINOP_LT: op = ".LT."; break; case ExprBinary.BINOP_LE: op = ".LE."; break; case ExprBinary.BINOP_GT: op = ".GT."; break; case ExprBinary.BINOP_GE: op = ".GE."; break; //special conversions case ExprBinary.BINOP_BAND: op = "*"; break; case ExprBinary.BINOP_BXOR: op = "+"; break; case ExprBinary.BINOP_MOD: { String lhs=(String) exp.getLeft().accept(this); String rhs=(String) exp.getRight().accept(this); return "mod("+lhs+","+rhs+")"; } case ExprBinary.BINOP_BOR: case ExprBinary.BINOP_RSHIFT: case ExprBinary.BINOP_LSHIFT: default: assert false: "unsupported binary operator in "+exp; return null; } String lhs=(String) exp.getLeft().accept(this); String rhs=(String) exp.getRight().accept(this); return "("+lhs+" "+op+" "+rhs+")"; } public Object visitStmtFor(StmtFor stmt) { assert stmt.getInit() instanceof StmtVarDecl; StmtVarDecl decl=(StmtVarDecl) stmt.getInit(); assert decl.getNumVars()==1; String indexVar=decl.getName(0); Expression start=decl.getInit(0); assert start!=null; assert stmt.getCond() instanceof ExprBinary; ExprBinary cond=(ExprBinary) stmt.getCond(); assert cond.getLeft() instanceof ExprVar; assert ((ExprVar)cond.getLeft()).getName().equals(indexVar); Expression finish=null; switch(cond.getOp()) { case ExprBinary.BINOP_LT: finish=new ExprBinary(null,ExprBinary.BINOP_SUB,cond.getRight(),new ExprConstInt(1)); break; case ExprBinary.BINOP_LE: finish=cond.getRight(); break; case ExprBinary.BINOP_GT: finish=new ExprBinary(null,ExprBinary.BINOP_ADD,cond.getRight(),new ExprConstInt(1)); break; case ExprBinary.BINOP_GE: finish=cond.getRight(); break; default: assert false:"unsupported for loop termination condition"; } Expression stride=null; if(stmt.getIncr() instanceof StmtExpr) { StmtExpr se=(StmtExpr) stmt.getIncr(); assert se.getExpression() instanceof ExprUnary; ExprUnary expr=(ExprUnary) se.getExpression(); switch(expr.getOp()) { case ExprUnary.UNOP_POSTINC: case ExprUnary.UNOP_PREINC: stride=new ExprConstInt(1); break; case ExprUnary.UNOP_POSTDEC: case ExprUnary.UNOP_PREDEC: stride=new ExprConstInt(-1); break; default: assert false:"unsupported loop increment"; } } else if(stmt.getIncr() instanceof StmtAssign) { StmtAssign assign=(StmtAssign) stmt.getIncr(); assert assign.getLHS() instanceof ExprVar; assert ((ExprVar)assign.getLHS()).getName().equals(indexVar); switch(assign.getOp()) { case ExprBinary.BINOP_ADD: stride=assign.getRHS(); break; case ExprBinary.BINOP_SUB: stride=new ExprUnary(assign.getRHS(),ExprUnary.UNOP_NEG,assign.getRHS()); break; default: assert false:"unsupported loop increment"; } } else { assert false:"unsupported loop increment"; } String startstr=(String) start.accept(this); String finishstr=(String) finish.accept(this); String stridestr=(String) stride.accept(this); String ret="do "+indexVar+" = "+startstr+", "+finishstr; if(!"1".equals(stridestr)) ret+=", "+stridestr; ret=line(ret); indent++; ret+=stmt.getBody().accept(this); indent--; ret+=line("enddo"); return ret; } public Object visitStmtIfThen(StmtIfThen stmt) { String ret=""; String condstr=(String) stmt.getCond().accept(this); ret+=line("if ("+condstr+") then"); indent++; ret+=stmt.getCons().accept(this); indent--; if(stmt.getAlt()!=null) { ret+=line("else"); indent++; ret+=stmt.getAlt().accept(this); indent--; } ret+=line("endif"); return ret; } public Object visitExprUnary(ExprUnary exp) { switch(exp.getOp()) { case ExprUnary.UNOP_NOT: return ".NOT. "+exp.getExpr().accept(this); case ExprUnary.UNOP_NEG: return "(-"+exp.getExpr().accept(this)+")"; default: assert false: "Unsupported unary operator"; } return null; } public Object visitExprVar(ExprVar exp) { return exp.getName(); } public Object visitExprParen(ExprParen exp) { return "("+ exp.getExpr ().accept (this) +")"; } public Object visitExprConstChar(ExprConstChar exp) { assert false; return null; } public Object visitExprConstFloat(ExprConstFloat exp) { return ""+exp.getVal(); } public Object visitExprConstInt(ExprConstInt exp) { return ""+exp.getVal(); } public Object visitExprTernary(ExprTernary exp) { assert false; return null; } public Object visitExprLiteral(ExprLiteral exp) { return exp.getValue(); } public Object visitExprField(ExprField exp) { throw new IllegalStateException(); } public Object visitExprArrayInit(ExprArrayInit exp) { assert false; return null; } public Object visitExprStar(ExprStar star) { throw new IllegalStateException(); } public Object visitExprTypeCast(ExprTypeCast exp) { assert false; return null; } public Object visitFieldDecl(FieldDecl field) { assert false; return null; } public Object visitOther(FENode node) { throw new IllegalStateException(); } public Object visitStmtAssert(StmtAssert stmt) { //TODO? return ""; } public Object visitStmtBreak(StmtBreak stmt) { assert false; return null; } public Object visitStmtContinue(StmtContinue stmt) { assert false; return null; } public Object visitStmtDoWhile(StmtDoWhile stmt) { assert false; return null; } public Object visitStmtEmpty(StmtEmpty stmt) { return ""; } public Object visitStmtExpr(StmtExpr stmt) { assert false; return null; } public Object visitStmtJoin(StmtJoin stmt) { throw new IllegalStateException(); } public Object visitStmtWhile(StmtWhile stmt) { assert false; return null; } public String convertType(Type type) { assert (type instanceof TypePrimitive); switch(((TypePrimitive)type).getType()) { case TypePrimitive.TYPE_INT: return "integer"; case TypePrimitive.TYPE_BIT: return "real"; case TypePrimitive.TYPE_FLOAT: return "real"; } assert false; return null; } public Object visitType(Type t) { return null; } public Object visitTypePrimitive(TypePrimitive t) { return null; } public Object visitTypeArray(TypeArray t) { return null; } public Object visitTypeStructRef(TypeStructRef ts) { return null; } public Object visitParameter(Parameter par){ assert false :"NYI"; return null; } public Object visitExprNew(ExprNew expNew){ assert false :"No alloc in fortran."; return null; } public Object visitStmtFork(StmtFork loop){ throw new UnsupportedOperationException(); } public Object visitStmtReorderBlock(StmtReorderBlock block){throw new UnsupportedOperationException();} public Object visitStmtAtomicBlock(StmtAtomicBlock block){throw new UnsupportedOperationException();} public Object visitStmtInsertBlock(StmtInsertBlock block){throw new UnsupportedOperationException();} public Object visitStructDef(StructDef ts){throw new UnsupportedOperationException();} public Object visitExprNullPtr(ExprNullPtr nptr){ throw new UnsupportedOperationException(); } public Object visitExprAlt (ExprAlt exp) { throw new UnsupportedOperationException (); } public Object visitExprChoiceBinary(ExprChoiceBinary e) { throw new UnsupportedOperationException(); } public Object visitExprChoiceSelect(ExprChoiceSelect e) { throw new UnsupportedOperationException(); } public Object visitExprChoiceUnary(ExprChoiceUnary e) { throw new UnsupportedOperationException(); } public Object visitExprRegen(ExprRegen e) { throw new UnsupportedOperationException(); } public Object visitStmtSwitch(StmtSwitch sw) { throw new UnsupportedOperationException(); } }
3e0960f3b0f0f2a74bbea421ade6fe423e04a368
1,687
java
Java
src/main/java/com/example/widgets_are_us/productsservice/models/Product.java
johatfie/products-service
63a1f9dd63b8b9d535b9b110bcf1e0254db3343b
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/example/widgets_are_us/productsservice/models/Product.java
johatfie/products-service
63a1f9dd63b8b9d535b9b110bcf1e0254db3343b
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/example/widgets_are_us/productsservice/models/Product.java
johatfie/products-service
63a1f9dd63b8b9d535b9b110bcf1e0254db3343b
[ "BSD-3-Clause" ]
null
null
null
24.1
66
0.691168
3,956
package com.example.widgets_are_us.productsservice.models; import com.example.widgets_are_us.productsservice.utils.Dollars; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Transient; @Entity @Slf4j @Data @Builder(toBuilder = true) @NoArgsConstructor @AllArgsConstructor public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String description; private Dollars price; @Transient @JsonIgnore @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private static final ObjectMapper mapper = new ObjectMapper(); public String toJson() { try { log.info("Mapping customer to json"); return mapper.writeValueAsString(this); } catch(Exception e) { log.error(e.getClass().getName(), e.getMessage()); return ""; } } public static Product fromJson(String json) { try { log.info("Mapping customer from json"); return mapper.readValue(json, Product.class); } catch(Exception e) { log.error(e.getClass().getName(), e.getMessage()); return new Product(); } } }
3e09621018229f7f8ebff7a1e0a59d923f690c19
1,545
java
Java
src/net/segoia/ogeg/node/vo/core/PeerNodeContext.java
acionescu/og-node-core
f48f666c72f2393de0b5880aacb81b3fe2ea1ca3
[ "Apache-2.0" ]
null
null
null
src/net/segoia/ogeg/node/vo/core/PeerNodeContext.java
acionescu/og-node-core
f48f666c72f2393de0b5880aacb81b3fe2ea1ca3
[ "Apache-2.0" ]
null
null
null
src/net/segoia/ogeg/node/vo/core/PeerNodeContext.java
acionescu/og-node-core
f48f666c72f2393de0b5880aacb81b3fe2ea1ca3
[ "Apache-2.0" ]
null
null
null
32.1875
102
0.752104
3,957
/** * og-node-core - The core resources of an Open Groups node * Copyright (C) 2020 Adrian Cristian Ionescu - https://github.com/acionescu * * 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.segoia.ogeg.node.vo.core; import net.segoia.eventbus.web.ws.v0.EventNodeWsEndpointTransceiver; public class PeerNodeContext { private PeerNodeConfig peerConfig; private EventNodeWsEndpointTransceiver clientEndpoint; public PeerNodeContext(PeerNodeConfig peerConfig, EventNodeWsEndpointTransceiver clientEndpoint) { super(); this.peerConfig = peerConfig; this.clientEndpoint = clientEndpoint; } public PeerNodeConfig getPeerConfig() { return peerConfig; } public void setPeerConfig(PeerNodeConfig peerConfig) { this.peerConfig = peerConfig; } public EventNodeWsEndpointTransceiver getClientEndpoint() { return clientEndpoint; } public void setClientEndpoint(EventNodeWsEndpointTransceiver clientEndpoint) { this.clientEndpoint = clientEndpoint; } }
3e09625ca2a8be53936adda0307640091fa1c1e4
6,766
java
Java
src/test/java/org/opengis/cite/cdb10/cdbStructure/VerifyMModelTextureStructureTests.java
hustbill/ets-cdb10
874506ebcfb1b44526b5709b3fcb1e35895508cd
[ "Apache-2.0" ]
1
2019-01-24T16:26:06.000Z
2019-01-24T16:26:06.000Z
src/test/java/org/opengis/cite/cdb10/cdbStructure/VerifyMModelTextureStructureTests.java
hustbill/ets-cdb10
874506ebcfb1b44526b5709b3fcb1e35895508cd
[ "Apache-2.0" ]
43
2018-04-18T23:26:38.000Z
2021-06-25T14:32:58.000Z
src/test/java/org/opengis/cite/cdb10/cdbStructure/VerifyMModelTextureStructureTests.java
hustbill/ets-cdb10
874506ebcfb1b44526b5709b3fcb1e35895508cd
[ "Apache-2.0" ]
5
2018-04-18T21:02:59.000Z
2020-09-28T18:32:33.000Z
25.923372
106
0.720071
3,958
package org.opengis.cite.cdb10.cdbStructure; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import org.junit.Test; public class VerifyMModelTextureStructureTests extends StructureTestFixture<MModelTextureStructureTests> { public VerifyMModelTextureStructureTests() throws IOException { this.testSuite = new MModelTextureStructureTests(); } @Test(expected = AssertionError.class) public void verifyTNAMPrefix_TooLong() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "ABC"))); // execute this.testSuite.verifyTNAMPrefix(); } @Test(expected = AssertionError.class) public void verifyTNAMPrefix_WrongCase() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "a"))); // execute this.testSuite.verifyTNAMPrefix(); } @Test public void verifyTNAMPrefix_Good() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A"))); // execute this.testSuite.verifyTNAMPrefix(); } @Test public void verifyTNAMPrefix_Skip() throws IOException { // setup // execute this.testSuite.verifyTNAMPrefix(); } @Test(expected = AssertionError.class) public void verifyTNAMSecond_TooLong() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "BCD"))); // execute this.testSuite.verifyTNAMSecond(); } @Test(expected = AssertionError.class) public void verifyTNAMSecond_WrongCase() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "b"))); // execute this.testSuite.verifyTNAMSecond(); } @Test public void verifyTNAMSecond_Good() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B"))); // execute this.testSuite.verifyTNAMSecond(); } @Test public void verifyTNAMSecond_Skip() throws IOException { // setup // execute this.testSuite.verifyTNAMSecond(); } @Test(expected = AssertionError.class) public void verifyTNAM_TooShort() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "A"))); // execute this.testSuite.verifyTNAM(); } @Test(expected = AssertionError.class) public void verifyTNAM_TooLong() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"))); // execute this.testSuite.verifyTNAM(); } @Test(expected = AssertionError.class) public void verifyTNAM_WrongChars() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "$$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"))); // execute this.testSuite.verifyTNAM(); } @Test(expected = AssertionError.class) public void verifyTNAM_Mismatch() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AC_1"))); // execute this.testSuite.verifyTNAM(); } @Test public void verifyTNAM_Good() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AB_1"))); // execute this.testSuite.verifyTNAM(); } @Test public void verifyTNAM_Skip() throws IOException { // setup // execute this.testSuite.verifyTNAM(); } @Test(expected = AssertionError.class) public void verifyFile_invalid() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AB", "asdf"))); // execute this.testSuite.verifyFile(); } @Test(expected = AssertionError.class) public void verifyFile_invalidDataset() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AB", "D600_S001_T001_W10_AB.rgb"))); // execute this.testSuite.verifyFile(); } @Test(expected = AssertionError.class) public void verifyFile_invalidExtension() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AB", "D601_S001_T001_W10_AB.txt"))); // execute this.testSuite.verifyFile(); } @Test(expected = AssertionError.class) public void verifyFile_mismatchExtension() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AB", "D601_S001_T001_W10_AB.xml"))); // execute this.testSuite.verifyFile(); } @Test(expected = AssertionError.class) public void verifyFile_mismatchMMDC() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AB", "D601_S001_T001_W10_ABCD.rgb"))); // execute this.testSuite.verifyFile(); } @Test(expected = AssertionError.class) public void verifyFile_badCS1Length() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AB", "D601_S1_T001_W10_AB.rgb"))); // execute this.testSuite.verifyFile(); } @Test(expected = AssertionError.class) public void verifyFile_badCS1Type() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AB", "D601_SABC_T001_W10_AB.rgb"))); // execute this.testSuite.verifyFile(); } @Test(expected = AssertionError.class) public void verifyFile_badCS2Length() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AB", "D601_S001_T1_W10_AB.rgb"))); // execute this.testSuite.verifyFile(); } @Test(expected = AssertionError.class) public void verifyFile_badCS2Type() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AB", "D601_S001_TABC_W10_AB.rgb"))); // execute this.testSuite.verifyFile(); } @Test public void verifyFile_Good() throws IOException { // setup Files.createDirectories(this.cdb_root.resolve(Paths.get("MModel", "601_MModelTexture", "A", "B", "AB", "D601_S002_T001_W10_AB.rgb"))); // execute this.testSuite.verifyFile(); } @Test public void verifyFile_Skip() throws IOException { // setup // execute this.testSuite.verifyFile(); } }
3e096265950c298ffa084f74416a0cf869bb7146
11,167
java
Java
netreflected/src/net461/system_version_4.0.0.0_culture_neutral_publickeytoken_b77a5c561934e089/system/security/permissions/ResourcePermissionBase.java
mariomastrodicasa/JCOReflector
a88b6de9d3cc607fd375ab61df8c61f44de88c93
[ "MIT" ]
35
2020-08-30T03:19:42.000Z
2022-03-12T09:22:23.000Z
netreflected/src/net461/system_version_4.0.0.0_culture_neutral_publickeytoken_b77a5c561934e089/system/security/permissions/ResourcePermissionBase.java
mariomastrodicasa/JCOReflector
a88b6de9d3cc607fd375ab61df8c61f44de88c93
[ "MIT" ]
50
2020-06-22T17:03:18.000Z
2022-03-30T21:19:05.000Z
netreflected/src/net461/system_version_4.0.0.0_culture_neutral_publickeytoken_b77a5c561934e089/system/security/permissions/ResourcePermissionBase.java
mariomastrodicasa/JCOReflector
a88b6de9d3cc607fd375ab61df8c61f44de88c93
[ "MIT" ]
12
2020-08-30T03:19:45.000Z
2022-03-05T02:22:37.000Z
47.519149
529
0.706904
3,959
/* * MIT License * * Copyright (c) 2021 MASES s.r.l. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.security.permissions; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.security.CodeAccessPermission; import system.security.IPermission; import system.security.IPermissionImplementation; import system.security.SecurityElement; /** * The base .NET class managing System.Security.Permissions.ResourcePermissionBase, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Security.Permissions.ResourcePermissionBase" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Security.Permissions.ResourcePermissionBase</a> */ public class ResourcePermissionBase extends CodeAccessPermission { /** * Fully assembly qualified name: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 */ public static final String assemblyFullName = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; /** * Assembly name: System */ public static final String assemblyShortName = "System"; /** * Qualified class name: System.Security.Permissions.ResourcePermissionBase */ public static final String className = "System.Security.Permissions.ResourcePermissionBase"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public ResourcePermissionBase(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link ResourcePermissionBase}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link ResourcePermissionBase} instance * @throws java.lang.Throwable in case of error during cast operation */ public static ResourcePermissionBase cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new ResourcePermissionBase(from.getJCOInstance()); } // Constructors section public ResourcePermissionBase() throws Throwable { } // Methods section public boolean IsSubsetOf(IPermission target) throws Throwable, system.ArgumentNullException, system.ObjectDisposedException, system.threading.AbandonedMutexException, system.ArgumentException, system.FormatException, system.ArgumentOutOfRangeException, system.InvalidOperationException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (boolean)classInstance.Invoke("IsSubsetOf", target == null ? null : target.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public boolean IsUnrestricted() throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (boolean)classInstance.Invoke("IsUnrestricted"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public IPermission Copy() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.NotSupportedException, system.InvalidOperationException, system.FormatException, system.MissingMethodException, system.reflection.TargetInvocationException, system.ArgumentOutOfRangeException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objCopy = (JCObject)classInstance.Invoke("Copy"); return new IPermissionImplementation(objCopy); } catch (JCNativeException jcne) { throw translateException(jcne); } } public IPermission Intersect(IPermission target) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.security.SecurityException, system.FormatException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objIntersect = (JCObject)classInstance.Invoke("Intersect", target == null ? null : target.getJCOInstance()); return new IPermissionImplementation(objIntersect); } catch (JCNativeException jcne) { throw translateException(jcne); } } public IPermission Union(IPermission target) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.security.SecurityException, system.FormatException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objUnion = (JCObject)classInstance.Invoke("Union", target == null ? null : target.getJCOInstance()); return new IPermissionImplementation(objUnion); } catch (JCNativeException jcne) { throw translateException(jcne); } } public SecurityElement ToXml() throws Throwable, system.ArgumentNullException, system.TypeLoadException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotSupportedException, system.globalization.CultureNotFoundException, system.ArgumentOutOfRangeException, system.OutOfMemoryException, system.FormatException, system.NotImplementedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objToXml = (JCObject)classInstance.Invoke("ToXml"); return new SecurityElement(objToXml); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void FromXml(SecurityElement securityElement) throws Throwable, system.ArgumentNullException, system.NullReferenceException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidCastException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("FromXml", securityElement == null ? null : securityElement.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Properties section // Instance Events section }
3e0963348d783326bf0441f3260e3f6619a78b02
906
java
Java
oap-common/src/main/java/com/intel/oap/common/unsafe/PMemMemoryMapper.java
tsface/OAP
97e0be1feb3db949205a0ee1ee30b6fd60a852b5
[ "Apache-2.0" ]
3
2021-01-20T01:57:59.000Z
2021-11-10T03:27:46.000Z
oap-common/src/main/java/com/intel/oap/common/unsafe/PMemMemoryMapper.java
tsface/OAP
97e0be1feb3db949205a0ee1ee30b6fd60a852b5
[ "Apache-2.0" ]
22
2020-12-28T10:09:01.000Z
2021-12-14T04:32:32.000Z
oap-common/src/main/java/com/intel/oap/common/unsafe/PMemMemoryMapper.java
tsface/OAP
97e0be1feb3db949205a0ee1ee30b6fd60a852b5
[ "Apache-2.0" ]
8
2020-12-29T02:52:02.000Z
2021-09-02T03:34:17.000Z
23.842105
84
0.657837
3,960
package com.intel.oap.common.unsafe; import com.intel.oap.common.util.NativeLibraryLoader; public class PMemMemoryMapper { private static final String LIBNAME = "pmemmemorymapper"; static { NativeLibraryLoader.load(LIBNAME); } /** * Create a file and memory map it. * pmem_map_file(path, PMEM_LEN, PMEM_FILE_CREATE,0666, &mapped_len, &is_pmem) * * @param fileName * @param fileLength * @return pmem address */ public static native long pmemMapFile(String fileName, long fileLength); public static native void pmemMemcpy(long pmemAddress, byte[] src, long length); /** * Flush at final */ public static native void pmemDrain(); /** * Unmap the file * * @param address pmem address * @param length mapped length */ public static native void pmemUnmap(long address, long length); }
3e09637ea4085c900ec3a08a6038e7b5d8e9921c
2,983
java
Java
src/main/java/seedu/address/logic/commands/prescription/AddPrescriptionCommand.java
juslam19/tp
d8d3758b2b885c56e3b4d12494ffd1dac034cc15
[ "MIT" ]
null
null
null
src/main/java/seedu/address/logic/commands/prescription/AddPrescriptionCommand.java
juslam19/tp
d8d3758b2b885c56e3b4d12494ffd1dac034cc15
[ "MIT" ]
116
2022-03-06T07:09:17.000Z
2022-03-31T18:11:46.000Z
src/main/java/seedu/address/logic/commands/prescription/AddPrescriptionCommand.java
juslam19/tp
d8d3758b2b885c56e3b4d12494ffd1dac034cc15
[ "MIT" ]
5
2022-02-11T16:21:48.000Z
2022-03-15T08:14:02.000Z
39.25
99
0.710694
3,961
package seedu.address.logic.commands.prescription; import static java.util.Objects.requireNonNull; import static seedu.address.logic.parser.CliSyntax.PREFIX_DATE; import static seedu.address.logic.parser.CliSyntax.PREFIX_INSTRUCTION; import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME; import static seedu.address.logic.parser.CliSyntax.PREFIX_NRIC; import static seedu.address.logic.parser.CliSyntax.PREFIX_TYPE; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.CommandType; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.patient.Nric; import seedu.address.model.prescription.Prescription; import seedu.address.model.prescription.PrescriptionWithNricPredicate; public class AddPrescriptionCommand extends Command { public static final String COMMAND_WORD = "add"; public static final CommandType COMMAND_TYPE = CommandType.PRESCRIPTION; public static final String MESSAGE_USAGE = COMMAND_WORD + " " + PREFIX_TYPE + "prescription " + ": Adds a medical prescription of a patient in Medbook. \n" + "Parameters: " + PREFIX_NRIC + "NRIC " + PREFIX_NAME + "DRUG_NAME " + PREFIX_DATE + "DATE " + PREFIX_INSTRUCTION + "INSTRUCTION \n" + "Example: " + COMMAND_WORD + " " + PREFIX_TYPE + "prescription " + PREFIX_NRIC + "S1234567L " + PREFIX_NAME + "Acetaminophen " + PREFIX_DATE + "2022-02-22 " + PREFIX_INSTRUCTION + "2 tablets after meal everyday "; public static final String MESSAGE_SUCCESS = "New medical prescription added: %1$s"; public static final String MESSAGE_DUPLICATE_PRESCRIPTION = "This medical prescription already exist in this patient's prescription list"; public static final String MESSAGE_MISSING_PATIENT = "This patient does not exists in MedBook"; private final Nric nric; private final Prescription toAdd; /** * Creates an AddPrescriptionCommand to add the specified {@code Patient} */ public AddPrescriptionCommand(Nric nric, Prescription prescription) { requireNonNull(nric); requireNonNull(prescription); toAdd = prescription; this.nric = nric; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); if (!model.hasNric(nric)) { throw new CommandException(MESSAGE_MISSING_PATIENT); } if (model.hasPrescription(toAdd)) { throw new CommandException(MESSAGE_DUPLICATE_PRESCRIPTION); } model.addPrescription(toAdd); model.updateFilteredPrescriptionList(new PrescriptionWithNricPredicate(nric)); return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd), COMMAND_TYPE); } }
3e09637f2cb45c9546c6953b113932212a8e0df8
399
java
Java
src/main/java/com/sb/kafka/KafkaApplication.java
mahajanankur/kafka-client
f6f3a5e2354a27b3de336965008d14dbf6fafd1f
[ "MIT" ]
null
null
null
src/main/java/com/sb/kafka/KafkaApplication.java
mahajanankur/kafka-client
f6f3a5e2354a27b3de336965008d14dbf6fafd1f
[ "MIT" ]
null
null
null
src/main/java/com/sb/kafka/KafkaApplication.java
mahajanankur/kafka-client
f6f3a5e2354a27b3de336965008d14dbf6fafd1f
[ "MIT" ]
null
null
null
24.9375
70
0.837093
3,962
package com.sb.kafka; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableAutoConfiguration public class KafkaApplication { public static void main(String[] args) { SpringApplication.run(KafkaApplication.class, args); } }
3e0963e1a7be9dd00bf0b1fd14783045ae963ea5
7,286
java
Java
src/main/java/com/github/andreldsr/criteriaresolver/repository/CriteriaResolverBaseRepository.java
andreldsr/criteriaresolver
0e955ec6529386b90782077be2e191c99dfaad07
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/andreldsr/criteriaresolver/repository/CriteriaResolverBaseRepository.java
andreldsr/criteriaresolver
0e955ec6529386b90782077be2e191c99dfaad07
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/andreldsr/criteriaresolver/repository/CriteriaResolverBaseRepository.java
andreldsr/criteriaresolver
0e955ec6529386b90782077be2e191c99dfaad07
[ "Apache-2.0" ]
null
null
null
40.254144
115
0.637524
3,963
package com.github.andreldsr.criteriaresolver.repository; import com.github.andreldsr.criteriaresolver.annotation.CriteriaField; import com.github.andreldsr.criteriaresolver.annotation.ProjectionField; import com.github.andreldsr.criteriaresolver.searchobject.SearchObject; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.*; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.criteria.Selection; public abstract class CriteriaResolverBaseRepository<T> { EntityManager em; private Class<T> c; private CriteriaBuilder criteriaBuilder; private CriteriaQuery<T> criteria; private Root<T> root; private Map<String, Join> joinMap; @SuppressWarnings("unchecked") public CriteriaResolverBaseRepository(EntityManager entityManager){ ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass(); this.c = (Class<T>) genericSuperclass.getActualTypeArguments()[0]; this.em = entityManager; joinMap = new HashMap<>(); } public List<T> getResultList(SearchObject searchObject){ return this.getQuery(searchObject).getResultList(); } public T getSingleResult(SearchObject searchObject) { return this.getQuery(searchObject).getSingleResult(); } public <D> TypedQuery<D> getGenericQuery(SearchObject searchObject, Class<D> clazz){ CriteriaQuery<D> genericCriteria; criteriaBuilder = em.getCriteriaBuilder(); genericCriteria = criteriaBuilder.createQuery(clazz); root = genericCriteria.from(c); createJoins(searchObject); setProjections(genericCriteria, clazz); List<Predicate> predicates = getPredicates(root, searchObject); genericCriteria.where(predicates.toArray(new Predicate[0])); return em.createQuery(genericCriteria); } public TypedQuery<T> getQuery(SearchObject searchObject){ criteriaBuilder = em.getCriteriaBuilder(); criteria = criteriaBuilder.createQuery(c); root = criteria.from(c); createJoins(searchObject); List<Predicate> predicates = getPredicates(root, searchObject); criteria.where(predicates.toArray(new Predicate[0])); return em.createQuery(criteria); } private void setProjections(CriteriaQuery genericCriteria, Class clazz) { List<String> projections = new ArrayList(); for(Field field: clazz.getDeclaredFields()) { projections.add(getProjection(field)); } List<Selection> selectionList = new ArrayList<>(); Selection[] selectionArray; if(projections.size() == 0) return; for (String projection : projections) { selectionList.add(getPath(projection)); } selectionArray = new Selection[selectionList.size()]; genericCriteria.multiselect(selectionList.toArray(selectionArray)); } private String getProjection(Field field) { field.setAccessible(true); String projectionPath = field.getName(); ProjectionField[] annotationsByType = field.getAnnotationsByType(ProjectionField.class); if(annotationsByType != null && annotationsByType.length == 1) { projectionPath = annotationsByType[0].projectionPath(); } return projectionPath; } private void createJoins(SearchObject searchObject) { Map<String, JoinType> joins = searchObject.getJoins(); Set<String> keySet = joins.keySet(); for (String key : keySet) { joinMap.put(key, root.join(key, joins.get(key))); } } private List<Predicate> getPredicates(Root<T> root, SearchObject searchObject) { List<Predicate> predicates = new ArrayList<>(); for(Field field: searchObject.getClass().getDeclaredFields()) { field.setAccessible(true); String fieldName; CriteriaField.ComparationType comparationType; CriteriaField[] annotationsByType = field.getAnnotationsByType(CriteriaField.class); if(annotationsByType.length == 1) { try { Object value = field.get(searchObject); if(value == null) continue; CriteriaField criteriaField = annotationsByType[0]; if(criteriaField.fieldName().equals("")) { fieldName = field.getName(); }else { fieldName = criteriaField.fieldName(); } comparationType = criteriaField.comparationType(); predicates.add(getPredicate(fieldName, comparationType, value)); }catch (Exception e) { e.printStackTrace(); } } } return predicates; } private Path getPath(String attributeName) { Path path = root; for (String part : attributeName.split("\\.")) { path = path.get(part); } return path; } @SuppressWarnings("unchecked") private Predicate getPredicate(String fieldName, CriteriaField.ComparationType comparationType, Object value) { Predicate predicate = null; switch(comparationType) { case LIKE: predicate = criteriaBuilder.like(getPath(fieldName), "%" +value + "%"); break; case STARTS_WITH: predicate = criteriaBuilder.like(getPath(fieldName), value + "%"); break; case ENDS_WITH: predicate = criteriaBuilder.like(getPath(fieldName), "%" +value); break; case GREATER_THAN: predicate = criteriaBuilder.greaterThan(getPath(fieldName), (Comparable) value); break; case GREATER_EQUALS: predicate = criteriaBuilder.greaterThanOrEqualTo(getPath(fieldName), (Comparable) value); break; case LESS_THAN: predicate = criteriaBuilder.lessThan(getPath(fieldName), (Comparable) value); break; case LESS_EQUALS: predicate = criteriaBuilder.lessThanOrEqualTo(getPath(fieldName), (Comparable) value); break; case IN: predicate = criteriaBuilder.in(getPath(fieldName)).value(value); break; case NOT_IN: predicate = criteriaBuilder.in(getPath(fieldName)).value(value).not(); break; case DIFFERENT: predicate = criteriaBuilder.notEqual(getPath(fieldName), value); break; default: predicate = criteriaBuilder.equal(getPath(fieldName), value); break; } return predicate; } }
3e09649b20bd40f5ab29fb3a72ae203a488b2fa8
615
java
Java
src/main/java/io/shirley/domainmodels/Attachment.java
cShirley14/JobPostings
56cbdb21f0a82450057081d42bdd3e63faa982af
[ "MIT" ]
null
null
null
src/main/java/io/shirley/domainmodels/Attachment.java
cShirley14/JobPostings
56cbdb21f0a82450057081d42bdd3e63faa982af
[ "MIT" ]
null
null
null
src/main/java/io/shirley/domainmodels/Attachment.java
cShirley14/JobPostings
56cbdb21f0a82450057081d42bdd3e63faa982af
[ "MIT" ]
null
null
null
19.21875
79
0.635772
3,964
/* * 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 io.shirley.domainmodels; /** * * @author Shirley */ public class Attachment { private String name; private byte[] contents; public String getName() { return name; } public void setName(String name) { this.name = name; } public byte[] getContents() { return contents; } public void setContents(byte[] contents) { this.contents = contents; } }
3e096525f1fba5ca66a49149f8c7a555fc657357
225
java
Java
sp2-tencent-cos/src/test/java/com/zgy/learn/txyuncos/TxyunCosApplicationTests.java
prayjourney/boot-mybatis-mbplus-shiro
e8e1f2de53e3486344871e32c17102a6c3b8f3b3
[ "BSD-3-Clause" ]
6
2020-10-21T02:37:49.000Z
2021-12-05T13:08:48.000Z
sp2-tencent-cos/src/test/java/com/zgy/learn/txyuncos/TxyunCosApplicationTests.java
prayjourney/boot-mybatis-mbplus-shiro
e8e1f2de53e3486344871e32c17102a6c3b8f3b3
[ "BSD-3-Clause" ]
4
2020-08-18T07:12:47.000Z
2021-02-23T14:12:14.000Z
sp2-tencent-cos/src/test/java/com/zgy/learn/txyuncos/TxyunCosApplicationTests.java
prayjourney/boot-mybatis-mbplus-shiro
e8e1f2de53e3486344871e32c17102a6c3b8f3b3
[ "BSD-3-Clause" ]
5
2020-10-21T02:37:53.000Z
2021-05-09T04:23:30.000Z
16.071429
60
0.755556
3,965
package com.zgy.learn.txyuncos; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class TxyunCosApplicationTests { @Test void contextLoads() { } }
3e09653d44743ceaf3c1cddfee48a92e898ea24b
5,166
java
Java
extern-api-java-sdk-httpclient-api/src/main/java/ru/kontur/extern_api/sdk/httpclient/api/builders/fns_inventory/FnsInventoryDraftsBuilderDocumentsApi.java
damirs11/extern-java-sdk
5f018b8e504f81de94645f59954035df03842205
[ "MIT" ]
5
2019-03-28T08:01:40.000Z
2021-09-23T10:12:55.000Z
extern-api-java-sdk-httpclient-api/src/main/java/ru/kontur/extern_api/sdk/httpclient/api/builders/fns_inventory/FnsInventoryDraftsBuilderDocumentsApi.java
damirs11/extern-java-sdk
5f018b8e504f81de94645f59954035df03842205
[ "MIT" ]
20
2018-05-10T10:00:43.000Z
2021-12-20T05:52:01.000Z
extern-api-java-sdk-httpclient-api/src/main/java/ru/kontur/extern_api/sdk/httpclient/api/builders/fns_inventory/FnsInventoryDraftsBuilderDocumentsApi.java
damirs11/extern-java-sdk
5f018b8e504f81de94645f59954035df03842205
[ "MIT" ]
9
2018-01-22T10:40:59.000Z
2021-09-23T10:13:22.000Z
35.875
125
0.687573
3,966
/* * Copyright (c) 2019 SKB Kontur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package ru.kontur.extern_api.sdk.httpclient.api.builders.fns_inventory; import ru.kontur.extern_api.sdk.httpclient.api.builders.DraftsBuilderDocumentsApi; import ru.kontur.extern_api.sdk.httpclient.api.builders.retrofit.common.RetrofitCommonDraftsBuilderDocumentsApi; import ru.kontur.extern_api.sdk.httpclient.api.builders.retrofit.fns_inventory.RetrofitFnsInventoryDraftsBuilderDocumentsApi; import ru.kontur.extern_api.sdk.model.builders.fns_inventory.FnsInventoryDraftsBuilderDocument; import ru.kontur.extern_api.sdk.model.builders.fns_inventory.FnsInventoryDraftsBuilderDocumentMeta; import ru.kontur.extern_api.sdk.model.builders.fns_inventory.FnsInventoryDraftsBuilderDocumentMetaRequest; import java.util.UUID; import java.util.concurrent.CompletableFuture; public class FnsInventoryDraftsBuilderDocumentsApi implements DraftsBuilderDocumentsApi< FnsInventoryDraftsBuilderDocument, FnsInventoryDraftsBuilderDocumentMeta, FnsInventoryDraftsBuilderDocumentMetaRequest> { private RetrofitFnsInventoryDraftsBuilderDocumentsApi specificContract; private RetrofitCommonDraftsBuilderDocumentsApi commonContract; public FnsInventoryDraftsBuilderDocumentsApi( RetrofitFnsInventoryDraftsBuilderDocumentsApi specificContract, RetrofitCommonDraftsBuilderDocumentsApi commonContract ) { this.specificContract = specificContract; this.commonContract = commonContract; } @Override public CompletableFuture<FnsInventoryDraftsBuilderDocument> create( UUID accountId, UUID draftsBuilderId, FnsInventoryDraftsBuilderDocumentMetaRequest meta ) { return specificContract.create( accountId, draftsBuilderId, meta ); } @Override public CompletableFuture<FnsInventoryDraftsBuilderDocument[]> getAll( UUID accountId, UUID draftsBuilderId ) { return specificContract.getAll( accountId, draftsBuilderId ); } @Override public CompletableFuture<FnsInventoryDraftsBuilderDocument> get( UUID accountId, UUID draftsBuilderId, UUID draftsBuilderDocumentId ) { return specificContract.get( accountId, draftsBuilderId, draftsBuilderDocumentId ); } @Override public CompletableFuture<FnsInventoryDraftsBuilderDocument> update( UUID accountId, UUID draftsBuilderId, UUID draftsBuilderDocumentId, FnsInventoryDraftsBuilderDocumentMetaRequest meta ) { return specificContract.update( accountId, draftsBuilderId, draftsBuilderDocumentId, meta ); } @Override public CompletableFuture<Void> delete( UUID accountId, UUID draftsBuilderId, UUID draftsBuilderDocumentId ) { return commonContract.delete( accountId, draftsBuilderId, draftsBuilderDocumentId ); } @Override public CompletableFuture<FnsInventoryDraftsBuilderDocumentMeta> getMeta( UUID accountId, UUID draftsBuilderId, UUID draftsBuilderDocumentId ) { return specificContract.getMeta( accountId, draftsBuilderId, draftsBuilderDocumentId ); } @Override public CompletableFuture<FnsInventoryDraftsBuilderDocumentMeta> updateMeta( UUID accountId, UUID draftsBuilderId, UUID draftsBuilderDocumentId, FnsInventoryDraftsBuilderDocumentMetaRequest newMeta ) { return specificContract.updateMeta( accountId, draftsBuilderId, draftsBuilderDocumentId, newMeta ); } }
3e096593f786121cda0a7f1778f5a7695aadfad5
5,919
java
Java
src-gen/fr/imag/adele/cadse/cadseg/managers/build/exporter/ExporterManager.java
chomats/cadse.model-cadseg
5fffcafc02b665038049b26e40bb3daf114c6959
[ "Apache-2.0" ]
null
null
null
src-gen/fr/imag/adele/cadse/cadseg/managers/build/exporter/ExporterManager.java
chomats/cadse.model-cadseg
5fffcafc02b665038049b26e40bb3daf114c6959
[ "Apache-2.0" ]
null
null
null
src-gen/fr/imag/adele/cadse/cadseg/managers/build/exporter/ExporterManager.java
chomats/cadse.model-cadseg
5fffcafc02b665038049b26e40bb3daf114c6959
[ "Apache-2.0" ]
null
null
null
23.211765
90
0.683055
3,967
/* * 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. * * Copyright (C) 2006-2010 Adele Team/LIG/Grenoble University, France */ package fr.imag.adele.cadse.cadseg.managers.build.exporter; import java.util.ArrayList; import java.util.List; import fede.workspace.eclipse.java.JavaIdentifier; import fr.imag.adele.cadse.cadseg.managers.IExtendClassManager; import fr.imag.adele.cadse.core.CadseGCST; import fr.imag.adele.cadse.core.DefaultItemManager; import fr.imag.adele.cadse.core.Item; import fr.imag.adele.cadse.core.LinkType; import fr.imag.adele.cadse.core.build.Exporter; import fr.imag.adele.cadse.core.util.Convert; /** * The Class ExporterManager. * * @generated */ public class ExporterManager extends DefaultItemManager implements IExtendClassManager { /** * The Constructor. * * @generated */ public ExporterManager() { super(); } /** * @generated */ @Override public String computeQualifiedName(Item item, String name, Item parent, LinkType lt) { StringBuilder sb = new StringBuilder(); try { Object value; Item currentItem; sb.append(parent.getQualifiedName()); if (sb.length() != 0) { sb.append("."); } sb.append(name); return sb.toString(); } catch (Throwable e) { e.printStackTrace(); return "error"; } } /** * Gets the types attribute. * * @param exporter * the exporter * * @return the types attribute * * @generated */ @SuppressWarnings("unchecked") public static final List<String> getTypesAttribute(Item exporter) { try { List<String> list = exporter.getAttribute(CadseGCST.EXPORTER_at_TYPES_); if (list == null) return null; return new ArrayList<String>(list); } catch (Throwable t) { return new ArrayList<String>(); } } /** * Sets the types attribute. * * @param exporter * the exporter * @param valueList * the value list * * @generated */ @SuppressWarnings("unchecked") public static final void setTypesAttribute(Item exporter, List<String> valueList) { try { List<String> list = new ArrayList<String>(valueList); exporter.setAttribute(CadseGCST.EXPORTER_at_TYPES_, list); } catch (Throwable t) { } } /** * Adds the types attribute. * * @param exporter * the exporter * @param value * the value * * @generated */ @SuppressWarnings("unchecked") public static final void addTypesAttribute(Item exporter, String value) { try { List<String> list = exporter.getAttribute(CadseGCST.EXPORTER_at_TYPES_); if (list == null) { list = new ArrayList<String>(); } list.add(value); exporter.setAttribute(CadseGCST.EXPORTER_at_TYPES_, list); } catch (Throwable t) { } } /** * Removes the types attribute. * * @param exporter * the exporter * @param value * the value * * @generated */ @SuppressWarnings("unchecked") public static final void removeTypesAttribute(Item exporter, String value) { try { List<String> list = exporter.getAttribute(CadseGCST.EXPORTER_at_TYPES_); if (list == null) { return; } list.remove(value); if (list.size() == 0) exporter.setAttribute(CadseGCST.EXPORTER_at_TYPES_, null); else exporter.setAttribute(CadseGCST.EXPORTER_at_TYPES_, list); } catch (Throwable t) { } } /* * (non-Javadoc) * * @see * model.workspace.workspace.managers.IExtendClassManager#mustBeExtended() */ public boolean mustBeExtended() { return true; } /** * Checks if is extends class. * * @param contentmodel * the contentmodel * * @return true, if is extends class */ public static final boolean isExtendsClass(Item contentmodel) { Object value = contentmodel.getAttribute(CadseGCST.RUNTIME_ITEM_at_EXTENDS_CLASS_); if (value == null) { return false; } try { return Convert.toBooleanFalseIfNull(value); } catch (Throwable t) { return false; } } /* * (non-Javadoc) * * @see * fede.workspace.model.manager.DefaultItemManager#getDisplayName(fr.imag * .adele.cadse.core.Item) */ @Override public String getDisplayName(Item item) { return item.getName(); } /* * (non-Javadoc) * * @see * model.workspace.workspace.managers.IExtendClassManager#getClassName(fr * .imag.adele.cadse.core.Item) */ public String getClassName(Item uc) { return (mustBeExtended() || isExtendsClass(uc)) ? JavaIdentifier .javaIdentifierFromString(uc.getName(), true, false, "Exporter") : getDefaultClassName().getSimpleName(); } /** The Constant DEFAUL_CLASS_NAME. */ public static final String DEFAUL_CLASS_NAME = "fr.imag.adele.cadse.core.build.Exporter"; /* * (non-Javadoc) * * @see * model.workspace.workspace.managers.IExtendClassManager#getDefaultClassName * () */ public Class<?> getDefaultClassName() { return Exporter.class; } /* * (non-Javadoc) * * @see * model.workspace.workspace.IModelWorkspaceManager#getWorkspaceModel(fr * .imag.adele.cadse.core.Item) */ public Item getWorkspaceModel(Item source) { // TODO Auto-generated method stub return null; } }
3e0965a642258139d4aa6ab085b146791f48d40b
997
java
Java
core/server/project/commonBase/src/main/java/com/home/commonBase/scene/role/RoleAttributeLogic.java
hw233/home3
a15a63694918483b2e4853edab197b5cdddca560
[ "Apache-2.0" ]
8
2020-08-17T09:54:20.000Z
2021-02-08T05:25:02.000Z
core/server/project/commonBase/src/main/java/com/home/commonBase/scene/role/RoleAttributeLogic.java
shineTeam7/home3
a15a63694918483b2e4853edab197b5cdddca560
[ "Apache-2.0" ]
null
null
null
core/server/project/commonBase/src/main/java/com/home/commonBase/scene/role/RoleAttributeLogic.java
shineTeam7/home3
a15a63694918483b2e4853edab197b5cdddca560
[ "Apache-2.0" ]
5
2020-07-24T03:07:08.000Z
2021-11-17T14:20:15.000Z
16.344262
76
0.71013
3,968
package com.home.commonBase.scene.role; import com.home.commonBase.logic.role.RoleAttributeDataLogic; import com.home.commonBase.scene.base.RoleLogicBase; import com.home.shine.support.collection.IntIntMap; /** 玩家属性逻辑 */ public class RoleAttributeLogic extends RoleLogicBase { /** 属性模块 */ protected RoleAttributeDataLogic _aTool; @Override public void construct() { super.construct(); (_aTool=new RoleAttributeDataLogic()).setParent(this); } @Override public void init() { super.init(); _aTool.setData(_data.attribute.attributes); } @Override public void onFrame(int delay) { super.onFrame(delay); _aTool.onPiece(delay); } /** 获取属性逻辑 */ public RoleAttributeDataLogic getAttribute() { return _aTool; } /** 推送自己属性 */ public void sendSelfAttribute(IntIntMap dic) { } /** 推送别人属性 */ public void sendOtherAttribute(IntIntMap dic) { } /** 属性改变 */ public void onAttributeChange(int[] changeList,int num,boolean[] changeSet) { } }
3e0966d7c3ebb80eb77630fb1da4e1569e09da0b
3,947
java
Java
web/src/main/java/org/jboss/cdi/tck/tests/extensions/annotated/delivery/ejb/EnterpriseWithAnnotationsTest.java
manovotn/cdi-tck
a14899cc9345792808c8905d01219beb2b5cc505
[ "Apache-2.0" ]
3
2019-09-13T12:11:32.000Z
2022-02-05T16:09:05.000Z
web/src/main/java/org/jboss/cdi/tck/tests/extensions/annotated/delivery/ejb/EnterpriseWithAnnotationsTest.java
manovotn/cdi-tck
a14899cc9345792808c8905d01219beb2b5cc505
[ "Apache-2.0" ]
107
2019-11-13T13:07:39.000Z
2022-03-31T11:15:35.000Z
web/src/main/java/org/jboss/cdi/tck/tests/extensions/annotated/delivery/ejb/EnterpriseWithAnnotationsTest.java
manovotn/cdi-tck
a14899cc9345792808c8905d01219beb2b5cc505
[ "Apache-2.0" ]
14
2020-02-26T15:49:34.000Z
2022-03-24T15:20:07.000Z
43.855556
144
0.764378
3,969
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.cdi.tck.tests.extensions.annotated.delivery.ejb; import static org.jboss.cdi.tck.TestGroups.INTEGRATION; import static org.jboss.cdi.tck.cdi.Sections.PROCESS_ANNOTATED_TYPE; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.util.List; import jakarta.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.cdi.tck.AbstractTest; import org.jboss.cdi.tck.shrinkwrap.ee.WebArchiveBuilder; import org.jboss.cdi.tck.tests.full.extensions.annotated.delivery.Baby; import org.jboss.cdi.tck.tests.full.extensions.annotated.delivery.Chicken; import org.jboss.cdi.tck.tests.full.extensions.annotated.delivery.Desired; import org.jboss.cdi.tck.tests.full.extensions.annotated.delivery.MetaAnnotation; import org.jboss.cdi.tck.tests.full.extensions.annotated.delivery.ProcessAnnotatedTypeObserver; import org.jboss.cdi.tck.tests.full.extensions.annotated.delivery.Wanted; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.test.audit.annotations.SpecAssertion; import org.jboss.test.audit.annotations.SpecAssertions; import org.jboss.test.audit.annotations.SpecVersion; import org.testng.annotations.Test; /** * @author Martin Kouba * */ @Test(groups = INTEGRATION) @SpecVersion(spec = "cdi", version = "2.0") public class EnterpriseWithAnnotationsTest extends AbstractTest { @SuppressWarnings("unchecked") @Deployment public static WebArchive createTestArchive() { return new WebArchiveBuilder() .withTestClass(EnterpriseWithAnnotationsTest.class) .withClasses(Baby.class, Desired.class, ProcessAnnotatedTypeObserver.class, Hawk.class, Wanted.class, Chicken.class, MetaAnnotation.class).withExtensions(ProcessAnnotatedTypeObserver.class).build(); } @Inject ProcessAnnotatedTypeObserver processAnnotatedTypeObserver; @Test @SpecAssertions({ @SpecAssertion(section = PROCESS_ANNOTATED_TYPE, id = "fc") }) public void testDelivery() { List<Class<?>> processedDesiredAnWantedTypes = processAnnotatedTypeObserver.getProcessedDesiredAndWantedTypes(); assertFalse(processedDesiredAnWantedTypes.isEmpty()); assertEquals(processedDesiredAnWantedTypes.size(), 1); assertTrue(processedDesiredAnWantedTypes.contains(Hawk.class)); List<Class<?>> processedDesiredTypes = processAnnotatedTypeObserver.getProcessedDesiredTypes(); assertFalse(processedDesiredTypes.isEmpty()); assertEquals(processedDesiredTypes.size(), 1); } @Test @SpecAssertions({ @SpecAssertion(section = PROCESS_ANNOTATED_TYPE, id = "fc"), @SpecAssertion(section = PROCESS_ANNOTATED_TYPE, id = "g") }) public void testDeliveryMetaAnnotation() { List<Class<?>> processedTypes = processAnnotatedTypeObserver.getProcessedMetaAnnotationTypes(); assertFalse(processedTypes.isEmpty()); assertEquals(processedTypes.size(), 2); assertTrue(processedTypes.contains(Hawk.class)); assertTrue(processedTypes.contains(Chicken.class)); } }
3e09690efbe24f81f46163be5d7329f7e482ccc4
1,254
java
Java
sql/core/target/java/org/apache/spark/sql/streaming/StreamingQueryException.java
Y-sir/spark-cn
06a0459999131ee14864a69a15746c900e815a14
[ "BSD-2-Clause", "Apache-2.0", "CC0-1.0", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
sql/core/target/java/org/apache/spark/sql/streaming/StreamingQueryException.java
Y-sir/spark-cn
06a0459999131ee14864a69a15746c900e815a14
[ "BSD-2-Clause", "Apache-2.0", "CC0-1.0", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
sql/core/target/java/org/apache/spark/sql/streaming/StreamingQueryException.java
Y-sir/spark-cn
06a0459999131ee14864a69a15746c900e815a14
[ "BSD-2-Clause", "Apache-2.0", "CC0-1.0", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
57
210
0.732855
3,970
package org.apache.spark.sql.streaming; /** * Exception that stopped a {@link StreamingQuery}. Use <code>cause</code> get the actual exception * that caused the failure. * param: message Message of this exception * param: cause Internal cause of this exception * param: startOffset Starting offset in json of the range of data in which exception occurred * param: endOffset Ending offset in json of the range of data in exception occurred * @since 2.0.0 */ public class StreamingQueryException extends java.lang.Exception { // not preceding StreamingQueryException (java.lang.String queryDebugString, java.lang.String message, java.lang.Throwable cause, java.lang.String startOffset, java.lang.String endOffset) { throw new RuntimeException(); } public java.lang.Throwable cause () { throw new RuntimeException(); } public java.lang.String endOffset () { throw new RuntimeException(); } public java.lang.String message () { throw new RuntimeException(); } public java.lang.String startOffset () { throw new RuntimeException(); } /** Time when the exception occurred */ public long time () { throw new RuntimeException(); } public java.lang.String toString () { throw new RuntimeException(); } }
3e0969389c3dd279e5e5eee0a017ed1020104869
3,283
java
Java
src/main/java/edu/xjtu/social/controller/HobbyController.java
qianqianjun/social-recommend
8098e0495c355dd9105420c084b6bc409f6b2aec
[ "MIT" ]
7
2021-04-10T16:03:10.000Z
2022-03-03T07:14:00.000Z
src/main/java/edu/xjtu/social/controller/HobbyController.java
qianqianjun/social-recommend
8098e0495c355dd9105420c084b6bc409f6b2aec
[ "MIT" ]
null
null
null
src/main/java/edu/xjtu/social/controller/HobbyController.java
qianqianjun/social-recommend
8098e0495c355dd9105420c084b6bc409f6b2aec
[ "MIT" ]
3
2021-04-16T07:04:20.000Z
2021-12-23T03:31:22.000Z
35.684783
96
0.662199
3,971
package edu.xjtu.social.controller; import edu.xjtu.social.dao.FollowDao; import edu.xjtu.social.dao.HobbyDao; import edu.xjtu.social.dao.LikeDao; import edu.xjtu.social.domain.node.User; import edu.xjtu.social.domain.util.ResponseInfo; import edu.xjtu.social.domain.node.Hobby; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.Map; @Controller public class HobbyController { public static boolean contains(ArrayList<Hobby> hobbies,Hobby target){ for (Hobby hobby : hobbies) { if (hobby.getId().equals(target.getId())) return true; } return false; } @Autowired HobbyDao hobbyDao; @Autowired LikeDao likeDao; @Autowired FollowDao followDao; @GetMapping("/hobby/getall") public String getAll(HttpServletRequest request, Map<String,Object> map){ HttpSession session=request.getSession(); User user=(User) session.getAttribute("user"); if(user==null) return "login"; ArrayList<Hobby> hobbies=(ArrayList<Hobby>) hobbyDao.getAllHobbies(); ArrayList<Hobby> myhobbies=(ArrayList<Hobby>) hobbyDao.getMyHobby(user.getAccount()); ArrayList<Hobby> res=new ArrayList<>(); for (Hobby hobby : hobbies) { if (contains(myhobbies, hobby)) continue; res.add(hobby); } Integer following_num=followDao.getMyFollowing(user.getAccount()).size(); Integer follower_num=followDao.getPeopleWhoFollowMe(user.getAccount()).size(); map.put("myfollowing",following_num); map.put("follower",follower_num); map.put("hobbies",res); map.put("myhobbies",myhobbies); map.put("user",user); return "hobbys"; } @PostMapping("/hobby/addhobby") @ResponseBody public ResponseInfo addHobby(@RequestParam("hname") String hname, @RequestParam("htype") String htype){ Hobby hobby=hobbyDao.addHobby(hname,htype); if(hobby==null){ return new ResponseInfo("fail",false,null); } return new ResponseInfo("sucess",true,hobby); } @PostMapping("/hobby/delete") @ResponseBody public ResponseInfo deleteHobby(@RequestParam("id") Long id){ Hobby hobby=hobbyDao.deleteWithId(id); return new ResponseInfo("success",true,hobby); } @GetMapping("/hobby/search") @ResponseBody public ResponseInfo search(@RequestParam("hname") String hname){ ArrayList<Hobby> hobbies=(ArrayList<Hobby>) hobbyDao.searchHobbyByName(".*"+hname+".*"); return new ResponseInfo("",true,hobbies); } @PostMapping("/hobby/fix") @ResponseBody public ResponseInfo fix(@RequestParam("id") Long id, @RequestParam("hname") String hname, @RequestParam("htype") String htype){ Hobby hobby=hobbyDao.fixHobby(id,hname,htype); if(hobby!=null){ return new ResponseInfo("修改成功",true,hobby); } return new ResponseInfo("修改失败",false,null); } }
3e096a512ac13ece694b76466c47194a378517ee
1,131
java
Java
src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest31.java
haimli/druid
97ed996c05380cc817a4d527ebe7d5f79e9d11ec
[ "Apache-2.0" ]
25
2016-06-19T09:26:05.000Z
2021-08-10T13:11:40.000Z
src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest31.java
haimli/druid
97ed996c05380cc817a4d527ebe7d5f79e9d11ec
[ "Apache-2.0" ]
null
null
null
src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest31.java
haimli/druid
97ed996c05380cc817a4d527ebe7d5f79e9d11ec
[ "Apache-2.0" ]
16
2015-09-06T04:12:22.000Z
2019-12-12T06:33:22.000Z
29.763158
76
0.69496
3,972
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.bvt.filter.wall.mysql; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.wall.WallUtils; /** * SQLServerWallTest * * @author RaymondXiu * @version 1.0, 2012-3-18 * @see */ public class MySqlWallTest31 extends TestCase { public void test_false() throws Exception { Assert.assertFalse(WallUtils.isValidateMySql(// "select * from t where FID = 1 OR UNHEX(HEX(FNAME)) = FNAME")); // } }
3e096bbd49abb2600c90fe8ad2ecb0985c43df4a
1,202
java
Java
jbm-framework/jbm-framework-autoconfigure/jbm-framework-autoconfigure-rocketmq/src/test/java/com/jbm/test/rocketmq/demo/Demo01Producer.java
numen06/JBM
a32782a91068e8cb2fd8c04c1ad9303202658071
[ "Apache-2.0" ]
6
2018-12-09T16:18:06.000Z
2019-11-03T07:41:34.000Z
jbm-framework/jbm-framework-autoconfigure/jbm-framework-autoconfigure-rocketmq/src/test/java/com/jbm/test/rocketmq/demo/Demo01Producer.java
numen06/JBM
a32782a91068e8cb2fd8c04c1ad9303202658071
[ "Apache-2.0" ]
8
2019-12-02T11:37:50.000Z
2022-03-10T02:19:05.000Z
jbm-framework/jbm-framework-autoconfigure/jbm-framework-autoconfigure-rocketmq/src/test/java/com/jbm/test/rocketmq/demo/Demo01Producer.java
numen06/JBM
a32782a91068e8cb2fd8c04c1ad9303202658071
[ "Apache-2.0" ]
3
2019-03-25T05:33:08.000Z
2022-03-09T05:25:22.000Z
30.820513
75
0.707987
3,973
package com.jbm.test.rocketmq.demo; import org.apache.rocketmq.client.producer.SendCallback; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Demo01Producer { @Autowired private RocketMQTemplate rocketMQTemplate; public SendResult syncSend(Integer id) { // 创建 Demo01Message 消息 Demo01Message message = new Demo01Message(); message.setId(id); // 同步发送消息 return rocketMQTemplate.syncSend(Demo01Message.TOPIC, message); } public void asyncSend(Integer id, SendCallback callback) { // 创建 Demo01Message 消息 Demo01Message message = new Demo01Message(); message.setId(id); // 异步发送消息 rocketMQTemplate.asyncSend(Demo01Message.TOPIC, message, callback); } public void onewaySend(Integer id) { // 创建 Demo01Message 消息 Demo01Message message = new Demo01Message(); message.setId(id); // oneway 发送消息 rocketMQTemplate.sendOneWay(Demo01Message.TOPIC, message); } }
3e096d5c7f107cd4ac17e6c7b7e989dac2a12c99
492
java
Java
main-module/src/main/java/com/diffblue/javatest/nestedobjects/User.java
krobelus/java-test
1563e52e41c17478d78e9dd674025499c510ee6f
[ "BSD-4-Clause" ]
null
null
null
main-module/src/main/java/com/diffblue/javatest/nestedobjects/User.java
krobelus/java-test
1563e52e41c17478d78e9dd674025499c510ee6f
[ "BSD-4-Clause" ]
null
null
null
main-module/src/main/java/com/diffblue/javatest/nestedobjects/User.java
krobelus/java-test
1563e52e41c17478d78e9dd674025499c510ee6f
[ "BSD-4-Clause" ]
1
2018-11-26T14:44:43.000Z
2018-11-26T14:44:43.000Z
21.391304
63
0.693089
3,974
package com.diffblue.javatest.nestedobjects; import com.diffblue.javatest.nestedobjects.subpackage.Item; import com.diffblue.javatest.nestedobjects.subpackage.Order; public class User { public User(Order order) { this.order = order; } /** * Checks if an item costs the same as the user's order item. */ public boolean checkItemCost(Item item) { if (!order.hasItem()) { return false; } return order.item.cost == item.cost; } private Order order; }
3e096de3d112e374dc9a60daac348274cf8d6366
989
java
Java
challenges/src/main/java/challenges/DataStructures/Library.java
kuya32/data-structures-and-algorithms
c7774b8affa9862756f9af5215591131cc3a5ad2
[ "MIT" ]
1
2020-08-10T21:59:24.000Z
2020-08-10T21:59:24.000Z
challenges/src/main/java/challenges/DataStructures/Library.java
kuya32/data-structures-and-algorithms
c7774b8affa9862756f9af5215591131cc3a5ad2
[ "MIT" ]
null
null
null
challenges/src/main/java/challenges/DataStructures/Library.java
kuya32/data-structures-and-algorithms
c7774b8affa9862756f9af5215591131cc3a5ad2
[ "MIT" ]
null
null
null
24.725
93
0.53185
3,975
/* * This Java source file was generated by the Gradle 'init' task. */ package challenges.DataStructures; public class Library { public boolean someLibraryMethod() { return true; } } // Node head = null; // Node tail = null; // // public void insert(String value) { // Node node = new Node(value); // if(head == null) { // head = node; // tail = node; // } else { // node.next = head; // head = node; // } // } // // public String toString() { // String output = ""; // Node currentNodeIAmLookingAt = head; // while(currentNodeIAmLookingAt != null) { // output = output + System.out.printf("{%s} -> ", currentNodeIAmLookingAt.value); // currentNodeIAmLookingAt = currentNodeIAmLookingAt.next; // } // output = output + "null"; // return output; // } // public static boolean includes(String value) { // // }
3e096e725d9e8cbd9e5afb13af3301da8c12a306
7,785
java
Java
sponge/src/main/java/com/griefdefender/configuration/category/VisualCategory.java
ItsFlicker/GriefDefender
a05a0dededc47f6075f367d89341aeed0f7d9f3a
[ "MIT" ]
104
2019-06-16T00:15:27.000Z
2022-03-22T07:15:14.000Z
sponge/src/main/java/com/griefdefender/configuration/category/VisualCategory.java
ItsFlicker/GriefDefender
a05a0dededc47f6075f367d89341aeed0f7d9f3a
[ "MIT" ]
423
2019-07-24T01:50:30.000Z
2022-03-24T21:59:24.000Z
sponge/src/main/java/com/griefdefender/configuration/category/VisualCategory.java
ItsFlicker/GriefDefender
a05a0dededc47f6075f367d89341aeed0f7d9f3a
[ "MIT" ]
142
2019-07-25T06:44:26.000Z
2022-03-19T14:55:06.000Z
70.135135
184
0.741683
3,976
/* * This file is part of GriefDefender, licensed under the MIT License (MIT). * * Copyright (c) bloodmc * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.griefdefender.configuration.category; import ninja.leaping.configurate.objectmapping.Setting; import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; import org.spongepowered.api.MinecraftVersion; import org.spongepowered.api.Sponge; @ConfigSerializable public class VisualCategory extends ConfigCategory { @Setting(value = "hide-borders-when-using-wecui", comment = "Whether to hide the glowstone/gold block borders when using WECUI.") public boolean hideBorders = false; @Setting(value = "hide-fillers-when-using-wecui", comment = "Whether to hide the block fillers when using WECUI.") public boolean hideFillers = false; @Setting(value = "hide-wecui-drag-visuals-2d", comment = "Whether drag visuals should be shown while creating a claim in 2D mode.") public boolean hideDrag2d = true; @Setting(value = "cuboid-level-visuals-2d", comment = "Whether to use cuboid visuals, in 2D claims, during inspection with owner min/max claim levels between 0 and 255." + "\nNote: WECUI visuals are not associated to this option." + "\nNote: If enabled, this will send many block updates to players causing more client strain depending on size of claim. Use with caution.") public boolean cuboidLevelVisuals = false; @Setting(value = "client-visuals-per-tick", comment = "The amount of block visuals a client can receive per tick when showing/hiding claims. Default: 12") public int clientVisualsPerTick = 12; @Setting(value = "claim-create-block", comment = "The visual block used during claim creation. (Default: minecraft:diamond_block)") public String claimCreateStartBlock = "minecraft:diamond_block"; @Setting(value = "filler-spacing", comment = "The space between each filler visual block.") public int fillerSpacing = 10; @Setting(value = "active-claim-visual-time", comment = "The active time, in seconds, to keep a claim's visuals shown to a player. (Default: 60)" + "\nNote: If value is <= 0, GD will use the default value.") public int claimVisualTime = 60; @Setting(value = "active-create-block-visual-time", comment = "The active time, in seconds, to keep a claim's create block visual shown to a player. (Default: 180)" + "\nNote: This only applies during claim creation." + "\nNote: If value is <= 0, GD will use the default value.") public int createBlockVisualTime = 180; @Setting(value = "admin-accent-block", comment = "The visual accent block used for admin claims. (Default: minecraft:pumpkin)") public String visualAdminAccentBlock = "minecraft:pumpkin"; @Setting(value = "admin-corner-block", comment = "The visual corner block used for admin claims. (Default: minecraft:glowstone)") public String visualAdminCornerBlock = "minecraft:glowstone"; @Setting(value = "admin-filler-block", comment = "The visual filler block used for admin claims. (Default: minecraft:pumpkin)") public String visualAdminFillerBlock = "minecraft:pumpkin"; @Setting(value = "basic-accent-block", comment = "The visual accent block used for basic claims. (Default: minecraft:gold_block)") public String visualBasicAccentBlock = "minecraft:gold_block"; @Setting(value = "basic-corner-block", comment = "The visual corner block used for basic claims. (Default: minecraft:glowstone)") public String visualBasicCornerBlock = "minecraft:glowstone"; @Setting(value = "basic-filler-block", comment = "The visual filler block used for basic claims. (Default: minecraft:gold_block)") public String visualBasicFillerBlock = "minecraft:gold_block"; @Setting(value = "error-accent-block", comment = "The visual accent block used to visualize an error in a claim. (Default: minecraft:netherrack)") public String visualErrorAccentBlock = "minecraft:netherrack"; @Setting(value = "error-corner-block", comment = "The visual corner block used to visualize an error in a claim. (Default: minecraft:redstone_ore)") public String visualErrorCornerBlock = "minecraft:redstone_ore"; @Setting(value = "error-filler-block", comment = "The visual filler block used to visualize an error in a claim. (Default: minecraft:diamond_block)") public String visualErrorFillerBlock = "minecraft:diamond_block"; @Setting(value = "subdivision-accent-block", comment = "The visual accent block used for subdivision claims. (Default: minecraft:white_wool or minecraft:wool for legacy versions)") public String visualSubdivisionAccentBlock; @Setting(value = "subdivision-corner-block", comment = "The visual corner block used for subdivision claims. (Default: minecraft:iron_block)") public String visualSubdivisionCornerBlock = "minecraft:iron_block"; @Setting(value = "subdivision-filler-block", comment = "The visual filler block used for subdivision claims. (Default: minecraft:white_wool or minecraft:wool for legacy versions)") public String visualSubdivisionFillerBlock; @Setting(value = "town-accent-block", comment = "The visual accent block used for town claims. (Default: minecraft:emerald_block)") public String visualTownAccentBlock = "minecraft:emerald_block"; @Setting(value = "town-corner-block", comment = "The visual corner block used for town claims. (Default: minecraft:glowstone)") public String visualTownCornerBlock = "minecraft:glowstone"; @Setting(value = "town-filler-block", comment = "The visual filler block used for town claims. (Default: minecraft:emerald_block)") public String visualTownFillerBlock = "minecraft:emerald_block"; @Setting(value = "nature-accent-block", comment = "The visual accent block used while in restore nature mode. (Default: minecraft:diamond_block)") public String visualNatureAccentBlock = "minecraft:diamond_block"; @Setting(value = "nature-corner-block", comment = "The visual corner block used while in restore nature mode. (Default: minecraft:diamond_block)") public String visualNatureCornerBlock = "minecraft:diamond_block"; public VisualCategory() { final MinecraftVersion version = Sponge.getPlatform().getMinecraftVersion(); if (version.getName().contains("1.8.8") || version.getName().contains("1.12")) { this.visualSubdivisionAccentBlock = "minecraft:wool"; this.visualSubdivisionFillerBlock = "minecraft:wool"; } else { this.visualSubdivisionAccentBlock = "minecraft:white_wool"; this.visualSubdivisionFillerBlock = "minecraft:white_wool"; } } }
3e096f24806affdc1993d8fdf72187cfb9ddd324
1,715
java
Java
EIDAS-Sources-1.4.5-MDSL/EIDAS-SAMLEngine/src/main/java/eu/eidas/auth/engine/metadata/MetadataFetcherI.java
swedenconnect/eidas-eu-mock
9f6d67af4085f7bde35faadd0d79891c17c8e67c
[ "Apache-2.0" ]
5
2019-02-24T15:49:59.000Z
2020-06-09T08:15:00.000Z
EIDAS-Sources-1.4.5-MDSL/EIDAS-SAMLEngine/src/main/java/eu/eidas/auth/engine/metadata/MetadataFetcherI.java
elegnamnden/eidas-eu-mock
a1ae9a3c497f1ca9906a8aa9e3f01e899d04c40c
[ "Apache-2.0" ]
11
2019-06-12T16:08:09.000Z
2022-03-31T20:59:55.000Z
EIDAS-Sources-1.4.5-MDSL/EIDAS-SAMLEngine/src/main/java/eu/eidas/auth/engine/metadata/MetadataFetcherI.java
elegnamnden/eidas-eu-mock
a1ae9a3c497f1ca9906a8aa9e3f01e899d04c40c
[ "Apache-2.0" ]
1
2018-10-25T18:57:50.000Z
2018-10-25T18:57:50.000Z
38.977273
114
0.759767
3,977
/* * This work is Open Source and licensed by the European Commission under the * conditions of the European Public License v1.1 * * (http://www.osor.eu/eupl/european-union-public-licence-eupl-v.1.1); * * any use of this file implies acceptance of the conditions of this 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 eu.eidas.auth.engine.metadata; import javax.annotation.Nonnull; import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.xml.signature.SignableXMLObject; import eu.eidas.engine.exceptions.EIDASSAMLEngineException; /** * Retrieves SAML2 metadata {code EntityDescriptor}s associated with a SAML Service Provider (SP) and/or Identity * Provider (IDP). * * @since 1.1 */ public interface MetadataFetcherI { /** * Returns the metadata EntityDescriptor instance fetched from the given URL. * * @param url the url of the metadata file * @param metadataSigner the metadataSigner which can be used to verify the digital signature of the retrieved * EntityDescriptor via the ({@link MetadataSignerI#validateMetadataSignature(SignableXMLObject)} method. * @return the entity descriptor associated with the given url. * @throws EIDASSAMLEngineException in case of errors */ @Nonnull EntityDescriptor getEntityDescriptor(@Nonnull String url, @Nonnull MetadataSignerI metadataSigner) throws EIDASSAMLEngineException; }
3e096f2bcb8f4f83873d15dfaf9ac4ba6073b7e1
11,710
java
Java
app/src/main/java/com/example/popularmoviesstage2/activities/DetailActivity.java
acasadoquijada/popularmovies-stage2
850b49cc8abc099db81bd0d7707ce57def899f2d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/popularmoviesstage2/activities/DetailActivity.java
acasadoquijada/popularmovies-stage2
850b49cc8abc099db81bd0d7707ce57def899f2d
[ "Apache-2.0" ]
5
2020-02-21T09:29:56.000Z
2020-03-09T14:45:04.000Z
app/src/main/java/com/example/popularmoviesstage2/activities/DetailActivity.java
acasadoquijada/popularmovies-stage2
850b49cc8abc099db81bd0d7707ce57def899f2d
[ "Apache-2.0" ]
null
null
null
34.139942
98
0.608284
3,978
package com.example.popularmoviesstage2.activities; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.databinding.DataBindingUtil; import android.content.Intent; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.ToggleButton; import com.example.popularmoviesstage2.database.MovieDataBase; import com.example.popularmoviesstage2.movie.Movie; import com.example.popularmoviesstage2.R; import com.example.popularmoviesstage2.utilities.AppExecutor; import com.squareup.picasso.Picasso; import com.example.popularmoviesstage2.databinding.ActivityDetailBinding; /** * Activity class that presents the movie details to the user * */ public class DetailActivity extends AppCompatActivity { private Movie movie; private MovieDataBase movieDataBase; private final String toogle_button_token = "toogle_button"; private boolean toggle_button_pressed; private int pos; /** * onCreate method run when the Activity is created * To avoid errors such as: Android E/Parcel﹕ Class not found when unmarshalling * * It reconstructs a Movie object passed as Parcelable within a Bundle * * This StackOverflow post have been followed: * https://stackoverflow.com/questions/28589509/ * android-e-parcel-class-not-found-when-unmarshalling-only-on-samsung-tab3 * * @param savedInstanceState bundle object */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); ActivityDetailBinding mBinding = DataBindingUtil.setContentView(this, R.layout.activity_detail); movieDataBase = MovieDataBase.getInstance(getApplicationContext()); Intent intent; intent = getIntent(); if (intent != null) { Bundle b = intent.getBundleExtra(MainActivity.bundle_token); if (b != null && b.getParcelable(MainActivity.parcelable_token) != null) { movie = b.getParcelable(MainActivity.parcelable_token); pos = intent.getIntExtra(MainActivity.movie_pos_token,-1); if (movie != null) { // Movie poster Picasso.get().load(movie.getPoster_path()).into(mBinding.moviePoster); // Movie original_title mBinding.title.setText(movie.getOriginal_title()); // Movie overview mBinding.overview.setText(movie.getOverview()); // Movie release date String release_date_help_text = "Release date: "; mBinding.releaseDate.setText(release_date_help_text); mBinding.releaseDate.append(movie.getRelease_date()); // Movie vote average String vote_average_help_text = "Vote average: "; mBinding.voteAverage.setText(vote_average_help_text); mBinding.voteAverage.append(movie.getVote_average() + "/10"); // We check if the movie is in the fav database. If so, we update the toggle setUpToggleButton(mBinding.favTogglebutton); // Add the trailers and reviews to the layout addTrailers(movie); addReviews(movie); } } } } /** * Setups the corresponding checked state and its listener * @param toggleButton to modify */ private void setUpToggleButton(final ToggleButton toggleButton){ updateToggleButton(toggleButton); setOnCheckedChangeListener(toggleButton); } private void setOnCheckedChangeListener(final ToggleButton toggleButton){ toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ AppExecutor.getsInstance().diskIO().execute(new Runnable() { @Override public void run() { if(movieDataBase.movieDAO().getMovie(movie.getId()) == null){ movieDataBase.movieDAO().insertMovie(movie); } } }); } else { AppExecutor.getsInstance().diskIO().execute(new Runnable() { @Override public void run() { movieDataBase.movieDAO().deleteMovie(movie); runOnUiThread(new Runnable() { @Override public void run() { MainActivity.mAdapter.removeMovie(pos); } }); } }); } } }); } private void updateToggleButton(final ToggleButton toggle) { AppExecutor.getsInstance().diskIO().execute(new Runnable() { @Override public void run() { if (movieDataBase.movieDAO().getMovie(movie.getId()) != null) { runOnUiThread(new Runnable() { @Override public void run() { toggle.setChecked(true); } }); } } }); } /** * In case a movie doesn't have trailers and/or reviews we display an informative text * @param layout_id that identifies if the movie doesn't have trailers or reviews */ private void noReviewOrTrailer(int layout_id){ LinearLayout contraConstraintLayout = findViewById(layout_id); TextView textView = new TextView(this); String no_reviews_trailers_text = ""; if(layout_id == R.id.review_linear_layout){ no_reviews_trailers_text = getString(R.string.no_reviews); } else if(layout_id == R.id.trailer_linear_layout){ no_reviews_trailers_text = getString(R.string.no_trailer); } textView.setText(no_reviews_trailers_text); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ); textView.setLayoutParams(layoutParams); contraConstraintLayout.addView(textView,contraConstraintLayout.getChildCount()); } /** * Adds the reviews (review_layout) to the corresponding layout * @param movie to obtain the reviews from */ private void addReviews(Movie movie){ // Get the parent layout LinearLayout reviewsLayout = findViewById(R.id.review_linear_layout); if(reviewsLayout != null) { // This is because the reviews are stored as follow: // 0: Author, 1: Review, 2: Author, 3: Review... // See parseContentReview and parseAuthor review for more details int review_number = movie.getReviews().size() / 2; if(review_number == 0){ noReviewOrTrailer(R.id.review_linear_layout); } for (int i = 0; i < review_number; i+=2) { // Inflate review_layout LayoutInflater inflater = LayoutInflater.from(this); View reviewLayout = inflater.inflate(R.layout.review_layout, null); // Get the review author textView TextView authorTextView = reviewLayout.findViewById(R.id.review_author); // Get the review content textView TextView contentTextView = reviewLayout.findViewById(R.id.review_text); // Set review author text String author_review = movie.getReviews().get(i); authorTextView.setText(author_review); Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD_ITALIC); authorTextView.setTypeface(boldTypeface); // Set review content text String content_review = movie.getReviews().get(i + 1); contentTextView.setText(content_review); // Set review layout params ConstraintLayout.LayoutParams l = new ConstraintLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); reviewLayout.setLayoutParams(l); reviewsLayout.addView(reviewLayout, reviewsLayout.getChildCount()); } } } /** * Adds the trailers (trailer_layout) to the corresponding layout * @param movie to obtain the trailers from */ private void addTrailers(Movie movie){ // This is because the trailers are stored as follow: // 0: Name, 1: Trailer, 2: Name, 3: Trailer... // See parseTrailerURL and parseTrailerName review for more details int trailer_number = movie.getTrailers().size()/2; if(trailer_number == 0){ noReviewOrTrailer(R.id.trailer_linear_layout); } LinearLayout contraConstraintLayout = findViewById(R.id.trailer_linear_layout); for(int i = 0; i < trailer_number; i+=2) { // Inflate trailer_layout LayoutInflater inflater = LayoutInflater.from(this); View trailerLayout = inflater.inflate(R.layout.trailer_layout, null); // Get the trailer textView TextView trailerTextView = trailerLayout.findViewById(R.id.trailer_text_view); // Set trailer textView text trailerTextView.setText(movie.getTrailers().get(i)); setOnClick(trailerLayout,movie.getTrailers().get(i+1)); // Set trailer layout params ConstraintLayout.LayoutParams l = new ConstraintLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); trailerLayout.setLayoutParams(l); contraConstraintLayout.addView(trailerLayout, contraConstraintLayout.getChildCount()); } } /** * onClick method to open a trailer in the Youtube app * @param imageView corresponding to the trailer * @param trailer_path trailer youtube link */ private void setOnClick(final View imageView, final String trailer_path){ imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(trailer_path)); DetailActivity.this.startActivity(webIntent); } }); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { toggle_button_pressed = (savedInstanceState.getBoolean(toogle_button_token)); } @Override public void onSaveInstanceState(Bundle outState) { outState.putBoolean(toogle_button_token, toggle_button_pressed); super.onSaveInstanceState(outState); } }
3e0970ce1421bb0b7ad5c63768b8e27d374263b7
5,803
java
Java
MarioAI-Base/src/main/java/ch/idsia/agents/controllers/modules/Entities.java
chrspo/MarioAi
e14f824cf0156a002a53e1f00a50a571914e7d8c
[ "BSD-3-Clause" ]
21
2015-10-13T14:00:23.000Z
2020-09-17T00:37:45.000Z
MarioAI-Base/src/main/java/ch/idsia/agents/controllers/modules/Entities.java
chrspo/MarioAi
e14f824cf0156a002a53e1f00a50a571914e7d8c
[ "BSD-3-Clause" ]
1
2016-05-01T23:32:21.000Z
2016-05-11T17:19:07.000Z
MarioAI-Base/src/main/java/ch/idsia/agents/controllers/modules/Entities.java
chrspo/MarioAi
e14f824cf0156a002a53e1f00a50a571914e7d8c
[ "BSD-3-Clause" ]
22
2015-10-05T19:43:14.000Z
2020-05-04T02:19:05.000Z
27.76555
140
0.686886
3,979
package ch.idsia.agents.controllers.modules; import java.util.ArrayList; import java.util.List; import ch.idsia.agents.AgentOptions; import ch.idsia.benchmark.mario.engine.generalization.Entity; import ch.idsia.benchmark.mario.engine.generalization.EntityKind; import ch.idsia.benchmark.mario.engine.generalization.EntityType; import ch.idsia.benchmark.mario.engine.generalization.MarioEntity; public class Entities { private MarioEntity mario; /** * 2-dimensional array representing entities. * * Entities are stored in [row][col] manner. * * Mario is at [marioEgoRow][marioEgoCol]. * * The array is {@link #receptiveFieldHeight} x {@link #receptiveFieldWidth} long. */ public List<Entity>[][] entityField; /** * List of all {@link Entity}ies that are within receptive field of Mario. */ public List<Entity> entities; public void reset(AgentOptions options) { this.mario = options.mario; } /** * Gets the most dangerous (lowest {@link EntityKind#getThreatLevel()}) entity type within receptive field on [mapX, mapY]. * @param mapX absolute receptive field tile x-coordinate * @param mapY absolute receptive field tile y-coordinate * @return */ protected EntityType getEntityType(int mapX, int mapY) { if (mapY < 0 || mapY >= entityField.length || mapX < 0 || mapX >= entityField[0].length) return EntityType.NOTHING; if (entityField[mapY][mapX].size() > 0) { // SEARCH FOR THE MOST DANGEROUS ONE Entity result = entityField[mapY][mapX].get(0); for (Entity entity : entityField[mapY][mapX]) { if (result.type.getKind().getThreatLevel() > entity.type.getKind().getThreatLevel()) result = entity; } return result.type; } else { return EntityType.NOTHING; } } /** * Returns all entities within receptive field on [mapX, mapY]. * @param mapX absolute receptive field tile x-coordinate * @param mapY absolute receptive field tile y-coordinate * @return */ protected List<Entity> getEntities(int mapX, int mapY) { if (entityField == null) return new ArrayList<Entity>(); if (mapY < 0 || mapY >= entityField.length || mapX < 0 || mapX >= entityField[0].length) return new ArrayList<Entity>(); return entityField[mapY][mapX]; } /** * Gets the most dangerous (lowest {@link EntityKind#getThreatLevel()}) entity type within receptive field relatively to Mario. * @param relMapX * @param relMapY * @return */ public EntityType entityType(int relMapX, int relMapY) { return getEntityType(mario.egoCol + relMapX,mario.egoRow + relMapY); } /** * Returns all entities within receptive field relatively to Mario. * @param relMapX * @param relMapY * @return */ public List<Entity> entities(int relMapX, int relMapY) { return getEntities(mario.egoCol + relMapX, mario.egoRow + relMapY); } /** * Is there something on the tile? (Relatively to Mario.) * @param relMapX * @param relMapY * @return */ public boolean anything(int relMapX, int relMapY) { return entities(relMapX, relMapY).size() > 0; } /** * Is there no entities there? (Relatively to Mario.) * @param relMapX * @param relMapY * @return */ public boolean nothing(int relMapX, int relMapY) { return entities(relMapX, relMapY).size() == 0; } /** * Is there any danger, something that can hurt me? (Relatively to Mario.) * @param relMapX * @param relMapY * @return */ public boolean danger(int relMapX, int relMapY) { if (nothing(relMapX, relMapY)) return false; for (Entity entity : entities(relMapX, relMapY)) { if (isDanger(entity)) return true; } return false; } /** * Is this 'entity' dangerous (i.e. it can hurt Mario if Mario touches it)? * @param entity * @return */ public boolean isDanger(Entity entity) { return entity.type.getKind().isDangerous(); } /** * Can I squish something there? (Relative to Mario). Note that this will return FALSE if there is non-squishable dangerous stuff there. * if the same tile is * @param relMapX * @param relMapY * @return */ public boolean squishy(int relMapX, int relMapY) { if (nothing(relMapX, relMapY)) return false; boolean result = false; for (Entity entity : entities(relMapX, relMapY)) { if (!isSquishy(entity) && isDanger(entity)) return false; if (isSquishy(entity)) { result = true; } } return result; } /** * Is this 'entity' squishable by jumping on it (== destroyable)? * @param entity * @return */ public boolean isSquishy(Entity entity) { return entity.type.getKind().isSquishy(); } /** * Can I shoot out something there? If the tile is occupied by both shootable and non-shootable things, this will report FALSE (play safe). * @param relMapX * @param relMapY * @return */ public boolean shootable(int relMapX, int relMapY) { if (nothing(relMapX, relMapY)) return false; boolean result = false; for (Entity entity : entities(relMapX, relMapY)) { if (!isShootable(entity)) return false; result = true; } return result; } /** * Is this 'entity' shootable by fireball? * @param entity * @return */ public boolean isShootable(Entity entity) { return entity.type.getKind().isShootable(); } /** * Can I collect something by going to that tile? (TRUE == collectible & !danger) * @param relMapX * @param relMapY * @return */ public boolean collectible(int relMapX, int relMapY) { if (nothing(relMapX, relMapY)) return false; if (danger(relMapX, relMapY)) return false; for (Entity entity : entities(relMapX, relMapY)) { if (isCollectible(entity)) return true; } return false; } /** * Is this entity 'collectible'? * @param entity * @return */ public boolean isCollectible(Entity entity) { return entity.type.getKind().isCollectible(); } }
3e0970cf88614105c0a645445824b5c9af2cb9c7
5,010
java
Java
service/tps/central/src/main/java/org/im97mori/ble/service/tps/central/TxPowerService.java
im97mori-github/AdvertisingDataParser
12a8501b495aba4f0bcfff154d28afc0fd83f75d
[ "MIT" ]
2
2021-12-16T01:34:55.000Z
2021-12-17T02:19:48.000Z
service/tps/central/src/main/java/org/im97mori/ble/service/tps/central/TxPowerService.java
im97mori-github/AdvertisingDataParser
12a8501b495aba4f0bcfff154d28afc0fd83f75d
[ "MIT" ]
null
null
null
service/tps/central/src/main/java/org/im97mori/ble/service/tps/central/TxPowerService.java
im97mori-github/AdvertisingDataParser
12a8501b495aba4f0bcfff154d28afc0fd83f75d
[ "MIT" ]
2
2020-11-03T02:19:25.000Z
2021-12-16T01:35:06.000Z
55.054945
316
0.774052
3,980
package org.im97mori.ble.service.tps.central; import android.bluetooth.BluetoothDevice; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.im97mori.ble.BLECallback; import org.im97mori.ble.BLEConnection; import org.im97mori.ble.characteristic.u2a07.TxPowerLevelAndroid; import org.im97mori.ble.service.central.AbstractCentralService; import org.im97mori.ble.task.ReadCharacteristicTask; import java.util.UUID; import static org.im97mori.ble.constants.CharacteristicUUID.TX_POWER_LEVEL_CHARACTERISTIC; import static org.im97mori.ble.constants.ServiceUUID.TX_POWER_SERVICE; /** * Tx Power Service (Service UUID: 0x1804) for Central */ public class TxPowerService extends AbstractCentralService { /** * {@link TxPowerService} instance */ private final TxPowerServiceCallback mTxPowerServiceCallback; /** * @param bleConnection {@link BLEConnection} instance * @param txPowerServiceCallback {@link TxPowerServiceCallback} instance * @param bleCallback {@link BLECallback} instance(optional) */ public TxPowerService(@NonNull BLEConnection bleConnection, @NonNull TxPowerServiceCallback txPowerServiceCallback, @Nullable BLECallback bleCallback) { super(bleConnection, bleCallback); mTxPowerServiceCallback = txPowerServiceCallback; } /** * {@inheritDoc} */ @Override public synchronized void onCharacteristicReadSuccess(@NonNull Integer taskId, @NonNull BluetoothDevice bluetoothDevice, @NonNull UUID serviceUUID, @NonNull Integer serviceInstanceId, @NonNull UUID characteristicUUID, @NonNull Integer characteristicInstanceId, @NonNull byte[] values, @Nullable Bundle argument) { if (mBLEConnection.getBluetoothDevice().equals(bluetoothDevice) && TX_POWER_SERVICE.equals(serviceUUID) && TX_POWER_LEVEL_CHARACTERISTIC.equals(characteristicUUID)) { mTxPowerServiceCallback.onTxPowerLevelReadSuccess(taskId, bluetoothDevice, serviceUUID, serviceInstanceId, characteristicUUID, characteristicInstanceId, TxPowerLevelAndroid.CREATOR.createFromByteArray(values), argument); } super.onCharacteristicReadSuccess(taskId, bluetoothDevice, serviceUUID, serviceInstanceId, characteristicUUID, characteristicInstanceId, values, argument); } /** * {@inheritDoc} */ @Override public synchronized void onCharacteristicReadFailed(@NonNull Integer taskId, @NonNull BluetoothDevice bluetoothDevice, @NonNull UUID serviceUUID, @Nullable Integer serviceInstanceId, @NonNull UUID characteristicUUID, @Nullable Integer characteristicInstanceId, int status, @Nullable Bundle argument) { if (mBLEConnection.getBluetoothDevice().equals(bluetoothDevice) && TX_POWER_SERVICE.equals(serviceUUID) && TX_POWER_LEVEL_CHARACTERISTIC.equals(characteristicUUID)) { mTxPowerServiceCallback.onTxPowerLevelReadFailed(taskId, bluetoothDevice, serviceUUID, serviceInstanceId, characteristicUUID, characteristicInstanceId, status, argument); } super.onCharacteristicReadFailed(taskId, bluetoothDevice, serviceUUID, serviceInstanceId, characteristicUUID, characteristicInstanceId, status, argument); } /** * {@inheritDoc} */ @Override public synchronized void onCharacteristicReadTimeout(@NonNull Integer taskId, @NonNull BluetoothDevice bluetoothDevice, @NonNull UUID serviceUUID, @Nullable Integer serviceInstanceId, @NonNull UUID characteristicUUID, @Nullable Integer characteristicInstanceId, long timeout, @Nullable Bundle argument) { if (mBLEConnection.getBluetoothDevice().equals(bluetoothDevice) && TX_POWER_SERVICE.equals(serviceUUID) && TX_POWER_LEVEL_CHARACTERISTIC.equals(characteristicUUID)) { mTxPowerServiceCallback.onTxPowerLevelReadTimeout(taskId, bluetoothDevice, serviceUUID, serviceInstanceId, characteristicUUID, characteristicInstanceId, timeout, argument); } super.onCharacteristicReadTimeout(taskId, bluetoothDevice, serviceUUID, serviceInstanceId, characteristicUUID, characteristicInstanceId, timeout, argument); } /** * get Tx Power Level * * @return task id. if {@code null} returned, service is not ready * @see TxPowerServiceCallback#onTxPowerLevelReadSuccess(Integer, BluetoothDevice, UUID, Integer, UUID, Integer, TxPowerLevelAndroid, Bundle) * @see TxPowerServiceCallback#onTxPowerLevelReadFailed(Integer, BluetoothDevice, UUID, Integer, UUID, Integer, int, Bundle) * @see TxPowerServiceCallback#onTxPowerLevelReadTimeout(Integer, BluetoothDevice, UUID, Integer, UUID, Integer, long, Bundle) */ @Nullable public synchronized Integer getTxPowerLevel() { Integer taskId = null; if (isStarted()) { taskId = mBLEConnection.createReadCharacteristicTask(TX_POWER_SERVICE, null, TX_POWER_LEVEL_CHARACTERISTIC, null, ReadCharacteristicTask.TIMEOUT_MILLIS, null, this); } return taskId; } }
3e09721c00d86b224ce7363e862cbcda23d549a0
2,580
java
Java
src/main/java/de/netbeacon/xenia/bot/commands/chat/structure/settings/guild/CMDLicense.java
Horstexplorer/Xenia
d073a393c8687e89b2ce25956a6fc5012f945f27
[ "Apache-2.0" ]
null
null
null
src/main/java/de/netbeacon/xenia/bot/commands/chat/structure/settings/guild/CMDLicense.java
Horstexplorer/Xenia
d073a393c8687e89b2ce25956a6fc5012f945f27
[ "Apache-2.0" ]
22
2020-10-22T14:36:43.000Z
2021-09-20T01:16:17.000Z
src/main/java/de/netbeacon/xenia/bot/commands/chat/structure/settings/guild/CMDLicense.java
Horstexplorer/Xenia
d073a393c8687e89b2ce25956a6fc5012f945f27
[ "Apache-2.0" ]
1
2020-12-04T18:23:34.000Z
2020-12-04T18:23:34.000Z
43
168
0.787597
3,981
/* * Copyright 2020 Horstexplorer @ https://www.netbeacon.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.netbeacon.xenia.bot.commands.chat.structure.settings.guild; import de.netbeacon.xenia.backend.client.objects.apidata.License; import de.netbeacon.xenia.backend.client.objects.apidata.Role; import de.netbeacon.xenia.backend.client.objects.internal.exceptions.DataException; import de.netbeacon.xenia.bot.commands.chat.objects.Command; import de.netbeacon.xenia.bot.commands.chat.objects.misc.cmdargs.CmdArg; import de.netbeacon.xenia.bot.commands.chat.objects.misc.cmdargs.CmdArgs; import de.netbeacon.xenia.bot.commands.chat.objects.misc.cooldown.CommandCooldown; import de.netbeacon.xenia.bot.commands.chat.objects.misc.event.CommandEvent; import de.netbeacon.xenia.bot.commands.chat.objects.misc.translations.TranslationPackage; import net.dv8tion.jda.api.Permission; import java.util.HashSet; import java.util.List; import static de.netbeacon.xenia.bot.commands.chat.objects.misc.cmdargs.CmdArgDefStatics.LICENSE_KEY_DEF; public class CMDLicense extends Command{ public CMDLicense(){ super("upgradelicense", false, new CommandCooldown(CommandCooldown.Type.Guild, 2000), null, new HashSet<>(List.of(Permission.MANAGE_SERVER)), new HashSet<>(List.of(Role.Permissions.Bit.GUILD_SETTINGS_OVERRIDE)), List.of(LICENSE_KEY_DEF) ); } @Override public void onExecution(CmdArgs args, CommandEvent commandEvent, TranslationPackage translationPackage) throws Exception{ CmdArg<String> licenseKey = args.getByIndex(0); License license = commandEvent.getBackendDataPack().license(); try{ license.updateLicenseKey(licenseKey.getValue()); commandEvent.getEvent().getChannel().sendMessageEmbeds(onSuccess(translationPackage, translationPackage.getTranslation(getClass(), "response.success.msg"))).queue(); } catch(DataException e){ commandEvent.getEvent().getChannel().sendMessageEmbeds(onError(translationPackage, translationPackage.getTranslation(getClass(), "response.error.msg"))).queue(); } } }
3e09735bd846a2de4d8020c5ef1f071a42447723
449
java
Java
fpc.aoc.problems/fpc.aoc.day24/src/main/java/fpc/aoc/day24/Day24Part1Solver.java
baracil/java-aoc-2021
e86828c6b1053c1ae097402f34b42939ebc8851b
[ "MIT" ]
null
null
null
fpc.aoc.problems/fpc.aoc.day24/src/main/java/fpc/aoc/day24/Day24Part1Solver.java
baracil/java-aoc-2021
e86828c6b1053c1ae097402f34b42939ebc8851b
[ "MIT" ]
null
null
null
fpc.aoc.problems/fpc.aoc.day24/src/main/java/fpc/aoc/day24/Day24Part1Solver.java
baracil/java-aoc-2021
e86828c6b1053c1ae097402f34b42939ebc8851b
[ "MIT" ]
null
null
null
22.45
65
0.714922
3,982
package fpc.aoc.day24; import lombok.NonNull; import fpc.aoc.api.AOCProblem; import fpc.aoc.common.NotSolvedYet; import java.util.stream.Stream; public class Day24Part1Solver extends Day24Solver { public static @NonNull AOCProblem<?> provider() { return new Day24Part1Solver().createProblem().skipped(); } @Override public @NonNull String solve(@NonNull Stream<String> input) { throw new NotSolvedYet(); } }
3e0973b3aa9ce3c4f84bb777c4720eb343f1d6a2
1,415
java
Java
src/test/java/dev/turingcomplete/asmtestkit/representation/_internal/RepresentationUtilsTest.java
marcelkliemannel/asm-testkit
96b34e280527d79de6a3819b013e7d630671f8d2
[ "Apache-2.0" ]
null
null
null
src/test/java/dev/turingcomplete/asmtestkit/representation/_internal/RepresentationUtilsTest.java
marcelkliemannel/asm-testkit
96b34e280527d79de6a3819b013e7d630671f8d2
[ "Apache-2.0" ]
null
null
null
src/test/java/dev/turingcomplete/asmtestkit/representation/_internal/RepresentationUtilsTest.java
marcelkliemannel/asm-testkit
96b34e280527d79de6a3819b013e7d630671f8d2
[ "Apache-2.0" ]
null
null
null
50.535714
120
0.414841
3,983
package dev.turingcomplete.asmtestkit.representation._internal; import dev.turingcomplete.asmtestkit.representation._internal.RepresentationUtils; import org.assertj.core.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; class RepresentationUtilsTest { // -- Class Fields ------------------------------------------------------------------------------------------------ // // -- Instance Fields --------------------------------------------------------------------------------------------- // // -- Initialization ---------------------------------------------------------------------------------------------- // // -- Exposed Methods --------------------------------------------------------------------------------------------- // @ParameterizedTest @CsvSource({ "'foo\nbar\nbaz',test,'testfoo\n bar\n baz'", "foo,test,testfoo", "'',test,test" }) void testPrependToFirstLine(String text, String toPrepend, String expected) { Assertions.assertThat(RepresentationUtils.prependToFirstLine(toPrepend, text)) .isEqualTo(expected); } // -- Private Methods --------------------------------------------------------------------------------------------- // // -- Inner Type -------------------------------------------------------------------------------------------------- // }
3e09745f4ae079a9a34f9503b0059b1a4838394d
726
java
Java
coca-co/src/main/java/coca/co/ins/fmt/MapTextInsFormat.java
dzh/coca
2ad141209a6a2d2138a509d68c23e69e4944f8db
[ "Apache-2.0" ]
8
2017-10-13T17:13:50.000Z
2018-12-05T09:41:49.000Z
coca-co/src/main/java/coca/co/ins/fmt/MapTextInsFormat.java
dzh/coca
2ad141209a6a2d2138a509d68c23e69e4944f8db
[ "Apache-2.0" ]
1
2018-07-20T07:15:43.000Z
2018-07-24T07:29:54.000Z
coca-co/src/main/java/coca/co/ins/fmt/MapTextInsFormat.java
dzh/coca
2ad141209a6a2d2138a509d68c23e69e4944f8db
[ "Apache-2.0" ]
null
null
null
22
79
0.575758
3,984
/** * */ package coca.co.ins.fmt; import java.util.HashMap; import java.util.Map; /** * TODO * TextIns formatted to Map * * @author dzh * @date Sep 6, 2017 2:27:57 PM * @since 0.0.1 */ public class MapTextInsFormat extends TextInsFormat<Map<String, String>> { @Override public Map<String, String> format(String fmt, String data) { String[] fmtList = split(fmt); String[] dataList = split(data); // TODO Map<String, String> r = new HashMap<String, String>(fmtList.length, 1); for (int i = 0; i < fmtList.length; i++) { if (i < dataList.length) r.put(fmtList[i], dataList[i]); else r.put(fmtList[i], ""); } return r; } }
3e097501321cfa8124b12d4b007016d9fa4e4a41
2,174
java
Java
src/main/java/untitled_thinggy_thingg/core/drawing/sprites/AnimationSprite.java
CooperRoalson/UntitledThinggyThingg
07834942384738eedc365d5af96065f274f797e4
[ "MIT" ]
null
null
null
src/main/java/untitled_thinggy_thingg/core/drawing/sprites/AnimationSprite.java
CooperRoalson/UntitledThinggyThingg
07834942384738eedc365d5af96065f274f797e4
[ "MIT" ]
null
null
null
src/main/java/untitled_thinggy_thingg/core/drawing/sprites/AnimationSprite.java
CooperRoalson/UntitledThinggyThingg
07834942384738eedc365d5af96065f274f797e4
[ "MIT" ]
null
null
null
23.376344
143
0.715731
3,985
package untitled_thinggy_thingg.core.drawing.sprites; import java.util.List; import untitled_thinggy_thingg.core.Constants; import untitled_thinggy_thingg.util.files.FilePath; import untitled_thinggy_thingg.world.blocks.Block; import untitled_thinggy_thingg.world.entities.Entity; /** * A subclass of {@link TextureSprite} which supports multiple frames looping at a given speed. * */ public class AnimationSprite extends TextureSprite { private static final long serialVersionUID = 1L; private transient double frameCounter = 0; private List<FilePath> textures; private int fps; private transient int animationFrame = 0; public AnimationSprite(List<FilePath> textures, int fps) { super(textures.get(0)); this.textures = textures; this.fps = fps; } /** * Returns the number of frames of animation that pass per game update (using {@link AnimationSprite#getCurrentFPS()}). Cannot be more than 1. * * @return How many frames occur per game update */ public double getCurrentFramesPerUpdate() { return Math.min((double) fps/Constants.Window.TARGET_FPS, 1.0); } /** * Resets the animation to its first frame. */ public void resetFrameCounter() { frameCounter = 0; } /** * Same as {@link AnimationSprite#updateAnimation()}. Used for compatibility with {@link Block}s and {@link Entity}s. */ public void update() { this.updateAnimation(); } public void resetAnimationFrame() { this.animationFrame = 0; } public void setTextures(List<FilePath> textures) { this.textures = textures; this.resetAnimationFrame(); this.resetFrameCounter(); this.setTexture(textures.get(0)); } public int getFps() { return fps; } public void setFps(int fps) { this.fps = fps; } public void onAnimationComplete() {} private void nextFrame() { animationFrame ++; animationFrame %= textures.size(); this.setTexture(textures.get(animationFrame)); if (animationFrame == 0) {onAnimationComplete();} } /** * Updates the animation. */ public void updateAnimation() { frameCounter += getCurrentFramesPerUpdate(); if (frameCounter >= 1) { nextFrame(); frameCounter --; } } }
3e09756ed29c8249c632bcca01bdc17d0a76a18b
745
java
Java
website/src/main/java/com/cesarmando/website/controller/JavascriptC.java
lrn2prgrm/shopping-cart
2a180519fbc5d245ec4a18b8a226ee1437bf2b1c
[ "MIT" ]
null
null
null
website/src/main/java/com/cesarmando/website/controller/JavascriptC.java
lrn2prgrm/shopping-cart
2a180519fbc5d245ec4a18b8a226ee1437bf2b1c
[ "MIT" ]
null
null
null
website/src/main/java/com/cesarmando/website/controller/JavascriptC.java
lrn2prgrm/shopping-cart
2a180519fbc5d245ec4a18b8a226ee1437bf2b1c
[ "MIT" ]
null
null
null
24.833333
60
0.708725
3,986
package com.cesarmando.website.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; /** * Created by jarma on 7/25/2017. */ @Controller public class JavascriptC { private TemplateEngine jsTemplating; public JavascriptC(TemplateEngine jsTemplating) { this.jsTemplating = jsTemplating; } // @GetMapping("/service-worker.js") // @ResponseBody // public String serviceWorker() { // String text = jsTemplating // .process("service-worker", new Context()); // return ""; // } }
3e0977221e14cfc6a09ebd0983b4df2fd464a836
5,746
java
Java
h2-web-console/h2webconsole-service/src/main/java/org/lealone/examples/h2webconsole/service/generated/executor/AdminServiceExecutor.java
VilenEera/Lealone-Examples
ccef99667541b693e9dbfe2c0a2dfa9d1a41832a
[ "Apache-2.0" ]
53
2020-10-14T17:21:12.000Z
2022-03-22T13:22:54.000Z
h2-web-console/h2webconsole-service/src/main/java/org/lealone/examples/h2webconsole/service/generated/executor/AdminServiceExecutor.java
VilenEera/Lealone-Examples
ccef99667541b693e9dbfe2c0a2dfa9d1a41832a
[ "Apache-2.0" ]
9
2020-10-15T09:10:33.000Z
2021-11-28T16:08:07.000Z
h2-web-console/h2webconsole-service/src/main/java/org/lealone/examples/h2webconsole/service/generated/executor/AdminServiceExecutor.java
VilenEera/Lealone-Examples
ccef99667541b693e9dbfe2c0a2dfa9d1a41832a
[ "Apache-2.0" ]
16
2020-10-15T04:15:08.000Z
2021-07-04T20:56:00.000Z
37.311688
90
0.563348
3,987
package org.lealone.examples.h2webconsole.service.generated.executor; import java.util.Map; import org.lealone.db.service.ServiceExecutor; import org.lealone.db.value.*; import org.lealone.examples.h2webconsole.service.AdminServiceImpl; import org.lealone.orm.json.JsonArray; /** * Service executor for 'admin_service'. * * THIS IS A GENERATED OBJECT, DO NOT MODIFY THIS CLASS. */ public class AdminServiceExecutor implements ServiceExecutor { private final AdminServiceImpl s = new AdminServiceImpl(); @Override public Value executeService(String methodName, Value[] methodArgs) { switch (methodName) { case "LOGIN": String p_password_1 = methodArgs[0].getString(); String result1 = this.s.login(p_password_1); if (result1 == null) return ValueNull.INSTANCE; return ValueString.get(result1); case "SAVE": String p_port_2 = methodArgs[0].getString(); String p_allowOthers_2 = methodArgs[1].getString(); String p_ssl_2 = methodArgs[2].getString(); String result2 = this.s.save(p_port_2, p_allowOthers_2, p_ssl_2); if (result2 == null) return ValueNull.INSTANCE; return ValueString.get(result2); case "ADMIN": String result3 = this.s.admin(); if (result3 == null) return ValueNull.INSTANCE; return ValueString.get(result3); case "START_TRANSLATE": String result4 = this.s.startTranslate(); if (result4 == null) return ValueNull.INSTANCE; return ValueString.get(result4); case "SHUTDOWN": String result5 = this.s.shutdown(); if (result5 == null) return ValueNull.INSTANCE; return ValueString.get(result5); case "TOOLS": String p_toolName_6 = methodArgs[0].getString(); String p_args_6 = methodArgs[1].getString(); String result6 = this.s.tools(p_toolName_6, p_args_6); if (result6 == null) return ValueNull.INSTANCE; return ValueString.get(result6); default: throw new RuntimeException("no method: " + methodName); } } @Override public String executeService(String methodName, Map<String, Object> methodArgs) { switch (methodName) { case "LOGIN": String p_password_1 = ServiceExecutor.toString("PASSWORD", methodArgs); String result1 = this.s.login(p_password_1); if (result1 == null) return null; return result1; case "SAVE": String p_port_2 = ServiceExecutor.toString("PORT", methodArgs); String p_allowOthers_2 = ServiceExecutor.toString("ALLOW_OTHERS", methodArgs); String p_ssl_2 = ServiceExecutor.toString("SSL", methodArgs); String result2 = this.s.save(p_port_2, p_allowOthers_2, p_ssl_2); if (result2 == null) return null; return result2; case "ADMIN": String result3 = this.s.admin(); if (result3 == null) return null; return result3; case "START_TRANSLATE": String result4 = this.s.startTranslate(); if (result4 == null) return null; return result4; case "SHUTDOWN": String result5 = this.s.shutdown(); if (result5 == null) return null; return result5; case "TOOLS": String p_toolName_6 = ServiceExecutor.toString("TOOL_NAME", methodArgs); String p_args_6 = ServiceExecutor.toString("ARGS", methodArgs); String result6 = this.s.tools(p_toolName_6, p_args_6); if (result6 == null) return null; return result6; default: throw new RuntimeException("no method: " + methodName); } } @Override public String executeService(String methodName, String json) { JsonArray ja = null; switch (methodName) { case "LOGIN": ja = new JsonArray(json); String p_password_1 = ja.getString(0); String result1 = this.s.login(p_password_1); if (result1 == null) return null; return result1; case "SAVE": ja = new JsonArray(json); String p_port_2 = ja.getString(0); String p_allowOthers_2 = ja.getString(1); String p_ssl_2 = ja.getString(2); String result2 = this.s.save(p_port_2, p_allowOthers_2, p_ssl_2); if (result2 == null) return null; return result2; case "ADMIN": String result3 = this.s.admin(); if (result3 == null) return null; return result3; case "START_TRANSLATE": String result4 = this.s.startTranslate(); if (result4 == null) return null; return result4; case "SHUTDOWN": String result5 = this.s.shutdown(); if (result5 == null) return null; return result5; case "TOOLS": ja = new JsonArray(json); String p_toolName_6 = ja.getString(0); String p_args_6 = ja.getString(1); String result6 = this.s.tools(p_toolName_6, p_args_6); if (result6 == null) return null; return result6; default: throw new RuntimeException("no method: " + methodName); } } }
3e0978374674c59acb3cfb4d952b212bb5c58f0d
3,289
java
Java
app/src/main/java/com/lucasg234/parstagram/mainactivity/MainActivity.java
LucasG234/Parstagram
85d53162b1edde719392eac08cae10b2655ddc79
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/lucasg234/parstagram/mainactivity/MainActivity.java
LucasG234/Parstagram
85d53162b1edde719392eac08cae10b2655ddc79
[ "Apache-2.0" ]
1
2020-07-11T10:52:06.000Z
2020-07-14T04:17:20.000Z
app/src/main/java/com/lucasg234/parstagram/mainactivity/MainActivity.java
LucasG234/Parstagram
85d53162b1edde719392eac08cae10b2655ddc79
[ "Apache-2.0" ]
null
null
null
35.75
135
0.671329
3,988
package com.lucasg234.parstagram.mainactivity; import android.os.Bundle; import android.text.format.DateUtils; import android.view.Menu; import android.view.MenuItem; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.lucasg234.parstagram.R; import com.lucasg234.parstagram.databinding.ActivityMainBinding; import com.lucasg234.parstagram.dialogs.SettingsDialogFragment; import java.util.Date; /** * Central activity which holds FeedFragment, ComposeFragment, and ProfileFragment * Handles navigation through a BottomNavigationView */ public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private ActivityMainBinding mBinding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(mBinding.getRoot()); setSupportActionBar(mBinding.mainToolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); final FragmentManager fragmentManager = getSupportFragmentManager(); // Set a listener for fragment selection mBinding.bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Fragment fragment = null; switch (item.getItemId()) { case R.id.menuCompose: fragment = ComposeFragment.newInstance(); break; case R.id.menuProfile: fragment = ProfileFragment.newInstance(); break; // Default to menuHome default: fragment = FeedFragment.newInstance(); break; } fragmentManager.beginTransaction().replace(R.id.frameContainer, fragment).commit(); return true; } }); // Set a default fragment mBinding.bottomNavigationView.setSelectedItemId(R.id.menuFeed); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_settings, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.menuSettings: openSettingsDialog(); return true; default: return super.onOptionsItemSelected(item); } } private void openSettingsDialog() { final FragmentManager fragmentManager = getSupportFragmentManager(); DialogFragment dialogFragment = SettingsDialogFragment.newInstance(); dialogFragment.show(fragmentManager, "fragment_post_settings"); } }
3e0978dba9bbfcdb038bb7b882f5fb621044e642
1,505
java
Java
client/shared/src/main/java/com/threerings/bang/game/data/piece/Barricade.java
mimeyy/dylansbang
b3e913eb7fe3702cd97e93edde8c8b700e7d9fdf
[ "BSD-2-Clause" ]
17
2016-03-23T15:34:18.000Z
2021-12-15T21:24:45.000Z
client/shared/src/main/java/com/threerings/bang/game/data/piece/Barricade.java
mimeyy/dylansbang
b3e913eb7fe3702cd97e93edde8c8b700e7d9fdf
[ "BSD-2-Clause" ]
3
2016-12-15T07:22:06.000Z
2019-01-23T11:41:04.000Z
client/shared/src/main/java/com/threerings/bang/game/data/piece/Barricade.java
mimeyy/dylansbang
b3e913eb7fe3702cd97e93edde8c8b700e7d9fdf
[ "BSD-2-Clause" ]
15
2016-11-01T22:14:38.000Z
2021-07-31T10:04:32.000Z
27.87037
86
0.668439
3,989
// // $Id$ package com.threerings.bang.game.data.piece; import java.util.ArrayList; import java.util.List; import com.threerings.bang.game.client.sprite.MobileSprite; import com.threerings.bang.game.client.sprite.PieceSprite; import com.threerings.bang.game.data.BangBoard; import com.threerings.bang.game.data.BangObject; import com.threerings.bang.game.data.effect.Effect; import com.threerings.bang.game.data.effect.ClearPieceEffect; /** * A barricade that will hang out for a while before disappearing. */ public class Barricade extends Piece { /** The number of ticks remaining until this barricade disappears. */ public transient int tickCounter = 6; @Override // documentation inherited public ArrayList<Effect> tick (short tick, BangObject bangobj, List<Piece> pieces) { if (tickCounter-- > 0) { return null; } ArrayList<Effect> effects = new ArrayList<Effect>(); effects.add(new ClearPieceEffect(this)); return effects; } @Override // documentation inherited public int computeElevation ( BangBoard board, int tx, int ty, boolean moving) { return board.getElevation(tx, ty); } @Override // documentation inherited public PieceSprite createSprite () { return new MobileSprite("extras", "frontier_town/barricade") { public boolean removed () { queueAction(REMOVED); return true; } }; } }
3e0978f64362824d8ff627f952a0ba4291a3a780
2,787
java
Java
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/qm/QMEventCriteria.java
tomas303/dbeaver
f96af4733065668b9483132714b1fbb11bba02a9
[ "Apache-2.0" ]
3
2017-10-25T01:25:55.000Z
2020-12-23T06:05:00.000Z
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/qm/QMEventCriteria.java
tomas303/dbeaver
f96af4733065668b9483132714b1fbb11bba02a9
[ "Apache-2.0" ]
4
2020-05-16T17:16:10.000Z
2020-05-16T17:18:13.000Z
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/qm/QMEventCriteria.java
tomas303/dbeaver
f96af4733065668b9483132714b1fbb11bba02a9
[ "Apache-2.0" ]
1
2017-10-18T20:06:47.000Z
2017-10-18T20:06:47.000Z
28.131313
97
0.691562
3,990
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 Serge Rider (kenaa@example.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.model.qm; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.model.exec.DBCExecutionPurpose; import org.jkiss.utils.ArrayUtils; /** * QM event criteria */ public class QMEventCriteria { @Nullable String containerId; @Nullable String sessionId; @NotNull QMObjectType[] objectTypes = new QMObjectType[0]; @NotNull DBCExecutionPurpose[] queryTypes = new DBCExecutionPurpose[0]; @Nullable String searchString; public String getContainerId() { return containerId; } public void setContainerId(String containerId) { this.containerId = containerId; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public QMObjectType[] getObjectTypes() { return objectTypes; } public void setObjectTypes(QMObjectType[] objectTypes) { this.objectTypes = objectTypes; } public boolean hasObjectTypes() { return objectTypes.length > 0 && objectTypes.length != QMObjectType.values().length; } public boolean hasObjectType(QMObjectType type) { // If all object types are here it is the same as no object type return objectTypes.length > 0 && ArrayUtils.contains(objectTypes, type); } public DBCExecutionPurpose[] getQueryTypes() { return queryTypes; } public void setQueryTypes(DBCExecutionPurpose[] queryTypes) { this.queryTypes = queryTypes; } public boolean hasQueryTypes() { // If all query types are here it is the same as no query type return queryTypes.length > 0 && queryTypes.length != DBCExecutionPurpose.values().length; } public boolean hasQueryType(DBCExecutionPurpose type) { return queryTypes.length > 0 && ArrayUtils.contains(queryTypes, type); } public String getSearchString() { return searchString; } public void setSearchString(String searchString) { this.searchString = searchString; } }
3e097921a5772e6e0c9c536efb342595707a809f
3,906
java
Java
oss-lib-security/src/main/java/com/yirendai/oss/lib/security/internal/AuthenticationTokens.java
Yirendai/oss-lib
912e24382c4482c851997eee4d29e90af9e7db6c
[ "MIT" ]
2
2017-04-07T16:15:09.000Z
2018-12-07T02:59:36.000Z
oss-lib-security/src/main/java/com/yirendai/oss/lib/security/internal/AuthenticationTokens.java
Yirendai/oss-lib
912e24382c4482c851997eee4d29e90af9e7db6c
[ "MIT" ]
null
null
null
oss-lib-security/src/main/java/com/yirendai/oss/lib/security/internal/AuthenticationTokens.java
Yirendai/oss-lib
912e24382c4482c851997eee4d29e90af9e7db6c
[ "MIT" ]
5
2017-04-07T16:14:25.000Z
2022-03-06T10:34:18.000Z
37.2
110
0.736559
3,991
package com.yirendai.oss.lib.security.internal; import static com.yirendai.oss.lib.security.api.GenericUser.isGenericUser; import com.google.common.collect.ImmutableSet; import com.yirendai.oss.lib.security.api.GenericUser; import com.yirendai.oss.lib.webmvc.api.TypeSafeToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import java.util.Collection; /** * Created by zhanghaolun on 16/10/30. */ public abstract class AuthenticationTokens { private AuthenticationTokens() { } public static PreAuthenticatedAuthenticationToken authenticated( // final PreAuthenticatedAuthenticationToken authentication // ) { final PreAuthenticatedAuthenticationToken result; if (authentication == null) { result = null; } else { authentication.setAuthenticated(true); authentication.eraseCredentials(); final Object principal = authentication.getPrincipal(); final Object credentials = authentication.getCredentials(); final GenericUser genericUser = isGenericUser(principal) ? (GenericUser) principal : null; if (genericUser == null) { result = authentication; } else { genericUser.eraseCredentials(); final Collection<GrantedAuthority> authorities = genericUser.getAuthorities() != null ? // genericUser.getAuthorities() : ImmutableSet.of(); result = new PreAuthenticatedAuthenticationToken(principal, credentials, authorities); } } return result; } public static String rawToken(final Authentication authentication, final TypeSafeToken<GenericUser> token) { // TODO find OAuth2Authentication's header Authorization: Bearer? final String result; if (authentication instanceof PreAuthenticatedAuthenticationToken) { final Object principal = authentication.getPrincipal(); final GenericUser genericUser = isGenericUser(principal) ? (GenericUser) principal : null; result = genericUser != null ? (String) authentication.getCredentials() : null; } else { final GenericUser genericUser = GenericUser.fromPrincipal(authentication); result = token.toToken(genericUser); } return result; } public static Boolean tokenInSecurityContext() { final SecurityContext securityContext = SecurityContextHolder.getContext(); final Authentication authentication = securityContext.getAuthentication(); return authentication != null && authentication.isAuthenticated(); } public static String tokenFromSecurityContext(final TypeSafeToken<GenericUser> token) { final SecurityContext securityContext = SecurityContextHolder.getContext(); final Authentication authentication = securityContext.getAuthentication(); final String result; if (authentication != null && authentication.isAuthenticated()) { result = AuthenticationTokens.rawToken(authentication, token); } else { result = null; } return result; } // public static boolean containsUserInfo(final Authentication authentication) { // final boolean result; // if (authentication == null) { // result = false; // } else if (authentication instanceof OAuth2Authentication) { // final OAuth2Authentication oAuth2Auth = (OAuth2Authentication) authentication; // result = !oAuth2Auth.isClientOnly(); // } else if (authentication instanceof AbstractAuthenticationToken) { // // PreAuthenticatedAuthenticationToken // result = isGenericUser(authentication.getPrincipal()); // } else { // result = false; // } // return result; // } }
3e0979586274379a78b248668f3494dbbebd0237
3,138
java
Java
src/main/java/top/forcebing/borrowhome/common/config/ShiroConfiguration.java
BorrowHome/borrowhomeend
c0cca4c3dd022aa01a52d5738235b0f2b39d36a9
[ "Apache-2.0" ]
null
null
null
src/main/java/top/forcebing/borrowhome/common/config/ShiroConfiguration.java
BorrowHome/borrowhomeend
c0cca4c3dd022aa01a52d5738235b0f2b39d36a9
[ "Apache-2.0" ]
null
null
null
src/main/java/top/forcebing/borrowhome/common/config/ShiroConfiguration.java
BorrowHome/borrowhomeend
c0cca4c3dd022aa01a52d5738235b0f2b39d36a9
[ "Apache-2.0" ]
null
null
null
33.084211
127
0.719695
3,992
package top.forcebing.borrowhome.common.config; import top.forcebing.borrowhome.common.utils.JwtAuthenticationTokenFilter; import org.apache.shiro.mgt.DefaultSessionStorageEvaluator; import org.apache.shiro.mgt.DefaultSubjectDAO; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.Filter; import java.util.HashMap; import java.util.Map; /** * @author liliangbin nnheo@example.com * @date 2018/11/8 23:37 */ @Configuration public class ShiroConfiguration { @Bean("securityManager") public DefaultWebSecurityManager getManager() { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); // 使用自己的realm manager.setRealm(myShiroRealm()); /* * 关闭shiro自带的session,详情见文档 * http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29 */ DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO(); DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator(); defaultSessionStorageEvaluator.setSessionStorageEnabled(false); subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator); manager.setSubjectDAO(subjectDAO); return manager; } @Bean public MyRealm myShiroRealm() { MyRealm myRealm = new MyRealm(); // myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());; /* * * 上面的那个注释是一个md5加密的一个解密算法,但是我密码并没有加密,这个锅后期来修改*/ return myRealm; } @Bean("shiroFilter") public ShiroFilterFactoryBean factory(DefaultWebSecurityManager securityManager) { ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean(); // 添加自己的过滤器并且取名为jwt Map<String, Filter> filterMap = new HashMap<>(); filterMap.put("jwt", new JwtAuthenticationTokenFilter()); factoryBean.setFilters(filterMap); factoryBean.setSecurityManager(securityManager); factoryBean.setUnauthorizedUrl("/401"); /* * 自定义url规则 * http://shiro.apache.org/web.html#urls- */ Map<String, String> filterRuleMap = new HashMap<>(); // 所有请求通过我们自己的JWT Filter filterRuleMap.put("/**", "jwt"); // 访问401和404页面不通过我们的Filter filterRuleMap.put("/401", "anon"); filterRuleMap.put("/login", "anon"); filterRuleMap.put("/getuser", "anon"); factoryBean.setFilterChainDefinitionMap(filterRuleMap); return factoryBean; } @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) { AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); advisor.setSecurityManager(securityManager); return advisor; } }
3e097cdbbe73cbd53a077ebf6a14f53dacd9d2ee
1,734
java
Java
urule-core/src/main/java/com/bstek/urule/dsl/builder/LibraryContextBuilder.java
lisongyan123/urule
597b0659411486ab7a067ea8a2788f8ed6e75c20
[ "Apache-2.0" ]
null
null
null
urule-core/src/main/java/com/bstek/urule/dsl/builder/LibraryContextBuilder.java
lisongyan123/urule
597b0659411486ab7a067ea8a2788f8ed6e75c20
[ "Apache-2.0" ]
2
2021-04-22T17:11:34.000Z
2021-09-20T21:01:11.000Z
urule-core/src/main/java/com/bstek/urule/dsl/builder/LibraryContextBuilder.java
lisongyan123/urule
597b0659411486ab7a067ea8a2788f8ed6e75c20
[ "Apache-2.0" ]
null
null
null
41.285714
91
0.690888
3,993
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.bstek.urule.dsl.builder; import com.bstek.urule.dsl.RuleParserParser.ResourceContext; import com.bstek.urule.exception.RuleException; import com.bstek.urule.model.rule.Library; import com.bstek.urule.model.rule.LibraryType; import org.antlr.v4.runtime.ParserRuleContext; public class LibraryContextBuilder extends AbstractContextBuilder { public LibraryContextBuilder() { } public Library build(ParserRuleContext var1) { ResourceContext var2 = (ResourceContext)var1; String var3; if (var2.importActionLibrary() != null) { var3 = BuildUtils.getSTRINGContent(var2.importActionLibrary().STRING()); return new Library(var3, (String)null, LibraryType.Action); } else if (var2.importConstantLibrary() != null) { var3 = BuildUtils.getSTRINGContent(var2.importConstantLibrary().STRING()); return new Library(var3, (String)null, LibraryType.Constant); } else if (var2.importVariableLibrary() != null) { var3 = BuildUtils.getSTRINGContent(var2.importVariableLibrary().STRING()); return new Library(var3, (String)null, LibraryType.Variable); } else if (var2.importParameterLibrary() != null) { var3 = BuildUtils.getSTRINGContent(var2.importParameterLibrary().STRING()); return new Library(var3, (String)null, LibraryType.Parameter); } else { throw new RuleException("Unsupport context " + var2.getClass().getName() + ""); } } public boolean support(ParserRuleContext var1) { return var1 instanceof ResourceContext; } }
3e097e411498b514ba5260e5c6df2a54d79332a1
1,236
java
Java
picview/src/com/google/android/apps/picview/request/CachedResponse.java
isabella232/picview-for-android
aa698b741d179ae1d36fdc4f166a76dc74f7e028
[ "Apache-2.0" ]
51
2015-01-04T06:59:23.000Z
2021-04-07T11:24:37.000Z
picview-for-android/picview/src/com/google/android/apps/picview/request/CachedResponse.java
SDRausty/buildAPKsSamples
934401274868f2ccb1ef8f456e77c7cbe56c3726
[ "MIT" ]
1
2021-07-12T12:26:20.000Z
2021-07-12T12:26:20.000Z
picview-for-android/picview/src/com/google/android/apps/picview/request/CachedResponse.java
SDRausty/buildAPKsSamples
934401274868f2ccb1ef8f456e77c7cbe56c3726
[ "MIT" ]
34
2015-02-05T10:29:11.000Z
2021-07-12T12:25:35.000Z
30.243902
80
0.724194
3,994
/* * Copyright 2011 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 com.google.android.apps.picview.request; /** * A cached response, that can come from either filesystem, in-memory or was * directly fetched because no cached copy was present. * * @author dycjh@example.com (Sascha Haeberling) * * @param <T> * the actual content type */ public class CachedResponse<T> { public static final int NOT_CACHED = 0; public static final int FROM_FILE = 1; public static final int FROM_MEMORY = 2; public final int cacheStatus; public final T content; public CachedResponse(int cacheStatus, T content) { this.cacheStatus = cacheStatus; this.content = content; } }
3e097f37bdaaca8a590dcdc9ac6356d619abdf4c
735
java
Java
blog/src/main/java/com/onwl007/blog/service/CommentServiceImpl.java
onwl007/blog
a05217505b941dd455ec823256f7596ec865d788
[ "Apache-2.0" ]
1
2018-03-03T13:55:37.000Z
2018-03-03T13:55:37.000Z
blog/src/main/java/com/onwl007/blog/service/CommentServiceImpl.java
onwl007/blog
a05217505b941dd455ec823256f7596ec865d788
[ "Apache-2.0" ]
null
null
null
blog/src/main/java/com/onwl007/blog/service/CommentServiceImpl.java
onwl007/blog
a05217505b941dd455ec823256f7596ec865d788
[ "Apache-2.0" ]
null
null
null
24.433333
64
0.757162
3,995
package com.onwl007.blog.service; import com.onwl007.blog.domain.Comment; import com.onwl007.blog.repository.CommentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @author dycjh@example.com * @date 2017/10/26 20:53 */ @Service public class CommentServiceImpl implements CommentService{ @Autowired private CommentRepository commentRepository; @Override public Comment getCommentById(Long id) { return commentRepository.findOne(id); } @Override @Transactional public void removeComment(Long id) { commentRepository.delete(id); } }
3e097f5b4e47f5494210e5774915bea4a4ae3e85
192
java
Java
test.java
theaswath/Program-Course--Sem2---Java-
bd14e275e490869bc360330709808fc17492b08c
[ "Unlicense" ]
null
null
null
test.java
theaswath/Program-Course--Sem2---Java-
bd14e275e490869bc360330709808fc17492b08c
[ "Unlicense" ]
null
null
null
test.java
theaswath/Program-Course--Sem2---Java-
bd14e275e490869bc360330709808fc17492b08c
[ "Unlicense" ]
null
null
null
19.2
41
0.723958
3,996
//For Testing class test { static void throwOne() { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { throwOne(); } }
3e0980f63a3d45f7465b2b12d11980a5d5221f89
2,681
java
Java
graphql/src/main/java/com/arcadedb/graphql/query/GraphQLQueryEngine.java
ArcadeData/arcadedb
f00032411c2d045837da929a3bb094a90d7e9e8f
[ "Apache-2.0" ]
137
2021-09-01T16:50:04.000Z
2022-03-24T14:21:37.000Z
graphql/src/main/java/com/arcadedb/graphql/query/GraphQLQueryEngine.java
ArcadeData/arcadedb
f00032411c2d045837da929a3bb094a90d7e9e8f
[ "Apache-2.0" ]
140
2021-08-31T22:21:43.000Z
2022-03-28T04:08:16.000Z
graphql/src/main/java/com/arcadedb/graphql/query/GraphQLQueryEngine.java
ArcadeData/arcadedb
f00032411c2d045837da929a3bb094a90d7e9e8f
[ "Apache-2.0" ]
20
2021-08-31T21:57:00.000Z
2022-02-12T01:35:01.000Z
31.564706
120
0.721208
3,997
/* * Copyright © 2021-present Arcade Data Ltd (nnheo@example.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.arcadedb.graphql.query; import com.arcadedb.exception.CommandExecutionException; import com.arcadedb.exception.QueryParsingException; import com.arcadedb.graphql.schema.GraphQLSchema; import com.arcadedb.query.QueryEngine; import com.arcadedb.query.sql.executor.ResultSet; import com.arcadedb.utility.FileUtils; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; public class GraphQLQueryEngine implements QueryEngine { public static final String ENGINE_NAME = "graphql-engine"; private final GraphQLSchema graphQLSchema; protected GraphQLQueryEngine(final GraphQLSchema graphQLSchema) { this.graphQLSchema = graphQLSchema; } @Override public AnalyzedQuery analyze(String query) { return new AnalyzedQuery() { @Override public boolean isIdempotent() { return false; } @Override public boolean isDDL() { return false; } }; } @Override public ResultSet query(final String query, final Map<String, Object> parameters) { return command(query, parameters); } @Override public ResultSet query(final String query, final Object... parameters) { return command(query, parameters); } @Override public ResultSet command(final String query, final Map<String, Object> parameters) { try { final ResultSet resultSet = graphQLSchema.execute(query); return resultSet; } catch (Exception e) { throw new QueryParsingException("Error on executing GraphQL query:\n" + FileUtils.printWithLineNumbers(query), e); } } @Override public ResultSet command(final String query, final Object... parameters) { if (parameters.length % 2 != 0) throw new IllegalArgumentException("Command parameters must be as pairs `<key>, <value>`"); final Map<String, Object> map = new HashMap<>(parameters.length / 2); for (int i = 0; i < parameters.length; i += 2) map.put((String) parameters[i], parameters[i + 1]); return command(query, map); } }
3e0981d620482f85d33c13541f022514555b0ba6
380
java
Java
note/src/main/java/com/designpattern/memento/Client.java
CodingSoldier/java-learn
c480f0c26c95b65f49c082e0ffeb10706bd366b1
[ "Apache-2.0" ]
23
2018-02-11T13:28:42.000Z
2021-12-24T05:53:13.000Z
note/src/main/java/com/designpattern/memento/Client.java
CodingSoldier/java-learn
c480f0c26c95b65f49c082e0ffeb10706bd366b1
[ "Apache-2.0" ]
5
2019-12-23T01:51:45.000Z
2021-11-30T15:12:08.000Z
note/src/main/java/com/designpattern/memento/Client.java
CodingSoldier/java-learn
c480f0c26c95b65f49c082e0ffeb10706bd366b1
[ "Apache-2.0" ]
17
2018-02-11T13:28:03.000Z
2022-01-24T20:30:02.000Z
20
46
0.6
3,998
package com.designpattern.memento; public class Client { public static void main(String[] args) { Originator o = new Originator(); Caretaker c = new Caretaker(); o.setState("On"); c.saveMemento(o.createMemento()); o.setState("Off"); o.restoreMemento(c.retrieveMemento()); System.out.println(o.getState()); } }
3e0982434c522736067738e8c8f5941dc9961995
2,347
java
Java
server/server/session/src/main/java/com/alipay/sofa/registry/server/session/mapper/ConnectionMapper.java
stulzq/sofa-registry
ff86e73225a71c16df64b1e6ac73b3a77f1b70cc
[ "Apache-2.0" ]
220
2019-03-22T09:03:01.000Z
2019-05-12T10:50:04.000Z
server/server/session/src/main/java/com/alipay/sofa/registry/server/session/mapper/ConnectionMapper.java
stulzq/sofa-registry
ff86e73225a71c16df64b1e6ac73b3a77f1b70cc
[ "Apache-2.0" ]
20
2019-03-24T08:24:54.000Z
2019-05-13T01:03:42.000Z
server/server/session/src/main/java/com/alipay/sofa/registry/server/session/mapper/ConnectionMapper.java
stulzq/sofa-registry
ff86e73225a71c16df64b1e6ac73b3a77f1b70cc
[ "Apache-2.0" ]
48
2019-03-24T07:14:10.000Z
2019-05-10T02:54:34.000Z
25.236559
75
0.697912
3,999
/* * 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.alipay.sofa.registry.server.session.mapper; import com.google.common.collect.Maps; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang.StringUtils; /** * @author ruoshan * @since 5.4.1 */ public class ConnectionMapper { /** <connectionIp:connectionPort, clientIp > * */ private final ConcurrentHashMap<String, String> connectionToClientIpMap = new ConcurrentHashMap<>(); /** * 添加连接到 clientIp 的映射 * * @param connectId 连接 ip:port * @param clientIp 客户端 ip */ public void add(String connectId, String clientIp) { if (StringUtils.isNotEmpty(clientIp)) { connectionToClientIpMap.putIfAbsent(connectId, clientIp); } } /** * 删除连接到 clientIp 的映射 * * @param connectId 连接 ip:port */ public void remove(String connectId) { connectionToClientIpMap.remove(connectId); } /** * 是否包含连接到 clientIp 的映射 * * @param connectId * @return */ public boolean contains(String connectId) { return connectionToClientIpMap.containsKey(connectId); } /** * 获取连接对应的 clientIp * * @param connectId 连接 ip:port * @return clientIp */ public String get(String connectId) { return connectionToClientIpMap.get(connectId); } /** * 获取连接映射的 size * * @return 连接映射的 size */ public int size() { return connectionToClientIpMap.size(); } /** * 获取所有的连接映射 * * @return 连接映射表 */ public Map<String, String> get() { return Maps.newHashMap(connectionToClientIpMap); } }
3e09824fd2f577a92cd862f9013945e8eab282ef
12,766
java
Java
app/src/main/java/com/eventyay/organizer/core/attendee/list/AttendeesFragment.java
gargVader/open-event-organizer-android
319f7f4508afa39c3d429e3e765ffe334b229974
[ "Apache-2.0" ]
1,240
2019-07-03T14:07:54.000Z
2022-03-31T14:40:10.000Z
app/src/main/java/com/eventyay/organizer/core/attendee/list/AttendeesFragment.java
Appy-arsnel/open-event-organizer-android
04812b35c14141e0a788ebdc665cbf2d2dfbf0ed
[ "Apache-2.0" ]
1,638
2016-08-20T20:29:20.000Z
2019-07-01T11:34:04.000Z
app/src/main/java/com/eventyay/organizer/core/attendee/list/AttendeesFragment.java
Appy-arsnel/open-event-organizer-android
04812b35c14141e0a788ebdc665cbf2d2dfbf0ed
[ "Apache-2.0" ]
414
2019-07-11T10:06:36.000Z
2022-02-23T18:20:17.000Z
35.362881
192
0.676249
4,000
package com.eventyay.organizer.core.attendee.list; import android.content.Context; import android.graphics.PorterDuff; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import androidx.appcompat.widget.SearchView; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.eventyay.organizer.BR; import com.eventyay.organizer.R; import com.eventyay.organizer.common.mvp.view.BaseFragment; import com.eventyay.organizer.core.attendee.ScanningDecider; import com.eventyay.organizer.core.attendee.checkin.AttendeeCheckInFragment; import com.eventyay.organizer.core.attendee.list.listeners.AttendeeItemCheckInEvent; import com.eventyay.organizer.core.main.MainActivity; import com.eventyay.organizer.data.ContextUtils; import com.eventyay.organizer.data.attendee.Attendee; import com.eventyay.organizer.databinding.FragmentAttendeesBinding; import com.eventyay.organizer.ui.ViewUtils; import com.eventyay.organizer.utils.SearchUtils; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; import com.mikepenz.fastadapter.FastAdapter; import com.mikepenz.fastadapter.adapters.ItemAdapter; import com.mikepenz.fastadapter.utils.ComparableItemListImpl; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Inject; /** * A simple {@link Fragment} subclass. * Use the {@link AttendeesFragment#newInstance} factory method to * create an instance of this fragment. */ @SuppressWarnings("PMD.TooManyMethods") public class AttendeesFragment extends BaseFragment implements AttendeesView { private static final int SORTBYTICKET = 1; private static final int SORTBYNAME = 0; private static final long ITEMS_PER_PAGE = 20; private Context context; private long eventId; @Inject ContextUtils utilModel; @Inject ViewModelProvider.Factory viewModelFactory; private FastAdapter<Attendee> fastAdapter; private final ScanningDecider scanningDecider = new ScanningDecider(); private ItemAdapter<Attendee> fastItemAdapter; private FragmentAttendeesBinding binding; private SwipeRefreshLayout refreshLayout; private SearchView searchView; private static final long FIRST_PAGE = 1; private long currentPage = 1; private List<Attendee> attendeeList = new ArrayList<>(); private AttendeesViewModel attendeesViewModel; private RecyclerView.AdapterDataObserver observer; private static final String FILTER_SYNC = "FILTER_SYNC"; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param eventId id of the event. * @return A new instance of fragment AttendeesFragment. */ public static AttendeesFragment newInstance(long eventId) { AttendeesFragment fragment = new AttendeesFragment(); Bundle args = new Bundle(); args.putLong(MainActivity.EVENT_KEY, eventId); fragment.setArguments(args); return fragment; } // Lifecycle methods @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getActivity(); setHasOptionsMenu(true); if (getArguments() != null) eventId = getArguments().getLong(MainActivity.EVENT_KEY); } @Override public void onDestroy() { super.onDestroy(); if (observer != null) { fastAdapter.unregisterAdapterDataObserver(observer); } } public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_attendees, menu); MenuItem search = menu.findItem(R.id.search); searchView = (SearchView) search.getActionView(); setupSearchListener(); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.filterByNone: fastItemAdapter.filter(""); return true; case R.id.filterBySync: fastItemAdapter.filter(FILTER_SYNC); return true; case R.id.sortByTicket: sortAttendees(SORTBYTICKET); return true; case R.id.sortByName: sortAttendees(SORTBYNAME); return true; default: return super.onOptionsItemSelected(item); } } private void sortAttendees(int sortBy) { if (sortBy == SORTBYTICKET) { ((ComparableItemListImpl<Attendee>) fastItemAdapter.getItemList()).withComparator((Attendee a1, Attendee a2) -> a1.getTicket().getType().compareTo(a2.getTicket().getType()), true); } else { ((ComparableItemListImpl<Attendee>) fastItemAdapter.getItemList()).withComparator((Attendee a1, Attendee a2) -> a1.getFirstname().compareTo(a2.getFirstname()), true); } fastItemAdapter.setNewList(attendeeList, true); binding.setVariable(BR.attendees, attendeeList); binding.executePendingBindings(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment binding = DataBindingUtil.inflate(inflater, R.layout.fragment_attendees, container, false); attendeesViewModel = ViewModelProviders.of(this, viewModelFactory).get(AttendeesViewModel.class); binding.fabScanQr.getDrawable().setColorFilter(getResources().getColor(android.R.color.white), PorterDuff.Mode.SRC_ATOP); binding.fabScanQr.setOnClickListener(v -> scanningDecider.openScanQRActivity(getActivity(), eventId)); return binding.getRoot(); } @Override public void onStart() { super.onStart(); setupSearchListener(); setupRefreshListener(); setupRecyclerView(); attendeesViewModel.getProgress().observe(this, this::showProgress); attendeesViewModel.getError().observe(this, this::showError); attendeesViewModel.getAttendeesLiveData().observe(this, this::showResults); attendeesViewModel.getShowScanButtonLiveData().observe(this, this::showScanButton); attendeesViewModel.getUpdateAttendeeLiveData().observe(this, this::updateAttendee); attendeesViewModel.loadAttendeesPageWise(FIRST_PAGE, false); attendeesViewModel.listenChanges(); } @Override protected int getTitle() { return R.string.attendees; } @Override public void onStop() { super.onStop(); refreshLayout.setOnRefreshListener(null); if (searchView != null) searchView.setOnQueryTextListener(null); } private void setupSearchListener() { if (searchView == null) return; searchView.setQueryHint(getString(R.string.search_placeholder)); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { return false; } @Override public boolean onQueryTextChange(String s) { fastItemAdapter.filter(s.trim()); return true; } }); } private void setupRecyclerView() { fastItemAdapter = new ItemAdapter<>(); fastItemAdapter.getItemFilter().setFilterPredicate( (attendee, query) -> { if (query == null) return true; if (query.equals(FILTER_SYNC)) { return attendee.checking; } return !SearchUtils.filter( query.toString(), attendee.getFirstname(), attendee.getLastname(), attendee.getEmail()); } ); fastAdapter = FastAdapter.with(Collections.singletonList(fastItemAdapter)); fastAdapter.setHasStableIds(true); fastAdapter.addEventHook(new AttendeeItemCheckInEvent(this)); RecyclerView recyclerView = binding.rvAttendeeList; recyclerView.setLayoutManager(new LinearLayoutManager(context)); recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL)); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(fastAdapter); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (dy > 0 || dy < 0 && binding.fabScanQr.isShown()) binding.fabScanQr.hide(); if (!recyclerView.canScrollVertically(1)) { if (recyclerView.getAdapter().getItemCount() > currentPage * ITEMS_PER_PAGE) { currentPage++; } else { currentPage++; attendeesViewModel.loadAttendeesPageWise(currentPage, true); } } } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == RecyclerView.SCROLL_STATE_IDLE && recyclerView.getAdapter().getItemCount() != 0) { binding.fabScanQr.show(); } super.onScrollStateChanged(recyclerView, newState); } }); SwipeController swipeController = new SwipeController(attendeesViewModel, attendeeList, context); ItemTouchHelper itemTouchHelper = new ItemTouchHelper(swipeController); itemTouchHelper.attachToRecyclerView(recyclerView); observer = new RecyclerView.AdapterDataObserver() { @Override public void onChanged() { super.onChanged(); } }; fastAdapter.registerAdapterDataObserver(observer); ViewUtils.setRecyclerViewScrollAwareFabBehaviour(recyclerView, binding.fabScanQr); } private void setupRefreshListener() { refreshLayout = binding.swipeContainer; refreshLayout.setColorSchemeColors(utilModel.getResourceColor(R.color.color_accent)); refreshLayout.setOnRefreshListener(() -> { refreshLayout.setRefreshing(false); attendeeList.clear(); attendeesViewModel.loadAttendeesPageWise(FIRST_PAGE, true); currentPage = FIRST_PAGE; }); } // View Implementation @Override public void showToggleDialog(long attendeeId) { BottomSheetDialogFragment bottomSheetDialogFragment = AttendeeCheckInFragment.newInstance(attendeeId); bottomSheetDialogFragment.show(getFragmentManager(), bottomSheetDialogFragment.getTag()); } @Override public void showProgress(boolean show) { ViewUtils.showView(binding.progressBar, show); } @Override public void onRefreshComplete(boolean success) { // Nothing to do } @Override public void showScanButton(boolean show) { ViewUtils.showView(binding.fabScanQr, show); } @Override public void showResults(List<Attendee> attendees) { attendeeList.addAll(attendees); fastItemAdapter.setNewList(attendeeList, true); binding.setVariable(BR.attendees, attendeeList); binding.executePendingBindings(); } @Override public void showEmptyView(boolean show) { if (currentPage > 1) return; ViewUtils.showView(binding.emptyView, show); } @Override public void updateAttendee(Attendee attendee) { int position = fastItemAdapter.getAdapterPosition(attendee); fastItemAdapter.getItemFilter().set(position, attendee); } @Override public void showError(String error) { ViewUtils.showSnackbar(binding.getRoot(), error); } @Override public List<Attendee> getAttendeeList() { return attendeeList; } }
3e0982c0286fcedd5800233721ea92b10b7eca9c
4,053
java
Java
ApiCoin/src/Gui/GuiJframe.java
edenlandpl/readingFromWebsiteApi
df13a7807555bb1eac895378e01e1fef2af4b2a2
[ "MIT" ]
null
null
null
ApiCoin/src/Gui/GuiJframe.java
edenlandpl/readingFromWebsiteApi
df13a7807555bb1eac895378e01e1fef2af4b2a2
[ "MIT" ]
null
null
null
ApiCoin/src/Gui/GuiJframe.java
edenlandpl/readingFromWebsiteApi
df13a7807555bb1eac895378e01e1fef2af4b2a2
[ "MIT" ]
null
null
null
34.347458
99
0.582285
4,001
package Gui; import java.awt.Color; import java.awt.Container; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; /** ApiCoin * author - Dell * date - 3 paz 2018 * version - */ public class GuiJframe extends JFrame{ private JLabel labelUsername = new JLabel("Enter username: "); private JLabel labelPassword = new JLabel("Enter password: "); private JTextField textUsername = new JTextField(20); private JPasswordField fieldPassword = new JPasswordField(20); private JButton buttonLogin = new JButton("Login"); public GuiJframe() { //// super("ApiCoin"); // JFrame frameMain = new JFrame("Panel główny"); // // // JPanel panel01 = new JPanel(new GridBagLayout()); // //// Container zawartoscGlowna = new Container(); //// zawartoscGlowna.add(panel01); // //add(panel01); // panel01.setBounds(140,180,500,500); // panel01.setBackground(Color.gray); // //panel01.setSize(400, 400); // panel01.setLayout(null); //// setContentPane(panel01); // umieszczenie kontenera panel01 w oknie głównym oraz wyświetlenie //// panel01.setVisible(true); // JLabel nazwaCoin = new JLabel("PAC"); // panel01.add(nazwaCoin); // frameMain.add(panel01); // setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // setVisible(true); // setSize(800,600); // setLocation(50,50); // setTitle("Api Coin"); // ///////////////////////////////////////////////////////////////////////////////// // JFrame f= new JFrame("Panel Example"); // JPanel panel=new JPanel(); // panel.setBounds(40,80,200,200); // koordynaty lewego rogu, szerokość, wysokość // panel.setBackground(Color.gray); // JButton b1=new JButton("Button 1"); // b1.setBounds(50,100,80,30); // b1.setBackground(Color.yellow); // JButton b2=new JButton("Button 2"); // b2.setBounds(100,100,80,30); // b2.setBackground(Color.green); // panel.add(b1); panel.add(b2); // f.add(panel); // f.setSize(400,400); // f.setLocation(200,200); // f.setLayout(null); // f.setVisible(true); /////////////////////////////////////////////////////////////////// super("JPanel Demo Program"); // create a new panel with GridBagLayout manager JPanel newPanel = new JPanel(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(10, 10, 10, 10); // add components to the panel constraints.gridx = 0; constraints.gridy = 0; newPanel.add(labelUsername, constraints); constraints.gridx = 1; newPanel.add(textUsername, constraints); constraints.gridx = 0; constraints.gridy = 1; newPanel.add(labelPassword, constraints); constraints.gridx = 1; newPanel.add(fieldPassword, constraints); constraints.gridx = 0; constraints.gridy = 2; constraints.gridwidth = 2; constraints.anchor = GridBagConstraints.CENTER; newPanel.add(buttonLogin, constraints); // set border for the panel newPanel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "Login Panel")); // add the panel to this frame add(newPanel); pack(); setLocationRelativeTo(null); setVisible(true); } }
3e0982cc98b17dbac7c655eb5b1cc7faa0ba6d2c
482
java
Java
Lion-Chat-Server/src/Main.java
Lukasz98/Lion-Chat
9b8327d2d92e1aa0badc11ed90fc32266810d51d
[ "MIT" ]
null
null
null
Lion-Chat-Server/src/Main.java
Lukasz98/Lion-Chat
9b8327d2d92e1aa0badc11ed90fc32266810d51d
[ "MIT" ]
null
null
null
Lion-Chat-Server/src/Main.java
Lukasz98/Lion-Chat
9b8327d2d92e1aa0badc11ed90fc32266810d51d
[ "MIT" ]
null
null
null
19.28
64
0.547718
4,002
import org.mariadb.jdbc.MySQLDataSource; import java.sql.*; public class Main { public static void main(String args[]) { System.out.println("Server"); try { MySQL.Init(); } catch (SQLException e) { e.printStackTrace(); System.out.println("Cannot connect with database."); return; } Listener listener = new Listener(); listener.run(); //MySQL.LoadPrintTest(); } }
3e0983932e5b9bb9ef729e4c0f19043e0c838cd4
1,274
java
Java
nepxion-swing-demo/src/com/nepxion/demo/control/selector/DemoLocaleSelectorTogglePanel.java
Nepxion/Marvel
51bb477ccbff64067981bd92efcdb9b7b01c6f5f
[ "Apache-2.0" ]
10
2016-11-28T11:16:42.000Z
2021-08-22T04:03:21.000Z
nepxion-swing-demo/src/com/nepxion/demo/control/selector/DemoLocaleSelectorTogglePanel.java
Nepxion/Marvel
51bb477ccbff64067981bd92efcdb9b7b01c6f5f
[ "Apache-2.0" ]
null
null
null
nepxion-swing-demo/src/com/nepxion/demo/control/selector/DemoLocaleSelectorTogglePanel.java
Nepxion/Marvel
51bb477ccbff64067981bd92efcdb9b7b01c6f5f
[ "Apache-2.0" ]
2
2021-01-14T09:41:50.000Z
2021-07-01T14:17:51.000Z
23.981132
156
0.760031
4,003
package com.nepxion.demo.control.selector; /** * <p>Title: Nepxion Swing</p> * <p>Description: Nepxion Swing Repository</p> * <p>Copyright: Copyright (c) 2010</p> * <p>Company: Nepxion</p> * @author Neptune * @email envkt@example.com * @version 1.0 */ import javax.swing.Icon; import com.nepxion.demo.common.DemoTogglePanel; import com.nepxion.demo.common.DemoToggleTemplate; import com.nepxion.demo.component.selector.DemoLocaleSelectorPanel; import com.nepxion.swing.icon.IconFactory; import com.nepxion.swing.tabbedpane.JEclipseTabbedPane; public class DemoLocaleSelectorTogglePanel extends DemoTogglePanel { public DemoLocaleSelectorTogglePanel() { } public void initialize() { JEclipseTabbedPane toggleTabbedPane = getToggleTabbedPane(); toggleTabbedPane.addTab("Locale", IconFactory.getSwingIcon("component/locale_16.png"), new DemoToggleTemplate(new DemoLocaleSelectorPanel()), "Locale"); } public String getToggleText() { return "Locale"; } public Icon getToggleIcon() { return IconFactory.getSwingIcon("component/locale_32.png"); } public Icon getToggleBannerIcon() { return IconFactory.getSwingIcon("component/locale_32.png"); } public String getToggleDescription() { return "Multi-style Locale Selector"; } }
3e0983e1c8c362539631fb0c6b5388165a931b81
17,456
java
Java
code/iaas/model/src/main/java/io/cattle/platform/core/dao/impl/VolumeDaoImpl.java
wlcumt/cattlewl
d709bde3a0d7cb17b6a8a1bb4685681330bc625a
[ "Apache-2.0" ]
null
null
null
code/iaas/model/src/main/java/io/cattle/platform/core/dao/impl/VolumeDaoImpl.java
wlcumt/cattlewl
d709bde3a0d7cb17b6a8a1bb4685681330bc625a
[ "Apache-2.0" ]
null
null
null
code/iaas/model/src/main/java/io/cattle/platform/core/dao/impl/VolumeDaoImpl.java
wlcumt/cattlewl
d709bde3a0d7cb17b6a8a1bb4685681330bc625a
[ "Apache-2.0" ]
null
null
null
45.105943
135
0.621849
4,004
package io.cattle.platform.core.dao.impl; import static io.cattle.platform.core.model.tables.AccountTable.*; import static io.cattle.platform.core.model.tables.DeploymentUnitTable.*; import static io.cattle.platform.core.model.tables.InstanceTable.*; import static io.cattle.platform.core.model.tables.MountTable.*; import static io.cattle.platform.core.model.tables.StorageDriverTable.*; import static io.cattle.platform.core.model.tables.StoragePoolHostMapTable.*; import static io.cattle.platform.core.model.tables.StoragePoolTable.*; import static io.cattle.platform.core.model.tables.VolumeStoragePoolMapTable.*; import static io.cattle.platform.core.model.tables.VolumeTable.*; import static io.cattle.platform.core.model.tables.VolumeTemplateTable.*; import io.cattle.platform.core.addon.MountEntry; import io.cattle.platform.core.constants.AccountConstants; import io.cattle.platform.core.constants.CommonStatesConstants; import io.cattle.platform.core.constants.InstanceConstants; import io.cattle.platform.core.constants.StoragePoolConstants; import io.cattle.platform.core.constants.VolumeConstants; import io.cattle.platform.core.dao.GenericResourceDao; import io.cattle.platform.core.dao.VolumeDao; import io.cattle.platform.core.model.Mount; import io.cattle.platform.core.model.StorageDriver; import io.cattle.platform.core.model.StoragePool; import io.cattle.platform.core.model.Volume; import io.cattle.platform.core.model.VolumeStoragePoolMap; import io.cattle.platform.core.model.tables.records.MountRecord; import io.cattle.platform.core.model.tables.records.VolumeRecord; import io.cattle.platform.core.model.tables.records.VolumeStoragePoolMapRecord; import io.cattle.platform.core.util.VolumeUtils; import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao; import io.cattle.platform.deferred.util.DeferredUtils; import io.cattle.platform.object.ObjectManager; import io.cattle.platform.object.process.ObjectProcessManager; import io.cattle.platform.object.util.DataAccessor; import io.github.ibuildthecloud.gdapi.id.IdFormatter; import io.github.ibuildthecloud.gdapi.util.TransactionDelegate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.lang3.StringUtils; import org.jooq.Record; import org.jooq.Record6; import org.jooq.RecordHandler; @Named public class VolumeDaoImpl extends AbstractJooqDao implements VolumeDao { private static final Set<String> LOCAL_POOL_KINDS = new HashSet<>(Arrays.asList(new String[]{"docker", "sim"})); @Inject GenericResourceDao resourceDao; @Inject ObjectManager objectManager; @Inject ObjectProcessManager objectProcessManager; @Inject TransactionDelegate transaction; @Override public Volume findVolumeByExternalId(Long storagePoolId, String externalId) { Record record = create() .select(VOLUME.fields()) .from(VOLUME) .join(VOLUME_STORAGE_POOL_MAP) .on(VOLUME_STORAGE_POOL_MAP.STORAGE_POOL_ID.eq(storagePoolId)) .where(VOLUME.EXTERNAL_ID.eq(externalId) .or(VOLUME.EXTERNAL_ID.eq(VolumeUtils.externalId(externalId))) .and((VOLUME.REMOVED.isNull().or(VOLUME.STATE.eq(CommonStatesConstants.REMOVING))))) .fetchAny(); return record == null ? null : record.into(VolumeRecord.class); } @Override public void createVolumeInStoragePool(Map<String, Object> volumeData, String volumeName, StoragePool storagePool) { transaction.doInTransaction(() -> { Record record = create() .select(VOLUME.fields()) .from(VOLUME) .join(VOLUME_STORAGE_POOL_MAP) .on(VOLUME_STORAGE_POOL_MAP.VOLUME_ID.eq(VOLUME.ID) .and(VOLUME_STORAGE_POOL_MAP.STORAGE_POOL_ID.eq(storagePool.getId()))) .join(STORAGE_POOL) .on(VOLUME_STORAGE_POOL_MAP.STORAGE_POOL_ID.eq(STORAGE_POOL.ID)) .and(STORAGE_POOL.REMOVED.isNull()) .where(VOLUME.NAME.eq(volumeName) .and((VOLUME.REMOVED.isNull().or(VOLUME.STATE.eq(CommonStatesConstants.REMOVING))))) .and(VOLUME.ACCOUNT_ID.eq(storagePool.getAccountId())) .fetchAny(); if (record != null) { return; } Volume volume = resourceDao.createAndSchedule(Volume.class, volumeData); Map<String, Object> vspm = new HashMap<>(); vspm.put("volumeId", volume.getId()); vspm.put("storagePoolId", storagePool.getId()); resourceDao.createAndSchedule(VolumeStoragePoolMap.class, vspm); }); } @Override public List<? extends Volume> findSharedOrUnmappedVolumes(long accountId, String volumeName) { List<VolumeRecord> volumes = create() .selectDistinct(VOLUME.fields()) .from(VOLUME) .leftOuterJoin(VOLUME_STORAGE_POOL_MAP) .on(VOLUME_STORAGE_POOL_MAP.VOLUME_ID.eq(VOLUME.ID)) .leftOuterJoin(STORAGE_POOL) .on(VOLUME_STORAGE_POOL_MAP.STORAGE_POOL_ID.eq(STORAGE_POOL.ID)) .where(VOLUME.NAME.eq(volumeName) .and((VOLUME.REMOVED.isNull()))) .and(VOLUME.ACCOUNT_ID.eq(accountId)) .and(STORAGE_POOL.KIND.notIn(LOCAL_POOL_KINDS).or(STORAGE_POOL.KIND.isNull())) .and(STORAGE_POOL.REMOVED.isNull()) .fetchInto(VolumeRecord.class); return volumes; } @Override public List<? extends Volume> identifyUnmappedVolumes(long accountId, Set<Long> volumeIds) { List<VolumeRecord> volumes = create() .selectDistinct(VOLUME.fields()) .from(VOLUME) .leftOuterJoin(VOLUME_STORAGE_POOL_MAP) .on(VOLUME_STORAGE_POOL_MAP.VOLUME_ID.eq(VOLUME.ID)) .where(VOLUME.ID.in(volumeIds) .and((VOLUME.REMOVED.isNull()))) .and(VOLUME.ACCOUNT_ID.eq(accountId)) .and(VOLUME_STORAGE_POOL_MAP.ID.isNull()) .fetchInto(VolumeRecord.class); return volumes; } public static final List<String> INELLIGIBLE_STATES = Arrays.asList(CommonStatesConstants.ACTIVE, CommonStatesConstants.ACTIVATING, CommonStatesConstants.REQUESTED); @Override public Set<? extends Volume> findNonremovedVolumesWithNoOtherMounts(long instanceId) { List<Long> instanceVolumeIds = create() .select(MOUNT.VOLUME_ID) .from(MOUNT) .where(MOUNT.INSTANCE_ID.eq(instanceId)) .fetchInto(Long.class); List<Long> inelligibleVolumeIds = create() .select(MOUNT.VOLUME_ID) .from(MOUNT) .where(MOUNT.VOLUME_ID.in(instanceVolumeIds) .and(MOUNT.INSTANCE_ID.ne(instanceId)) .and(MOUNT.STATE.in(INELLIGIBLE_STATES))) .fetchInto(Long.class); Set<Long> volumeIds = new HashSet<>(instanceVolumeIds); volumeIds.removeAll(inelligibleVolumeIds); List<VolumeRecord> vols = create() .select(VOLUME.fields()) .from(VOLUME) .where(VOLUME.ID.in(volumeIds)) .and(VOLUME.REMOVED.isNull()) .fetchInto(VolumeRecord.class); Set<? extends Volume> volumes = new HashSet<Volume>(vols); return volumes; } @Override public Volume createVolumeForDriver(final long accountId, final String volumeName, final String driverName) { StorageDriver driver = objectManager.findAny(StorageDriver.class, STORAGE_DRIVER.NAME, driverName, STORAGE_DRIVER.ACCOUNT_ID, accountId, STORAGE_DRIVER.REMOVED, null); final Long driverId = driver == null ? null : driver.getId(); return DeferredUtils.nest(new Callable<Volume>() { @Override public Volume call() throws Exception { return resourceDao.createAndSchedule(Volume.class, VOLUME.NAME, volumeName, VOLUME.ACCOUNT_ID, accountId, VOLUME.STORAGE_DRIVER_ID, driverId, VolumeConstants.FIELD_VOLUME_DRIVER, driverName); } }); } @Override public Map<Long, List<MountEntry>> getMountsForInstances(List<Long> ids, final IdFormatter idF) { final Map<Long, List<MountEntry>> result = new HashMap<>(); create().select(INSTANCE.NAME, VOLUME.NAME, VOLUME.ID, MOUNT.PERMISSIONS, MOUNT.PATH, MOUNT.INSTANCE_ID) .from(MOUNT) .join(VOLUME) .on(VOLUME.ID.eq(MOUNT.VOLUME_ID)) .join(INSTANCE) .on(INSTANCE.ID.eq(MOUNT.INSTANCE_ID)) .where(MOUNT.REMOVED.isNull() .and(VOLUME.REMOVED.isNull()) .and(MOUNT.INSTANCE_ID.in(ids))) .fetchInto(new RecordHandler<Record6<String, String, Long, String, String, Long>>() { @Override public void next(Record6<String, String, Long, String, String, Long> record) { Long instanceId = record.getValue(MOUNT.INSTANCE_ID); List<MountEntry> entries = result.get(instanceId); if (entries == null) { entries = new ArrayList<>(); result.put(instanceId, entries); } MountEntry mount = new MountEntry(); mount.setInstanceName(record.getValue(INSTANCE.NAME)); mount.setInstanceId(idF.formatId(InstanceConstants.TYPE, instanceId)); mount.setPath(record.getValue(MOUNT.PATH)); mount.setPermission(record.getValue(MOUNT.PERMISSIONS)); mount.setVolumeId(idF.formatId(VolumeConstants.TYPE, record.getValue(VOLUME.ID))); mount.setVolumeName(record.getValue(VOLUME.NAME)); entries.add(mount); } }); return result; } @Override public Map<Long, List<MountEntry>> getMountsForVolumes(List<Long> ids, final IdFormatter idF) { final Map<Long, List<MountEntry>> result = new HashMap<>(); create().select(VOLUME.NAME, MOUNT.PERMISSIONS, MOUNT.PATH, MOUNT.INSTANCE_ID, MOUNT.VOLUME_ID, INSTANCE.NAME) .from(MOUNT) .join(INSTANCE) .on(INSTANCE.ID.eq(MOUNT.INSTANCE_ID)) .join(VOLUME) .on(VOLUME.ID.eq(MOUNT.VOLUME_ID)) .where(INSTANCE.REMOVED.isNull() .and(VOLUME.REMOVED.isNull()) .and(MOUNT.VOLUME_ID.in(ids))) .fetchInto(new RecordHandler<Record6<String, String, String, Long, Long, String>>() { @Override public void next(Record6<String, String, String, Long, Long, String> record) { Long volumeId = record.getValue(MOUNT.VOLUME_ID); List<MountEntry> entries = result.get(volumeId); if (entries == null) { entries = new ArrayList<>(); result.put(volumeId, entries); } MountEntry mount = new MountEntry(); mount.setInstanceName(record.getValue(INSTANCE.NAME)); mount.setInstanceId(idF.formatId(InstanceConstants.TYPE, record.getValue(MOUNT.INSTANCE_ID))); mount.setPath(record.getValue(MOUNT.PATH)); mount.setPermission(record.getValue(MOUNT.PERMISSIONS)); mount.setVolumeId(idF.formatId(VolumeConstants.TYPE, volumeId)); mount.setVolumeName(record.getValue(VOLUME.NAME)); entries.add(mount); } }); return result; } @Override public List<? extends Volume> findNonRemovedVolumesOnPool(Long storagePoolId) { return create().select(VOLUME.fields()) .from(VOLUME) .join(VOLUME_STORAGE_POOL_MAP) .on(VOLUME_STORAGE_POOL_MAP.VOLUME_ID.eq(VOLUME.ID)) .join(STORAGE_POOL) .on(STORAGE_POOL.ID.eq(VOLUME_STORAGE_POOL_MAP.STORAGE_POOL_ID)) .where(VOLUME.REMOVED.isNull() .and(STORAGE_POOL.ID.eq(storagePoolId))) .fetchInto(VolumeRecord.class); } @Override public List<? extends Volume> findBadVolumes(int count) { return create().select(VOLUME.fields()) .from(VOLUME) .join(ACCOUNT) .on(ACCOUNT.ID.eq(VOLUME.ACCOUNT_ID)) .where(VOLUME.REMOVED.isNull() .and(ACCOUNT.STATE.eq(AccountConstants.STATE_PURGED)) .and(VOLUME.STATE.notIn(CommonStatesConstants.DEACTIVATING, CommonStatesConstants.REMOVING))) .limit(count) .fetchInto(VolumeRecord.class); } @Override public List<? extends Volume> findBadNativeVolumes(int count) { return create().select(VOLUME.fields()) .from(VOLUME) .join(MOUNT) .on(MOUNT.VOLUME_ID.eq(VOLUME.ID)) .join(INSTANCE) .on(MOUNT.INSTANCE_ID.eq(INSTANCE.ID)) .where(INSTANCE.STATE.eq(AccountConstants.STATE_PURGED) .and(VOLUME.STATE.eq(CommonStatesConstants.INACTIVE)) .and(INSTANCE.NATIVE_CONTAINER.isTrue())) .limit(count) .fetchInto(VolumeRecord.class); } @Override public List<? extends Mount> findBadMounts(int count) { return create().select(MOUNT.fields()) .from(MOUNT) .join(VOLUME) .on(VOLUME.ID.eq(MOUNT.VOLUME_ID)) .where(VOLUME.STATE.eq(AccountConstants.STATE_PURGED) .and(MOUNT.REMOVED.isNull()) .and(MOUNT.STATE.notIn(CommonStatesConstants.DEACTIVATING, CommonStatesConstants.REMOVING))) .limit(count) .fetchInto(MountRecord.class); } @Override public List<? extends VolumeStoragePoolMap> findBandVolumeStoragePoolMap(int count) { return create().select(VOLUME_STORAGE_POOL_MAP.fields()) .from(VOLUME_STORAGE_POOL_MAP) .join(VOLUME) .on(VOLUME.ID.eq(VOLUME_STORAGE_POOL_MAP.VOLUME_ID)) .where(VOLUME.STATE.eq(AccountConstants.STATE_PURGED) .and(VOLUME_STORAGE_POOL_MAP.REMOVED.isNull()) .and(VOLUME_STORAGE_POOL_MAP.STATE.notIn(CommonStatesConstants.DEACTIVATING, CommonStatesConstants.REMOVING))) .limit(count) .fetchInto(VolumeStoragePoolMapRecord.class); } @Override public List<Long> findDeploymentUnitsForVolume(Volume volume) { if (volume.getVolumeTemplateId() == null) { return Collections.emptyList(); } return create().select(DEPLOYMENT_UNIT.ID) .from(DEPLOYMENT_UNIT) .join(VOLUME_TEMPLATE) .on(VOLUME_TEMPLATE.STACK_ID.eq(DEPLOYMENT_UNIT.STACK_ID)) .where( DEPLOYMENT_UNIT.REMOVED.isNull() .and(VOLUME_TEMPLATE.ID.eq(volume.getVolumeTemplateId()))) .fetch(DEPLOYMENT_UNIT.ID); } @Override public Long findPoolForVolumeAndHost(Volume volume, long hostId) { String storageDriver = DataAccessor.fieldString(volume, VolumeConstants.FIELD_VOLUME_DRIVER); Long storageDriverId = volume.getStorageDriverId(); if (storageDriverId != null) { return create().select(STORAGE_POOL.ID) .from(STORAGE_POOL) .join(STORAGE_POOL_HOST_MAP) .on(STORAGE_POOL_HOST_MAP.STORAGE_POOL_ID.eq(STORAGE_POOL.ID)) .where(STORAGE_POOL.STORAGE_DRIVER_ID.eq(storageDriverId) .and(STORAGE_POOL_HOST_MAP.REMOVED.isNull()) .and(STORAGE_POOL.REMOVED.isNull()) .and(STORAGE_POOL_HOST_MAP.HOST_ID.eq(hostId))) .fetchAny(STORAGE_POOL.ID); } else if (StringUtils.isBlank(storageDriver) || VolumeConstants.LOCAL_DRIVER.equalsIgnoreCase(storageDriver)) { return create().select(STORAGE_POOL.ID) .from(STORAGE_POOL) .join(STORAGE_POOL_HOST_MAP) .on(STORAGE_POOL_HOST_MAP.STORAGE_POOL_ID.eq(STORAGE_POOL.ID)) .where(STORAGE_POOL.KIND.in(StoragePoolConstants.UNMANGED_STORAGE_POOLS) .and(STORAGE_POOL_HOST_MAP.REMOVED.isNull()) .and(STORAGE_POOL.REMOVED.isNull()) .and(STORAGE_POOL_HOST_MAP.HOST_ID.eq(hostId))) .fetchAny(STORAGE_POOL.ID); } return null; } }
3e0983fcd150e3d1922aa7de52085d0c05a19f8f
391
java
Java
freeipa-api/src/main/java/com/sequenceiq/service/api/doc/ModelDescriptions.java
doktoric/cloudbreak
0298ec42f9dcf23166fa06720ddcd73a3c2d224b
[ "Apache-2.0" ]
null
null
null
freeipa-api/src/main/java/com/sequenceiq/service/api/doc/ModelDescriptions.java
doktoric/cloudbreak
0298ec42f9dcf23166fa06720ddcd73a3c2d224b
[ "Apache-2.0" ]
1
2019-05-27T12:58:48.000Z
2019-05-27T12:58:48.000Z
freeipa-api/src/main/java/com/sequenceiq/service/api/doc/ModelDescriptions.java
doktoric/cloudbreak
0298ec42f9dcf23166fa06720ddcd73a3c2d224b
[ "Apache-2.0" ]
null
null
null
32.583333
77
0.734015
4,005
package com.sequenceiq.service.api.doc; public class ModelDescriptions { public static final String ID = "id of the resource"; public static final String NAME = "name of the resource"; public static final String DESCRIPTION = "description of the resource"; public static final String ENVIRONMENTS = "Environments of the resource"; private ModelDescriptions() { } }
3e0984385a10475026892e33f9aa7c241727f36b
1,747
java
Java
src/com/example/campushelper/activity/ScheduleActivity.java
ChuYh96/CampusHelper
b99eb256f69d41021affda09f762fea3524d55b2
[ "Apache-2.0" ]
null
null
null
src/com/example/campushelper/activity/ScheduleActivity.java
ChuYh96/CampusHelper
b99eb256f69d41021affda09f762fea3524d55b2
[ "Apache-2.0" ]
null
null
null
src/com/example/campushelper/activity/ScheduleActivity.java
ChuYh96/CampusHelper
b99eb256f69d41021affda09f762fea3524d55b2
[ "Apache-2.0" ]
null
null
null
28.639344
78
0.761878
4,006
package com.example.campushelper.activity; import com.example.campushelper.R; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class ScheduleActivity extends BaseActivity { private TextView btn_back; private EditText edit_semester, edit_stuId; private Button btn_search_schedule; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.layout_schedule); btn_back = (TextView) findViewById(R.id.title_back); btn_back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // finish(); Intent intent = new Intent(ScheduleActivity.this, MainActivity.class); startActivity(intent); } }); edit_semester = (EditText) findViewById(R.id.edit_semester); edit_stuId = (EditText) findViewById(R.id.edit_stu_num); btn_search_schedule = (Button) findViewById(R.id.btn_search_schedule); btn_search_schedule.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String semester = edit_semester.getText().toString(); String stuNum = edit_stuId.getText().toString(); ScheduleShowActivity.actionStart(ScheduleActivity.this, semester, stuNum); } }); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); ActivityCollector.finishAll(); } }
3e0984563a034c97b9085aa86e5534249062c000
7,149
java
Java
java/timebase/server/src/test/java/com/epam/deltix/qsrv/dtb/fs/azure/ReopenThresholdBenchmark.java
mcleo-d/TimeBase-CE
ecbe6fd28161c19bbafee6fd90b728655f34956e
[ "Apache-2.0" ]
23
2021-08-19T12:26:37.000Z
2022-03-22T14:58:54.000Z
java/timebase/server/src/test/java/com/epam/deltix/qsrv/dtb/fs/azure/ReopenThresholdBenchmark.java
mcleo-d/TimeBase-CE
ecbe6fd28161c19bbafee6fd90b728655f34956e
[ "Apache-2.0" ]
173
2021-05-13T11:04:42.000Z
2021-07-07T13:25:15.000Z
java/timebase/server/src/test/java/com/epam/deltix/qsrv/dtb/fs/azure/ReopenThresholdBenchmark.java
mcleo-d/TimeBase-CE
ecbe6fd28161c19bbafee6fd90b728655f34956e
[ "Apache-2.0" ]
5
2021-07-14T19:08:50.000Z
2022-03-18T13:48:06.000Z
35.391089
111
0.683312
4,007
/* * Copyright 2021 EPAM Systems, Inc * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. Licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.epam.deltix.qsrv.dtb.fs.azure; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.epam.deltix.qsrv.QSHome; import com.epam.deltix.qsrv.dtb.fs.azure2.AzureFsBase; import com.epam.deltix.timebase.messages.ConstantIdentityKey; import com.epam.deltix.timebase.messages.InstrumentMessage; import com.epam.deltix.qsrv.hf.tickdb.impl.TickDBImpl; import com.epam.deltix.qsrv.hf.tickdb.pub.DXTickDB; import com.epam.deltix.qsrv.hf.tickdb.pub.DXTickStream; import com.epam.deltix.qsrv.hf.tickdb.pub.SelectionOptions; import com.epam.deltix.qsrv.hf.tickdb.pub.TickCursor; import com.epam.deltix.util.concurrent.QuickExecutor; import com.epam.deltix.util.io.Home; import com.epam.deltix.util.os.CommonSysProps; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.results.format.ResultFormatType; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; /** * Measures performance of reading from Azure DataLake using {@link AzureFS} * with different values of {@link AzureFsBase#AZURE_REOPEN_ON_SEEK_THRESHOLD_PROP} parameter. * * @author Alexei Osipov */ @Warmup(time = 10, timeUnit = TimeUnit.SECONDS, iterations = 0) @Measurement(time = 2, timeUnit = TimeUnit.MINUTES, iterations = 1) @BenchmarkMode(Mode.Throughput) @Fork(1) @Threads(1) public class ReopenThresholdBenchmark { public static final String SELECTED_SYMBOLS_PATH = "ticks_selected.txt"; private static final Properties benchProps = getProps(); private static Properties getProps() { Properties props = new Properties(); try (FileInputStream is = new FileInputStream("cursor_read_bench.properties")){ props.load(is); } catch (Exception e) { throw new RuntimeException(e); } return props; } @Benchmark @OperationsPerInvocation(100_000) public long bench(SparseStreamState state) throws Exception { return readMessages(state.cursor, 100_000); } @State(Scope.Thread) public static class SparseStreamState extends StreamState { @Setup public void prepare(DbState dbState) throws Exception { cursor = setupCursor(dbState, benchProps.getProperty("sparseStream").trim()); } } @State(Scope.Benchmark) public static class DbState { //@Param({"1", "4", "8", "16", "32", "64", "128"}) @Param({"8", "64", "256", "1024", "2048", 8 * 1024 + ""}) long reopenThresholdKb; DXTickDB db; @Setup public void prepare() throws Exception { System.setProperty(AzureFsBase.AZURE_REOPEN_ON_SEEK_THRESHOLD_PROP, reopenThresholdKb * 1024 + ""); db = constructDB(); } @TearDown public void teardown() { db.close(); QuickExecutor.shutdownGlobalInstance(); } } public static abstract class StreamState { TickCursor cursor; protected TickCursor setupCursor(DbState dbState, String name) throws IOException { final DXTickStream stream = dbState.db.getStream(name); TickCursor cursor = stream.createCursor(new SelectionOptions()); List<String> selectedSymbols = getSelectedSymbols(); for (String symbol : selectedSymbols) { cursor.addEntity(new ConstantIdentityKey(symbol)); } cursor.reset(0); return cursor; } private static List<String> getSelectedSymbols() throws IOException { String content = new String(Files.readAllBytes(Paths.get(SELECTED_SYMBOLS_PATH))); return Lists.newArrayList(Splitter.on("\n").trimResults().omitEmptyStrings().split(content)); } } public static DXTickDB constructDB() throws Exception { // Load benchmark properties String home = benchProps.getProperty("deltix.home").trim(); String qsHome = benchProps.getProperty("qsHome").trim(); // Setub TB sustem props Home.set(home); CommonSysProps.mergeProps(); String timebaseLocation = qsHome + "\\timebase"; File folder = new File(timebaseLocation); QSHome.set(folder.getParent()); final DXTickDB db = new TickDBImpl(folder); db.open(false); return db; //final DXTickStream stream = db.getStream(STREAM_KEY); } private long readMessages(TickCursor cursor, int n) { long timeStampMs = 0; for (int i = 0; i < n; i++) { if (cursor.next()) { InstrumentMessage message = cursor.getMessage(); timeStampMs = message.getTimeStampMs(); } else { System.out.println("Cursor has no more messages. Resetting..."); cursor.reset(0); } } return timeStampMs; } public static void main(String[] args) throws RunnerException { String simpleName = ReopenThresholdBenchmark.class.getSimpleName(); Options opt = new OptionsBuilder() .include(simpleName) //.forks(1) //.syncIterations(false) .shouldFailOnError(true) .shouldDoGC(true) .result(simpleName + "_report.json") .resultFormat(ResultFormatType.JSON) .build(); Collection<RunResult> runResults = new Runner(opt).run(); System.out.println(runResults); } }
3e0984777736ff550db0eaebd9ac6bf170ebeab8
1,481
java
Java
lightadmin-core/src/main/java/org/lightadmin/core/config/bootstrap/parsing/validation/CustomFieldMetadataValidator.java
nevenc/light-admin
8855f3c875a1629448034e4286684c0c9b78072b
[ "Apache-2.0" ]
587
2015-01-04T02:12:39.000Z
2022-03-17T02:45:05.000Z
lightadmin-core/src/main/java/org/lightadmin/core/config/bootstrap/parsing/validation/CustomFieldMetadataValidator.java
servy/light-admin
b26c4f8ba13ab0d64627d01dcbba50609ff04a4f
[ "Apache-2.0" ]
103
2015-01-06T20:03:57.000Z
2020-06-07T11:26:57.000Z
lightadmin-core/src/main/java/org/lightadmin/core/config/bootstrap/parsing/validation/CustomFieldMetadataValidator.java
servy/light-admin
b26c4f8ba13ab0d64627d01dcbba50609ff04a4f
[ "Apache-2.0" ]
289
2015-01-01T10:24:17.000Z
2022-03-07T04:12:15.000Z
42.314286
195
0.779878
4,008
/* * Copyright 2012-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lightadmin.core.config.bootstrap.parsing.validation; import org.lightadmin.core.config.bootstrap.parsing.DomainConfigurationProblem; import org.lightadmin.core.config.domain.field.CustomFieldMetadata; import java.util.Collection; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.emptyList; class CustomFieldMetadataValidator implements FieldMetadataValidator<CustomFieldMetadata> { @Override public Collection<? extends DomainConfigurationProblem> validateFieldMetadata(CustomFieldMetadata fieldMetadata, Class<?> domainType, DomainConfigurationValidationContext validationContext) { if (fieldMetadata.getRenderer() == null) { return newArrayList(validationContext.rendererNotDefinedForFieldProblem(fieldMetadata.getName())); } return emptyList(); } }
3e098563d3969f3962fb35bd99566c87a2216788
79
java
Java
src/main/java/com/ancun/fastdfs/upload/config/FastdfsConfig.java
atian15/fastdfs-client
9559c198ba87b5958d9360998c13aedda92e59f8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ancun/fastdfs/upload/config/FastdfsConfig.java
atian15/fastdfs-client
9559c198ba87b5958d9360998c13aedda92e59f8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ancun/fastdfs/upload/config/FastdfsConfig.java
atian15/fastdfs-client
9559c198ba87b5958d9360998c13aedda92e59f8
[ "Apache-2.0" ]
null
null
null
13.166667
41
0.734177
4,009
package com.ancun.fastdfs.upload.config; public class FastdfsConfig { }
3e098597fbe279b2135292e15f0853d58374c0f6
8,209
java
Java
google/detectors/exposedui/kubernetes/src/test/java/com/google/tsunami/plugins/detectors/exposedui/kubernetes/KubernetesApiExposedDetectorTest.java
5wimming/5wimming-security-scanner-plugins
5e21863187af2070b0bd7387d891572c23d12a8d
[ "Apache-2.0" ]
766
2020-06-10T10:01:42.000Z
2022-03-30T17:18:46.000Z
google/detectors/exposedui/kubernetes/src/test/java/com/google/tsunami/plugins/detectors/exposedui/kubernetes/KubernetesApiExposedDetectorTest.java
5wimming/5wimming-security-scanner-plugins
5e21863187af2070b0bd7387d891572c23d12a8d
[ "Apache-2.0" ]
193
2020-06-21T17:38:52.000Z
2022-03-31T16:21:18.000Z
google/detectors/exposedui/kubernetes/src/test/java/com/google/tsunami/plugins/detectors/exposedui/kubernetes/KubernetesApiExposedDetectorTest.java
5wimming/5wimming-security-scanner-plugins
5e21863187af2070b0bd7387d891572c23d12a8d
[ "Apache-2.0" ]
150
2020-06-15T17:47:53.000Z
2022-03-29T10:27:19.000Z
41.045
99
0.653307
4,010
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.tsunami.plugins.detectors.exposedui.kubernetes; import static com.google.common.truth.extensions.proto.ProtoTruth.assertThat; import static com.google.tsunami.common.data.NetworkEndpointUtils.forHostname; import static com.google.tsunami.common.data.NetworkEndpointUtils.forHostnameAndPort; import com.google.common.collect.ImmutableList; import com.google.inject.Guice; import com.google.protobuf.util.Timestamps; import com.google.tsunami.common.net.http.HttpClientModule; import com.google.tsunami.common.net.http.HttpStatus; import com.google.tsunami.common.time.testing.FakeUtcClock; import com.google.tsunami.common.time.testing.FakeUtcClockModule; import com.google.tsunami.proto.AdditionalDetail; import com.google.tsunami.proto.DetectionReport; import com.google.tsunami.proto.DetectionStatus; import com.google.tsunami.proto.NetworkEndpoint; import com.google.tsunami.proto.NetworkService; import com.google.tsunami.proto.Severity; import com.google.tsunami.proto.Software; import com.google.tsunami.proto.TargetInfo; import com.google.tsunami.proto.TextData; import com.google.tsunami.proto.TransportProtocol; import com.google.tsunami.proto.Vulnerability; import com.google.tsunami.proto.VulnerabilityId; import java.io.IOException; import java.time.Instant; import javax.inject.Inject; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link KubernetesApiExposedDetector}. */ @RunWith(JUnit4.class) public final class KubernetesApiExposedDetectorTest { private final FakeUtcClock fakeUtcClock = FakeUtcClock.create().setNow(Instant.parse("2020-01-01T00:00:00.00Z")); private MockWebServer mockWebServer; @Inject private KubernetesApiExposedDetector detector; @Before public void setUp() { mockWebServer = new MockWebServer(); Guice.createInjector( new FakeUtcClockModule(fakeUtcClock), new HttpClientModule.Builder().build(), new KubernetesApiExposedDetectorBootstrapModule()) .injectMembers(this); } @After public void tearDown() throws IOException { mockWebServer.shutdown(); } @Test public void detect_whenApiEndpointExposed_reportsVuln() throws IOException { startMockWebServer( "/api/v1/pods", HttpStatus.OK.code(), "{\r\n \"kind\": \"PodList\",\r\n \"apiVersion\": \"v1\"\r\n}\r\n"); ImmutableList<NetworkService> httpServices = ImmutableList.of( NetworkService.newBuilder() .setNetworkEndpoint( forHostnameAndPort(mockWebServer.getHostName(), mockWebServer.getPort())) .setTransportProtocol(TransportProtocol.TCP) .setSoftware(Software.newBuilder().setName("Kubernetes API")) .setServiceName("http") .build()); assertThat( detector .detect(buildTargetInfo(forHostname(mockWebServer.getHostName())), httpServices) .getDetectionReportsList()) .containsExactly( DetectionReport.newBuilder() .setTargetInfo(buildTargetInfo(forHostname(mockWebServer.getHostName()))) .setNetworkService(httpServices.get(0)) .setDetectionTimestamp(Timestamps.fromMillis(fakeUtcClock.millis())) .setDetectionStatus(DetectionStatus.VULNERABILITY_VERIFIED) .setVulnerability( Vulnerability.newBuilder() .setMainId( VulnerabilityId.newBuilder() .setPublisher("GOOGLE") .setValue("KUBERNETES_API_EXPOSED")) .setSeverity(Severity.CRITICAL) .setTitle("Kubernetes API Exposed") .setDescription("Kubernetes API endpoint is exposed.") .addAdditionalDetails( AdditionalDetail.newBuilder() .setTextData( TextData.newBuilder() .setText( String.format( "The Kubernetes API endpoint at" + " http://%s:%d/api/v1/pods is exposed.", mockWebServer.getHostName(), mockWebServer.getPort()))))) .build()); } @Test public void detect_whenApiEndpointNotFound_doesNotReportVuln() throws IOException { startMockWebServer("/api/v1/pods", HttpStatus.NOT_FOUND.code(), ""); ImmutableList<NetworkService> httpServices = ImmutableList.of( NetworkService.newBuilder() .setNetworkEndpoint( forHostnameAndPort(mockWebServer.getHostName(), mockWebServer.getPort())) .setTransportProtocol(TransportProtocol.TCP) .setSoftware(Software.newBuilder().setName("Kubernetes API")) .setServiceName("http") .build()); assertThat( detector .detect(buildTargetInfo(forHostname(mockWebServer.getHostName())), httpServices) .getDetectionReportsList()) .isEmpty(); } @Test public void detect_whenNonKubernetesWebApp_ignoresServices() throws IOException { startMockWebServer("/api/v1/pods", HttpStatus.OK.code(), "This is WordPress."); ImmutableList<NetworkService> httpServices = ImmutableList.of( NetworkService.newBuilder() .setNetworkEndpoint( forHostnameAndPort(mockWebServer.getHostName(), mockWebServer.getPort())) .setTransportProtocol(TransportProtocol.TCP) .setSoftware(Software.newBuilder().setName("WordPress")) .setServiceName("http") .build()); assertThat( detector .detect(buildTargetInfo(forHostname(mockWebServer.getHostName())), httpServices) .getDetectionReportsList()) .isEmpty(); } @Test public void detect_whenNonHttpNetworkService_ignoresServices() { ImmutableList<NetworkService> nonHttpServices = ImmutableList.of( NetworkService.newBuilder().setServiceName("ssh").build(), NetworkService.newBuilder().setServiceName("rdp").build()); assertThat( detector .detect(buildTargetInfo(forHostname(mockWebServer.getHostName())), nonHttpServices) .getDetectionReportsList()) .isEmpty(); } @Test public void detect_whenEmptyNetworkService_generatesEmptyDetectionReports() { assertThat( detector .detect( buildTargetInfo(forHostname(mockWebServer.getHostName())), ImmutableList.of()) .getDetectionReportsList()) .isEmpty(); } private void startMockWebServer(String url, int responseCode, String response) throws IOException { mockWebServer.enqueue(new MockResponse().setResponseCode(responseCode).setBody(response)); mockWebServer.start(); mockWebServer.url(url); } private static TargetInfo buildTargetInfo(NetworkEndpoint networkEndpoint) { return TargetInfo.newBuilder().addNetworkEndpoints(networkEndpoint).build(); } }
3e0985c4e81231f28e02b329d379967f5a081add
928
java
Java
PgBulkInsert/src/main/java/de/bytefish/pgbulkinsert/model/ColumnDefinition.java
momania/PgBulkInsert
1cc25223f4d07d16f3bf5868cb2cf5a69b9c63a2
[ "MIT" ]
null
null
null
PgBulkInsert/src/main/java/de/bytefish/pgbulkinsert/model/ColumnDefinition.java
momania/PgBulkInsert
1cc25223f4d07d16f3bf5868cb2cf5a69b9c63a2
[ "MIT" ]
null
null
null
PgBulkInsert/src/main/java/de/bytefish/pgbulkinsert/model/ColumnDefinition.java
momania/PgBulkInsert
1cc25223f4d07d16f3bf5868cb2cf5a69b9c63a2
[ "MIT" ]
2
2019-07-23T08:51:24.000Z
2019-07-23T09:00:31.000Z
28.121212
110
0.707974
4,011
// Copyright (c) Philipp Wagner. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. package de.bytefish.pgbulkinsert.model; import de.bytefish.pgbulkinsert.functional.Action2; import de.bytefish.pgbulkinsert.pgsql.PgBinaryWriter; public class ColumnDefinition<TEntity> { private final String columnName; private final Action2<PgBinaryWriter, TEntity> write; public ColumnDefinition(String columnName, Action2<PgBinaryWriter, TEntity> write) { this.columnName = columnName; this.write = write; } public String getColumnName() { return columnName; } public Action2<PgBinaryWriter, TEntity> getWrite() { return write; } @Override public String toString() { return String.format("ColumnDefinition (ColumnName = {%1$s}, Serialize = {%2$s})", columnName, write); } }
3e0986582edd136de1c9dbffd4c7521870118fc5
28,110
java
Java
bbb-voice/src/main/java/org/red5/app/sip/SdpUtils.java
thong-hoczita/bigbluebutton
612b294e89e708eddb150d4dc7b17349bce21ef5
[ "MIT" ]
null
null
null
bbb-voice/src/main/java/org/red5/app/sip/SdpUtils.java
thong-hoczita/bigbluebutton
612b294e89e708eddb150d4dc7b17349bce21ef5
[ "MIT" ]
null
null
null
bbb-voice/src/main/java/org/red5/app/sip/SdpUtils.java
thong-hoczita/bigbluebutton
612b294e89e708eddb150d4dc7b17349bce21ef5
[ "MIT" ]
null
null
null
52.44403
143
0.510957
4,012
package org.red5.app.sip; import java.util.Enumeration; import java.util.Vector; import org.red5.app.sip.codecs.Codec; import org.red5.app.sip.codecs.CodecFactory; import org.zoolu.sdp.AttributeField; import org.zoolu.sdp.MediaDescriptor; import org.zoolu.sdp.MediaField; import org.zoolu.sdp.SessionDescriptor; import org.slf4j.Logger; import org.red5.logging.Red5LoggerFactory; public class SdpUtils { protected static Logger log = Red5LoggerFactory.getLogger(SdpUtils.class, "sip"); /** * @return Returns the audio codec to be used on current session. */ public static Codec getNegotiatedAudioCodec(SessionDescriptor negotiatedSDP){ int payloadId; String rtpmap; Codec sipCodec = null; MediaDescriptor md = negotiatedSDP.getMediaDescriptor(Codec.MEDIA_TYPE_AUDIO ); rtpmap = md.getAttribute(Codec.ATTRIBUTE_RTPMAP).getAttributeValue(); if (!rtpmap.isEmpty()) { payloadId = Integer.parseInt(rtpmap.substring(0, rtpmap.indexOf(" "))); sipCodec = CodecFactory.getInstance().getSIPAudioCodec(payloadId); if (sipCodec == null) { log.error("Negotiated codec {} not found", payloadId); } else { log.info("Found codec: payloadType={}, payloadName={}.", sipCodec.getCodecId(), sipCodec.getCodecName()); } } return sipCodec; } /** * * @param userName * @param viaAddress * * @return Return the initial local SDP. */ public static SessionDescriptor createInitialSdp(String userName, String viaAddress, int audioPort, int videoPort, String audioCodecsPrecedence) { SessionDescriptor initialDescriptor = null; try { // log.debug("userName = [" + userName + "], viaAddress = [" + viaAddress + // "], audioPort = [" + audioPort + "], videoPort = [" + videoPort + // "], audioCodecsPrecedence = [" + audioCodecsPrecedence + "]." ); int audioCodecsNumber = CodecFactory.getInstance().getAvailableAudioCodecsCount(); int videoCodecsNumber = CodecFactory.getInstance().getAvailableVideoCodecsCount(); if ((audioCodecsNumber == 0) && (videoCodecsNumber == 0)) { log.debug("audioCodecsNumber = [" + audioCodecsNumber + "], videoCodecsNumber = [" + videoCodecsNumber + "]."); return null; } initialDescriptor = new SessionDescriptor(userName, viaAddress); if (initialDescriptor == null) { log.error("Error instantiating the initialDescriptor!"); return null; } if (audioCodecsNumber > 0) { Codec[] audioCodecs; Vector audioAttributes = new Vector(); if (audioCodecsPrecedence.isEmpty()) { audioCodecs = CodecFactory.getInstance().getAvailableAudioCodecs(); } else { audioCodecs = CodecFactory.getInstance().getAvailableAudioCodecsWithPrecedence(audioCodecsPrecedence); } for (int audioIndex = 0; audioIndex < audioCodecsNumber; audioIndex++) { String payloadId = String.valueOf(audioCodecs[audioIndex].getCodecId()); String rtpmapParamValue = payloadId; rtpmapParamValue += " " + audioCodecs[audioIndex].getCodecName(); rtpmapParamValue += "/" + audioCodecs[audioIndex].getSampleRate() + "/1"; // log.debug("Adding rtpmap for payload [" + payloadId + // "] with value = [" + rtpmapParamValue + "]." ); audioAttributes.add(new AttributeField(Codec.ATTRIBUTE_RTPMAP, rtpmapParamValue)); String[] codecMediaAttributes = audioCodecs[audioIndex].getCodecMediaAttributes(); if (codecMediaAttributes != null) { // log.debug("Adding " + codecMediaAttributes.length + // " audio codec media attributes." ); for (int attribIndex = 0; attribIndex < codecMediaAttributes.length; attribIndex++) { // log.debug("Adding audio media attribute [" + // codecMediaAttributes[attribIndex] + "]." ); AttributeField newAttribute = parseAttributeField(codecMediaAttributes[attribIndex]); if (newAttribute != null) { audioAttributes.add(newAttribute); } } } else { log.warn("Audio codec has no especific media attributes." ); } } // Calculate the format list to be used on MediaDescriptor creation. String formatList = getFormatList(audioAttributes); for (Enumeration attributesEnum = audioAttributes.elements(); attributesEnum.hasMoreElements();) { AttributeField audioAttribute = (AttributeField) attributesEnum.nextElement(); if (initialDescriptor.getMediaDescriptor(Codec.MEDIA_TYPE_AUDIO) == null) { // log.debug("Creating audio media descriptor." ); MediaField mf = new MediaField(Codec.MEDIA_TYPE_AUDIO, audioPort, 0, "RTP/AVP", formatList); initialDescriptor.addMedia(mf, audioAttribute); } else { // log.debug("Just adding attribute."); initialDescriptor.getMediaDescriptor(Codec.MEDIA_TYPE_AUDIO).addAttribute(audioAttribute); } } String[] commonAudioMediaAttributes = CodecFactory.getInstance().getCommonAudioMediaAttributes(); if (commonAudioMediaAttributes != null) { // log.debug("Adding " + commonAudioMediaAttributes.length + " common audio media attributes." ); for (int attribIndex = 0; attribIndex < commonAudioMediaAttributes.length; attribIndex++) { // log.debug("Adding common audio media attribute [" + commonAudioMediaAttributes[attribIndex] + "]."); AttributeField newAttribute = parseAttributeField(commonAudioMediaAttributes[attribIndex]); if (newAttribute != null) { initialDescriptor.getMediaDescriptor(Codec.MEDIA_TYPE_AUDIO).addAttribute( newAttribute); } } } else { log.debug("No common audio media attributes."); } } if (videoCodecsNumber > 0) { Codec[] videoCodecs = CodecFactory.getInstance().getAvailableVideoCodecs(); Vector videoAttributes = new Vector(); for (int videoIndex = 0; videoIndex < audioCodecsNumber; videoIndex++) { String payloadId = String.valueOf(videoCodecs[videoIndex].getCodecId()); String rtpmapParamValue = payloadId; rtpmapParamValue += " " + videoCodecs[videoIndex].getCodecName(); rtpmapParamValue += "/" + videoCodecs[videoIndex].getSampleRate() + "/1"; // log.debug("Adding rtpmap for payload [" + payloadId + "] with value = [" + rtpmapParamValue + "]."); videoAttributes.add(new AttributeField(Codec.ATTRIBUTE_RTPMAP, rtpmapParamValue)); String[] codecMediaAttributes = videoCodecs[videoIndex].getCodecMediaAttributes(); if (codecMediaAttributes != null) { // log.debug("Adding " + codecMediaAttributes.length + " video codec media attributes."); for (int attribIndex = 0; attribIndex < codecMediaAttributes.length; attribIndex++) { // log.debug("Adding video media attribute [" + codecMediaAttributes[attribIndex] + "]."); AttributeField newAttribute = parseAttributeField(codecMediaAttributes[attribIndex]); if (newAttribute != null) { videoAttributes.add(newAttribute); } } } else { log.info("Video codec has no especific media attributes."); } } // Calculate the format list to be used on MediaDescriptor creation. String formatList = getFormatList(videoAttributes); for (Enumeration attributesEnum = videoAttributes.elements(); attributesEnum.hasMoreElements();) { AttributeField videoAttribute = (AttributeField) attributesEnum.nextElement(); if (initialDescriptor.getMediaDescriptor(Codec.MEDIA_TYPE_VIDEO) == null) { MediaField mf = new MediaField(Codec.MEDIA_TYPE_VIDEO, audioPort, 0, "RTP/AVP", formatList); initialDescriptor.addMedia(mf, videoAttribute); } else { initialDescriptor.getMediaDescriptor(Codec.MEDIA_TYPE_VIDEO).addAttribute(videoAttribute); } } String[] commonVideoMediaAttributes = CodecFactory.getInstance().getCommonAudioMediaAttributes(); if (commonVideoMediaAttributes != null) { // log.debug("Adding " + commonVideoMediaAttributes.length + " common video media attributes."); for (int attribIndex = 0; attribIndex < commonVideoMediaAttributes.length; attribIndex++) { // log.debug("Adding common video media attribute [" + commonVideoMediaAttributes[attribIndex] + "]." ); AttributeField newAttribute = parseAttributeField(commonVideoMediaAttributes[attribIndex]); if (newAttribute != null) { initialDescriptor.getMediaDescriptor(Codec.MEDIA_TYPE_VIDEO).addAttribute(newAttribute); } } } else { log.info("No common video media attributes."); } } } catch (Exception exception) { log.error("Failure creating initial SDP: " + exception.toString()); } // log.debug("Created initial SDP"); return initialDescriptor; } private static String getFormatList(Vector mediaAttributes) { AttributeField mediaAttribute = null; String formatList = ""; // log.debug("getting Format List"); for (Enumeration attributeEnum = mediaAttributes.elements(); attributeEnum.hasMoreElements();) { mediaAttribute = (AttributeField) attributeEnum.nextElement(); if (mediaAttribute.getAttributeName().equalsIgnoreCase(Codec.ATTRIBUTE_RTPMAP)) { if (!formatList.isEmpty()) { formatList += " "; } formatList += getPayloadIdFromAttribute(mediaAttribute); } } // log.debug("formatList = [" + formatList + "]."); return formatList; } private static AttributeField parseAttributeField(String codecMediaAttribute) { AttributeField newAttribute = null; // log.debug("codecMediaAttribute = [" + codecMediaAttribute + "]."); String attribName = codecMediaAttribute.substring(0, codecMediaAttribute.indexOf(":")); String attribValue = codecMediaAttribute.substring(codecMediaAttribute.indexOf(":") + 1); // log.debug("attribName = [" + attribName + "] attribValue = [" + attribValue + "]."); if ((!attribName.isEmpty()) && (!attribValue.isEmpty())) { newAttribute = new AttributeField(attribName, attribValue); } return newAttribute; } /** * We must validate the existence of all remote "rtpmap" attributes * on local SDP. * If some exist, we add it to newSdp negotiated SDP result. * * @param localSdp * @param remoteSdp * * @return Returns the new local descriptor as a result of media * payloads negotiation. */ public static SessionDescriptor makeMediaPayloadsNegotiation(SessionDescriptor localSdp, SessionDescriptor remoteSdp) { log.debug("makeMediaPayloadsNegotiation"); SessionDescriptor newSdp = null; try { newSdp = new SessionDescriptor(remoteSdp.getOrigin(), remoteSdp.getSessionName(), localSdp.getConnection(), localSdp.getTime()); Vector remoteDescriptors = remoteSdp.getMediaDescriptors(); for (Enumeration descriptorsEnum = remoteDescriptors.elements(); descriptorsEnum.hasMoreElements();) { MediaDescriptor remoteDescriptor = (MediaDescriptor) descriptorsEnum.nextElement(); MediaDescriptor localDescriptor = localSdp.getMediaDescriptor(remoteDescriptor.getMedia().getMedia() ); if (localDescriptor != null) { Vector remoteAttributes = remoteDescriptor.getAttributes(Codec.ATTRIBUTE_RTPMAP); Vector newSdpAttributes = new Vector(); for (Enumeration attributesEnum = remoteAttributes.elements(); attributesEnum.hasMoreElements();) { AttributeField remoteAttribute = (AttributeField) attributesEnum.nextElement(); String payloadId = getPayloadIdFromAttribute(remoteAttribute); if ("".equals(payloadId)) { log.error("Payload id not found on attribute: Name = [" + remoteAttribute.getAttributeName() + "], Value = [" + remoteAttribute.getAttributeValue() + "]." ); } else if (findAttributeByPayloadId(remoteAttribute.getAttributeName(), payloadId, localDescriptor) != null) { newSdpAttributes.add(remoteAttribute); } } // Calculate the format list to be used on MediaDescriptor creation. String formatList = getFormatList(newSdpAttributes); for (Enumeration attributesEnum = newSdpAttributes.elements(); attributesEnum.hasMoreElements();) { AttributeField mediaAttribute = (AttributeField) attributesEnum.nextElement(); if (newSdp.getMediaDescriptors().size() == 0) { MediaField mf = new MediaField(localDescriptor.getMedia().getMedia(), localDescriptor.getMedia().getPort(), 0, localDescriptor.getMedia().getTransport(), formatList); newSdp.addMediaDescriptor(new MediaDescriptor(mf, localDescriptor.getConnection())); } newSdp.getMediaDescriptor(localDescriptor.getMedia().getMedia()).addAttribute( mediaAttribute ); } } } } catch (Exception exception) { log.error("Failure creating initial SDP: " + exception.toString()); } return newSdp; } /** * Parameter "newSdp" must be the returning value from method's * "makeMediaPayloadsNegotiation" execution. * Here the pending attributes will be negotiated as well. * * @param newSdp * @param localSdp * @param remoteSdp * */ public static void completeSdpNegotiation(SessionDescriptor newSdp, SessionDescriptor localSdp, SessionDescriptor remoteSdp) { try { if (newSdp.getMediaDescriptors().size() == 0) { // Something is wrong. // We should have at least a "audio" media descriptor with // all audio payloads suported. log.error("No media descriptors after \"makeMediaPayloadsNegotiation\"." ); return; } Vector remoteDescriptors = remoteSdp.getMediaDescriptors(); for (Enumeration descriptorsEnum = remoteDescriptors.elements(); descriptorsEnum.hasMoreElements();) { MediaDescriptor remoteDescriptor = (MediaDescriptor) descriptorsEnum.nextElement(); MediaDescriptor localDescriptor = localSdp.getMediaDescriptor(remoteDescriptor.getMedia().getMedia()); if (localDescriptor != null) { // First we make the negotiation of remote attributes with // local ones to generate the new SDP "newSdp". Vector remoteAttributes = remoteDescriptor.getAttributes(); for (Enumeration atributesEnum = remoteAttributes.elements(); atributesEnum.hasMoreElements();) { AttributeField remoteAttribute = (AttributeField) atributesEnum.nextElement(); makeAttributeNegotiation(newSdp, localDescriptor, remoteAttribute); } // Now we add to "newSdp" all the local attributes that // were not negotiated yet. Vector localAttributes = localDescriptor.getAttributes(); for (Enumeration atributesEnum = localAttributes.elements(); atributesEnum.hasMoreElements();) { AttributeField localAttribute = (AttributeField) atributesEnum.nextElement(); MediaDescriptor newLocalDescriptor = newSdp.getMediaDescriptor(localDescriptor.getMedia().getMedia()); if (isPayloadRelatedAttribute(localAttribute)) { String payloadId = getPayloadIdFromAttribute(localAttribute); if (findAttributeByPayloadId(localAttribute.getAttributeName(), payloadId, newLocalDescriptor) == null) { newLocalDescriptor.addAttribute(localAttribute); } } else if (newLocalDescriptor.getAttribute(localAttribute.getAttributeName()) == null) { newLocalDescriptor.addAttribute(localAttribute); } } } } } catch (Exception exception) { log.error("Failure creating initial SDP: " + exception.toString()); } } /** * Here we make the negotiation of all attributes besides "rtpmap" ( * these are negotiated on "makeMediaPayloadsNegotiation" method). * * @param newSdp * @param localMedia * @param remoteAttribute */ private static void makeAttributeNegotiation(SessionDescriptor newSdp, MediaDescriptor localMedia, AttributeField remoteAttribute ) { try { // log.debug("AttributeName = [" + remoteAttribute.getAttributeName() + // "], AttributeValue = [" + remoteAttribute.getAttributeValue() + "]."); if (remoteAttribute.getAttributeName().equals(Codec.ATTRIBUTE_RTPMAP)) { log.info("\"rtpmap\" attributes were already negotiated." ); } else if (!isPayloadRelatedAttribute(remoteAttribute)) { // We do nothing with attributes that are not payload // related, like: "ptime", "direction", etc. // For now, we consider that they don't demand negotiation. log.info("Attribute is not payload related. Do not negotiate it..."); } else { String payloadId = getPayloadIdFromAttribute(remoteAttribute); if ("".equals(payloadId)) { log.error("Payload id not found on attribute: Name = [" + remoteAttribute.getAttributeName() + "], Value = [" + remoteAttribute.getAttributeValue() + "]." ); } else if (findAttributeByPayloadId( Codec.ATTRIBUTE_RTPMAP, payloadId, newSdp.getMediaDescriptor(localMedia.getMedia().getMedia())) != null) { // We must be sure this attribute is related with a payload // already present on newSdp. // log.debug("Payload " + payloadId + " present on newSdp."); AttributeField localAttribute = findAttributeByPayloadId(remoteAttribute.getAttributeName(), payloadId, localMedia ); Codec sipCodec = CodecFactory.getInstance().getSIPAudioCodec(Integer.valueOf( payloadId)); if (sipCodec != null) { String localAttibuteValue = ""; if (localAttribute != null) { localAttibuteValue = localAttribute.getAttributeValue(); } else { log.info("Attribute not found on local media."); } String attributeValueResult = sipCodec.codecNegotiateAttribute(remoteAttribute.getAttributeName(), localAttibuteValue, remoteAttribute.getAttributeValue()); if ((attributeValueResult != null) && (!"".equals(attributeValueResult))) { AttributeField af = new AttributeField(remoteAttribute.getAttributeName(), attributeValueResult); MediaDescriptor md = newSdp.getMediaDescriptor(localMedia.getMedia().getMedia()); md.addAttribute(af); } } else { log.warn("Codec not found!"); } } } } catch (Exception exception) { log.error("Failure creating initial SDP: " + exception.toString()); } } private static AttributeField findAttributeByPayloadId(String attributeName, String payloadId, MediaDescriptor mediaDescriptor) { AttributeField searchingMediaAttribute = null; // log.debug("attributeName = [" + attributeName + "], payloadId = [" + payloadId + "]."); Vector mediaAttributes = mediaDescriptor.getAttributes( attributeName ); for (Enumeration attributesEnum = mediaAttributes.elements(); attributesEnum.hasMoreElements();) { AttributeField mediaAttribute = (AttributeField) attributesEnum.nextElement(); // log.debug("Validating attribute with name = [" + mediaAttribute.getAttributeName() + // "] and value = [" + mediaAttribute.getAttributeValue() + "]."); if (getPayloadIdFromAttribute(mediaAttribute).equals(payloadId)) { searchingMediaAttribute = mediaAttribute; break; } } if (searchingMediaAttribute != null) { // log.debug("Attribute found with name = [" + // searchingMediaAttribute.getAttributeName() + "] and value = [" + // searchingMediaAttribute.getAttributeValue() + "]." ); } else { // log.info("Attribute with name [" + attributeName + "] and payloadId [" + payloadId + "] was not found." ); } return searchingMediaAttribute; } private static String getPayloadIdFromAttribute(AttributeField attribute) { String payloadId = ""; // log.debug("AttributeName = [" + attribute.getAttributeName() + "], AttributeValue = [" + attribute.getAttributeValue() + "]." ); if (isPayloadRelatedAttribute(attribute)) { payloadId = attribute.getAttributeValue().substring(0, attribute.getAttributeValue().indexOf(" ")); } // log.debug("payloadId = " + payloadId); return payloadId; } private static boolean isPayloadRelatedAttribute(AttributeField attribute) { boolean isPayloadAttribute = false; // log.debug("AttributeName = [" + attribute.getAttributeName() + "], AttributeValue = [" + attribute.getAttributeValue() + "]." ); if ((attribute.getAttributeName().compareToIgnoreCase(Codec.ATTRIBUTE_RTPMAP) == 0) || (attribute.getAttributeName().compareToIgnoreCase(Codec.ATTRIBUTE_AS) == 0) || (attribute.getAttributeName().compareToIgnoreCase(Codec.ATTRIBUTE_FMTP) == 0)) { isPayloadAttribute = true; } // log.debug("isPayloadAttribute = " + isPayloadAttribute); return isPayloadAttribute; } }
3e0986832a0db33b1429d8219292d5f9ccebcb17
422
java
Java
shared/src/main/java/edu/kit/ss17/chatsys/team1/shared/Roster/RosterObserverInterface.java
Noone-404/eXmessage
ece61af3d8deebcb8241385dc4b61aca2ca30c2f
[ "MIT" ]
null
null
null
shared/src/main/java/edu/kit/ss17/chatsys/team1/shared/Roster/RosterObserverInterface.java
Noone-404/eXmessage
ece61af3d8deebcb8241385dc4b61aca2ca30c2f
[ "MIT" ]
null
null
null
shared/src/main/java/edu/kit/ss17/chatsys/team1/shared/Roster/RosterObserverInterface.java
Noone-404/eXmessage
ece61af3d8deebcb8241385dc4b61aca2ca30c2f
[ "MIT" ]
1
2021-05-19T14:21:08.000Z
2021-05-19T14:21:08.000Z
24.823529
78
0.817536
4,013
package edu.kit.ss17.chatsys.team1.shared.Roster; import edu.kit.ss17.chatsys.team1.shared.Util.DesignHelpers.ObserverInterface; /** * */ public interface RosterObserverInterface extends ObserverInterface { void contactCreated(RosterInterface roster, ContactInterface contact); void contactRemoved(RosterInterface roster, ContactInterface contact); default void observerRegistered(RosterInterface roster) { } }
3e0987031c77cb868ba12a726182eb8e01a83611
3,267
java
Java
src/test/java/org/assertj/core/internal/strings/Strings_assertEndsWith_Test.java
glhez/assertj-core
d3e70030999cb3aaa090b9797d00892fcae57896
[ "Apache-2.0" ]
1,607
2015-01-06T13:35:38.000Z
2020-09-22T08:20:41.000Z
src/test/java/org/assertj/core/internal/strings/Strings_assertEndsWith_Test.java
glhez/assertj-core
d3e70030999cb3aaa090b9797d00892fcae57896
[ "Apache-2.0" ]
1,604
2015-01-01T04:10:21.000Z
2020-09-22T10:09:26.000Z
src/test/java/org/assertj/core/internal/strings/Strings_assertEndsWith_Test.java
glhez/assertj-core
d3e70030999cb3aaa090b9797d00892fcae57896
[ "Apache-2.0" ]
523
2015-01-07T16:57:54.000Z
2020-09-20T03:01:39.000Z
44.148649
157
0.734619
4,014
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2022 the original author or authors. */ package org.assertj.core.internal.strings; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatNullPointerException; import static org.assertj.core.error.ShouldEndWith.shouldEndWith; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.util.FailureMessages.actualIsNull; import org.assertj.core.api.AssertionInfo; import org.assertj.core.internal.Strings; import org.assertj.core.internal.StringsBaseTest; import org.junit.jupiter.api.Test; /** * Tests for <code>{@link Strings#assertEndsWith(AssertionInfo, CharSequence, CharSequence)}</code>. * * @author Alex Ruiz * @author Joel Costigliola */ class Strings_assertEndsWith_Test extends StringsBaseTest { @Test void should_fail_if_actual_does_not_end_with_suffix() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertEndsWith(someInfo(), "Yoda", "Luke")) .withMessage(shouldEndWith("Yoda", "Luke").create()); } @Test void should_throw_error_if_suffix_is_null() { assertThatNullPointerException().isThrownBy(() -> strings.assertEndsWith(someInfo(), "Yoda", null)) .withMessage("The given suffix should not be null"); } @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertEndsWith(someInfo(), null, "Yoda")) .withMessage(actualIsNull()); } @Test void should_pass_if_actual_ends_with_suffix() { strings.assertEndsWith(someInfo(), "Yoda", "oda"); } @Test void should_pass_if_actual_ends_with_suffix_according_to_custom_comparison_strategy() { stringsWithCaseInsensitiveComparisonStrategy.assertEndsWith(someInfo(), "Yoda", "oda"); stringsWithCaseInsensitiveComparisonStrategy.assertEndsWith(someInfo(), "Yoda", "da"); stringsWithCaseInsensitiveComparisonStrategy.assertEndsWith(someInfo(), "Yoda", "a"); stringsWithCaseInsensitiveComparisonStrategy.assertEndsWith(someInfo(), "Yoda", "Oda"); stringsWithCaseInsensitiveComparisonStrategy.assertEndsWith(someInfo(), "Yoda", "ODA"); } @Test void should_fail_if_actual_does_not_end_with_suffix_according_to_custom_comparison_strategy() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> stringsWithCaseInsensitiveComparisonStrategy.assertEndsWith(someInfo(), "Yoda", "Luke")) .withMessage(shouldEndWith("Yoda", "Luke", comparisonStrategy).create()); } }
3e098766a58165b3ec4594d14e5342c9d9ac269f
12,070
java
Java
components/camel-http/src/test/java/org/apache/camel/component/http/HttpDefaultPortNumberTest.java
dmgerman/camel
cab53c57b3e58871df1f96d54b2a2ad5a73ce220
[ "Apache-2.0" ]
null
null
null
components/camel-http/src/test/java/org/apache/camel/component/http/HttpDefaultPortNumberTest.java
dmgerman/camel
cab53c57b3e58871df1f96d54b2a2ad5a73ce220
[ "Apache-2.0" ]
23
2021-03-23T00:01:38.000Z
2022-01-04T16:47:34.000Z
components/camel-http/src/test/java/org/apache/camel/component/http/HttpDefaultPortNumberTest.java
dmgerman/camel
cab53c57b3e58871df1f96d54b2a2ad5a73ce220
[ "Apache-2.0" ]
null
null
null
15.594315
810
0.803728
4,015
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 DECL|package|org.apache.camel.component.http package|package name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|http package|; end_package begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|Exchange import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|builder operator|. name|RouteBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|http operator|. name|handler operator|. name|BasicValidationHandler import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|http operator|. name|conn operator|. name|HttpHostConnectException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|http operator|. name|impl operator|. name|bootstrap operator|. name|HttpServer import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|http operator|. name|impl operator|. name|bootstrap operator|. name|ServerBootstrap import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|After import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Before import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Ignore import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_class annotation|@ name|Ignore argument_list|( literal|"We cannot run this test as default port 80 is not allows on most boxes" argument_list|) DECL|class|HttpDefaultPortNumberTest specifier|public class|class name|HttpDefaultPortNumberTest extends|extends name|BaseHttpTest block|{ DECL|field|localServer specifier|private name|HttpServer name|localServer decl_stmt|; annotation|@ name|Before annotation|@ name|Override DECL|method|setUp () specifier|public name|void name|setUp parameter_list|() throws|throws name|Exception block|{ name|localServer operator|= name|ServerBootstrap operator|. name|bootstrap argument_list|() operator|. name|setHttpProcessor argument_list|( name|getBasicHttpProcessor argument_list|() argument_list|) operator|. name|setConnectionReuseStrategy argument_list|( name|getConnectionReuseStrategy argument_list|() argument_list|) operator|. name|setResponseFactory argument_list|( name|getHttpResponseFactory argument_list|() argument_list|) operator|. name|setExpectationVerifier argument_list|( name|getHttpExpectationVerifier argument_list|() argument_list|) operator|. name|setSslContext argument_list|( name|getSSLContext argument_list|() argument_list|) operator|. name|registerHandler argument_list|( literal|"/search" argument_list|, operator|new name|BasicValidationHandler argument_list|( literal|"GET" argument_list|, literal|null argument_list|, literal|null argument_list|, name|getExpectedContent argument_list|() argument_list|) argument_list|) operator|. name|create argument_list|() expr_stmt|; name|localServer operator|. name|start argument_list|() expr_stmt|; name|super operator|. name|setUp argument_list|() expr_stmt|; block|} annotation|@ name|After annotation|@ name|Override DECL|method|tearDown () specifier|public name|void name|tearDown parameter_list|() throws|throws name|Exception block|{ name|super operator|. name|tearDown argument_list|() expr_stmt|; if|if condition|( name|localServer operator|!= literal|null condition|) block|{ name|localServer operator|. name|stop argument_list|() expr_stmt|; block|} block|} annotation|@ name|Test DECL|method|testHttpConnectionWithTwoRoutesAndOneWithDefaultPort () specifier|public name|void name|testHttpConnectionWithTwoRoutesAndOneWithDefaultPort parameter_list|() throws|throws name|Exception block|{ name|context operator|. name|addRoutes argument_list|( operator|new name|RouteBuilder argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|configure parameter_list|() throws|throws name|Exception block|{ name|from argument_list|( literal|"direct:start" argument_list|) operator|. name|to argument_list|( literal|"http://" operator|+ name|localServer operator|. name|getInetAddress argument_list|() operator|. name|getHostName argument_list|() operator|+ literal|"/search" argument_list|) expr_stmt|; name|from argument_list|( literal|"direct:dummy" argument_list|) operator|. name|to argument_list|( literal|"http://" operator|+ name|localServer operator|. name|getInetAddress argument_list|() operator|. name|getHostName argument_list|() operator|+ literal|":" operator|+ name|localServer operator|. name|getLocalPort argument_list|() operator|+ literal|"/search" argument_list|) expr_stmt|; block|} block|} argument_list|) expr_stmt|; name|context operator|. name|start argument_list|() expr_stmt|; name|Exchange name|exchange init|= name|template operator|. name|request argument_list|( literal|"direct:start" argument_list|, literal|null argument_list|) decl_stmt|; comment|// note: the default portnumber will appear in the error message name|assertRefused argument_list|( name|exchange argument_list|, literal|":80" argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|testHttpConnectionWithTwoRoutesAndAllPortsSpecified () specifier|public name|void name|testHttpConnectionWithTwoRoutesAndAllPortsSpecified parameter_list|() throws|throws name|Exception block|{ name|context operator|. name|addRoutes argument_list|( operator|new name|RouteBuilder argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|configure parameter_list|() throws|throws name|Exception block|{ name|from argument_list|( literal|"direct:start" argument_list|) operator|. name|to argument_list|( literal|"http://" operator|+ name|localServer operator|. name|getInetAddress argument_list|() operator|. name|getHostName argument_list|() operator|+ literal|":80/search" argument_list|) expr_stmt|; name|from argument_list|( literal|"direct:dummy" argument_list|) operator|. name|to argument_list|( literal|"http://" operator|+ name|localServer operator|. name|getInetAddress argument_list|() operator|. name|getHostName argument_list|() operator|+ literal|":" operator|+ name|localServer operator|. name|getLocalPort argument_list|() operator|+ literal|"/search" argument_list|) expr_stmt|; block|} block|} argument_list|) expr_stmt|; name|context operator|. name|start argument_list|() expr_stmt|; name|Exchange name|exchange init|= name|template operator|. name|request argument_list|( literal|"direct:start" argument_list|, literal|null argument_list|) decl_stmt|; comment|//specifying the defaultportnumber helps name|assertRefused argument_list|( name|exchange argument_list|, literal|":80" argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|testHttpConnectionRefusedStoppedServer () specifier|public name|void name|testHttpConnectionRefusedStoppedServer parameter_list|() throws|throws name|Exception block|{ name|context operator|. name|addRoutes argument_list|( operator|new name|RouteBuilder argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|configure parameter_list|() throws|throws name|Exception block|{ name|from argument_list|( literal|"direct:start" argument_list|) operator|. name|to argument_list|( literal|"http://" operator|+ name|localServer operator|. name|getInetAddress argument_list|() operator|. name|getHostName argument_list|() operator|+ literal|"/search" argument_list|) expr_stmt|; name|from argument_list|( literal|"direct:dummy" argument_list|) operator|. name|to argument_list|( literal|"http://" operator|+ name|localServer operator|. name|getInetAddress argument_list|() operator|. name|getHostName argument_list|() operator|+ literal|":" operator|+ name|localServer operator|. name|getLocalPort argument_list|() operator|+ literal|"/search" argument_list|) expr_stmt|; block|} block|} argument_list|) expr_stmt|; name|context operator|. name|start argument_list|() expr_stmt|; name|localServer operator|. name|stop argument_list|() expr_stmt|; name|Exchange name|exchange init|= name|template operator|. name|request argument_list|( literal|"direct:start" argument_list|, literal|null argument_list|) decl_stmt|; name|assertRefused argument_list|( name|exchange argument_list|, literal|":80" argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|testHttpConnectionRefusedRunningServer () specifier|public name|void name|testHttpConnectionRefusedRunningServer parameter_list|() throws|throws name|Exception block|{ name|context operator|. name|addRoutes argument_list|( operator|new name|RouteBuilder argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|configure parameter_list|() throws|throws name|Exception block|{ name|from argument_list|( literal|"direct:start" argument_list|) operator|. name|to argument_list|( literal|"http://" operator|+ name|localServer operator|. name|getInetAddress argument_list|() operator|. name|getHostName argument_list|() operator|+ literal|"/search" argument_list|) expr_stmt|; block|} block|} argument_list|) expr_stmt|; name|context operator|. name|start argument_list|() expr_stmt|; comment|//server is runnning, but connecting to other port name|Exchange name|exchange init|= name|template operator|. name|request argument_list|( literal|"direct:start" argument_list|, literal|null argument_list|) decl_stmt|; name|assertRefused argument_list|( name|exchange argument_list|, literal|":80" argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|isUseRouteBuilder () specifier|public name|boolean name|isUseRouteBuilder parameter_list|() block|{ return|return literal|true return|; block|} DECL|method|assertRefused (Exchange exchange, String portExt) specifier|private name|void name|assertRefused parameter_list|( name|Exchange name|exchange parameter_list|, name|String name|portExt parameter_list|) block|{ name|Map argument_list|< name|String argument_list|, name|Object argument_list|> name|headers init|= name|exchange operator|. name|getOut argument_list|() operator|. name|getHeaders argument_list|() decl_stmt|; comment|//no http response: name|assertNull argument_list|( name|headers operator|. name|get argument_list|( name|Exchange operator|. name|HTTP_RESPONSE_CODE argument_list|) argument_list|) expr_stmt|; comment|//and got an exception: name|assertIsInstanceOf argument_list|( name|HttpHostConnectException operator|. name|class argument_list|, name|exchange operator|. name|getException argument_list|() argument_list|) expr_stmt|; comment|//with message: name|assertEquals argument_list|( literal|"Connection to http://127.0.0.1" operator|+ name|portExt operator|+ literal|" refused" argument_list|, name|exchange operator|. name|getException argument_list|() operator|. name|getMessage argument_list|() argument_list|) expr_stmt|; block|} block|} end_class end_unit
3e09888564980e5ca539502431d873e270aec2c2
473
java
Java
src/com/amydegregorio/javabasics/exceptionhandling/RuntimeExceptionExample.java
amdegregorio/JavaBasics-ExceptionHandling
c2b37486f79691da4bf1d5f555cab8dcc3dfd46d
[ "Apache-2.0" ]
null
null
null
src/com/amydegregorio/javabasics/exceptionhandling/RuntimeExceptionExample.java
amdegregorio/JavaBasics-ExceptionHandling
c2b37486f79691da4bf1d5f555cab8dcc3dfd46d
[ "Apache-2.0" ]
null
null
null
src/com/amydegregorio/javabasics/exceptionhandling/RuntimeExceptionExample.java
amdegregorio/JavaBasics-ExceptionHandling
c2b37486f79691da4bf1d5f555cab8dcc3dfd46d
[ "Apache-2.0" ]
null
null
null
16.310345
72
0.564482
4,016
/** * */ package com.amydegregorio.javabasics.exceptionhandling; /** * @author AMD * */ public class RuntimeExceptionExample { /** * @param args */ public static void main(String[] args) { //Divide by 0 int dividend = 14; int divisor = 0; try { int quotient = dividend / divisor; } catch (ArithmeticException ae) { System.err.println("Arithmetic Exception: " + ae.getMessage()); } } }
3e0988d5af21a44dfaf4aef142cd06f81eb95266
7,275
java
Java
external/cling/core/src/test/java/example/controlpoint/SwitchPowerWithInterruption.java
goyourfly/NovaCustom
c55265060a84b7b5b1f4b42ae096370205c66ad7
[ "Apache-2.0" ]
null
null
null
external/cling/core/src/test/java/example/controlpoint/SwitchPowerWithInterruption.java
goyourfly/NovaCustom
c55265060a84b7b5b1f4b42ae096370205c66ad7
[ "Apache-2.0" ]
null
null
null
external/cling/core/src/test/java/example/controlpoint/SwitchPowerWithInterruption.java
goyourfly/NovaCustom
c55265060a84b7b5b1f4b42ae096370205c66ad7
[ "Apache-2.0" ]
null
null
null
38.289474
120
0.705155
4,017
/* * Copyright (C) 2013 4th Line GmbH, Switzerland * * The contents of this file are subject to the terms of either the GNU * Lesser General Public License Version 2 or later ("LGPL") or the * Common Development and Distribution License Version 1 or later * ("CDDL") (collectively, the "License"). You may not use this file * except in compliance with the License. See LICENSE.txt for more * information. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package example.controlpoint; import org.fourthline.cling.binding.annotations.UpnpAction; import org.fourthline.cling.binding.annotations.UpnpInputArgument; import org.fourthline.cling.binding.annotations.UpnpOutputArgument; import org.fourthline.cling.binding.annotations.UpnpService; import org.fourthline.cling.binding.annotations.UpnpServiceId; import org.fourthline.cling.binding.annotations.UpnpServiceType; import org.fourthline.cling.binding.annotations.UpnpStateVariable; import org.fourthline.cling.model.profile.RemoteClientInfo; /** * Reacting to cancellation on the server * <p> * By default, an action method of your service will run until it completes, it either returns or throws an exception. * If you have to perform long-running tasks in a service, your action method can avoid doing unnecessary work by * checking if processing should continue. Think about processing in batches: You work for a while, then you check if * you should continue, then you work some more, check again, and so on. * </p> * <p> * There are two checks you have to perform: * </p> * <ul> * <li> * If a local control point called your service, and meanwhile cancelled the action call, the thread running your action * method will have its interruption flag set. When you see this flag you can stop processing, as any result of your * action method will be ignored anyway. * </li> * <li> * If a remote control point called your service, it might have dropped the connection while you were processing data * to return. Unfortunately, checking if the client's connection is still open requires, on a TCP level, writing data * on the socket. This is essentially a heartbeat signal: Every time you check if the client is still there, a byte of * (hopefully) insignificant data will be send to the client. If there wasn't any error sending data, the connection * is still alive. * </li> * </ul> * <p> * These checks look as follows in your service method: * </p> * <a class="citation" * href="javacode://this" * style="include: ACTION_METHOD; exclude: ACTUAL_WORK;"/> * * <p> * You abort processing by throwing an <code>InterruptedException</code>, Cling will do the rest. Cling will send * a heartbeat to the client whenever you check if the remote request was cancelled with the optional * <code>RemoteClientInfo</code>, see <a href="#javadoc.example.localservice.RemoteClientInfoTest">this section</a>. * </p> * <p> * <em>Danger:</em> Not all HTTP clients can deal with Cling's heartbeat signal. Not even all bundled * <code>StreamClient</code>'s of Cling can handle such a signal. You should only use this feature if you are sure that * all clients of your service will ignore the meaningless heartbeat signal. Cling sends a space character (this is * configurable) to the HTTP client to check the connection. Hence, the HTTP client sees a response such as * '[space][space][space]HTTP/1.0', with a space character for each alive check. If your HTTP client does not trim those * space characters before parsing the response, it will fail processing your otherwise valid response. * </p> * <p> * The following Cling-bundled client transports can deal with a heartbeat signal: * </p> * <table class="infotable fullwidth" border="1"> * <thead> * <tr> * <th>Transport</th> * <th class="thirdwidth">Accepts Heartbeat?</th> * </tr> * </thead> * <tbody> * <tr> * <td class="nowrap"> * <code>org.fourthline.cling.transport.impl.StreamClientImpl (default)</code> * </td> * <td>NO</td> * </tr> * <tr> * <td class="nowrap"> * <code>org.fourthline.cling.transport.impl.apache.StreamClientImpl</code> * </td> * <td>YES</td> * </tr> * <tr> * <td class="nowrap"> * <code>org.fourthline.cling.transport.impl.jetty.StreamClientImpl (default on Android)</code> * </td> * <td>YES</td> * </tr> * </tbody> * </table> * <p> * Equally important, not all server transports in Cling can send heartbeat signals, as low-level socket access is * required. Some server APIs do not provide this low-level access. If you check the connection state with those * transports, the connection is always "alive": * </p> * <table class="infotable fullwidth" border="1"> * <thead> * <tr> * <th>Transport</th> * <th class="thirdwidth">Sends Heartbeat?</th> * </tr> * </thead> * <tbody> * <tr> * <td class="nowrap"> * <code>org.fourthline.cling.transport.impl.StreamServerImpl (default)</code> * </td> * <td>NO</td> * </tr> * <tr> * <td class="nowrap"> * <code>org.fourthline.cling.transport.impl.apache.StreamServerImpl</code> * </td> * <td>YES</td> * </tr> * <tr> * <td class="nowrap"> * <code>org.fourthline.cling.transport.impl.AsyncServletStreamServerImpl</code><br/> * with <code>org.fourthline.cling.transport.impl.jetty.JettyServletContainer (default on Android)</code> * </td> * <td>YES</td> * </tr> * </tbody> * </table> * <p> * In practice, this heartbeat feature is less useful than it sounds in theory: As you usually don't control which HTTP * clients will access your server, sending them "garbage" bytes before responding properly will most likely cause * interoperability problems. * </p> */ @UpnpService( serviceId = @UpnpServiceId("SwitchPower"), serviceType = @UpnpServiceType(value = "SwitchPower", version = 1) ) public class SwitchPowerWithInterruption { @UpnpStateVariable(sendEvents = false) private boolean target = false; @UpnpStateVariable private boolean status = false; // DOC:ACTION_METHOD @UpnpAction public void setTarget(@UpnpInputArgument(name = "NewTargetValue") boolean newTargetValue, RemoteClientInfo remoteClientInfo) throws InterruptedException { // DOC:ACTUAL_WORK target = newTargetValue; status = newTargetValue; // DOC:ACTUAL_WORK boolean interrupted = false; while (!interrupted) { // Do some long-running work and periodically test if you should continue... // ... for local service invocation if (Thread.interrupted()) interrupted = true; // ... for remote service invocation if (remoteClientInfo != null && remoteClientInfo.isRequestCancelled()) interrupted = true; } throw new InterruptedException("Execution interrupted"); } // DOC:ACTION_METHOD @UpnpAction(out = @UpnpOutputArgument(name = "RetTargetValue")) public boolean getTarget() { return target; } @UpnpAction(out = @UpnpOutputArgument(name = "ResultStatus")) public boolean getStatus() { return status; } }