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
3e0eabd92b1a5bf4ad683d10071dbad5c2550f42
195
java
Java
app/src/main/java/au/gov/dva/sopapi/interfaces/model/FactorReference.java
govlawtech/dva-sop-api
202575d7c0e15eb99aa95a73377030576ea2335c
[ "Apache-2.0" ]
6
2017-02-03T02:44:43.000Z
2018-07-29T10:56:20.000Z
app/src/main/java/au/gov/dva/sopapi/interfaces/model/FactorReference.java
govlawtech/dva-sop-api
202575d7c0e15eb99aa95a73377030576ea2335c
[ "Apache-2.0" ]
35
2016-12-01T21:21:57.000Z
2021-07-27T23:26:41.000Z
app/src/main/java/au/gov/dva/sopapi/interfaces/model/FactorReference.java
govlawtech/dva-sop-api
202575d7c0e15eb99aa95a73377030576ea2335c
[ "Apache-2.0" ]
2
2017-03-14T08:07:54.000Z
2017-03-28T00:27:45.000Z
19.5
46
0.779487
6,228
package au.gov.dva.sopapi.interfaces.model; import java.util.Optional; public interface FactorReference { String getMainFactorReference(); Optional<String> getFactorPartReference(); }
3e0eac3d82dd6ff681594be90fb3fd1ee133eb8f
6,353
java
Java
src/main/java/fr/ippon/tatami/repository/cassandra/CassandraAttachmentRepository.java
ptemplier/tatami
8356fbed8e762b8aa1cd23630ed2dedf840eb22b
[ "Apache-2.0" ]
null
null
null
src/main/java/fr/ippon/tatami/repository/cassandra/CassandraAttachmentRepository.java
ptemplier/tatami
8356fbed8e762b8aa1cd23630ed2dedf840eb22b
[ "Apache-2.0" ]
null
null
null
src/main/java/fr/ippon/tatami/repository/cassandra/CassandraAttachmentRepository.java
ptemplier/tatami
8356fbed8e762b8aa1cd23630ed2dedf840eb22b
[ "Apache-2.0" ]
null
null
null
38.97546
106
0.65717
6,229
package fr.ippon.tatami.repository.cassandra; import fr.ippon.tatami.domain.Attachment; import fr.ippon.tatami.repository.AttachmentRepository; import me.prettyprint.cassandra.serializers.BytesArraySerializer; import me.prettyprint.cassandra.serializers.DateSerializer; import me.prettyprint.cassandra.serializers.LongSerializer; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.cassandra.utils.TimeUUIDUtils; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.ColumnQuery; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Repository; import javax.inject.Inject; import java.util.Date; import static fr.ippon.tatami.config.ColumnFamilyKeys.ATTACHMENT_CF; @Repository public class CassandraAttachmentRepository implements AttachmentRepository { private final Log log = LogFactory.getLog(CassandraAttachmentRepository.class); private final String CONTENT = "content"; private final String FILENAME = "filename"; private final String SIZE = "size"; private final String CREATION_DATE = "creation_date"; @Inject private Keyspace keyspaceOperator; @Override public void createAttachment(Attachment attachment) { String attachmentId = TimeUUIDUtils.getUniqueTimeUUIDinMillis().toString(); if (log.isDebugEnabled()) { log.debug("Creating attachment : " + attachment); } attachment.setAttachmentId(attachmentId); Mutator<String> mutator = HFactory.createMutator(keyspaceOperator, StringSerializer.get()); mutator.insert(attachmentId, ATTACHMENT_CF, HFactory.createColumn(CONTENT, attachment.getContent(), StringSerializer.get(), BytesArraySerializer.get())); mutator.insert(attachmentId, ATTACHMENT_CF, HFactory.createColumn(FILENAME, attachment.getFilename(), StringSerializer.get(), StringSerializer.get())); mutator.insert(attachmentId, ATTACHMENT_CF, HFactory.createColumn(SIZE, attachment.getSize(), StringSerializer.get(), LongSerializer.get())); mutator.insert(attachmentId, ATTACHMENT_CF, HFactory.createColumn(CREATION_DATE, attachment.getCreationDate(), StringSerializer.get(), DateSerializer.get())); } @Override @CacheEvict(value = "attachment-cache", key = "#attachment.attachmentId") public void deleteAttachment(Attachment attachment) { if (log.isDebugEnabled()) { log.debug("Deleting attachment : " + attachment); } Mutator<String> mutator = HFactory.createMutator(keyspaceOperator, StringSerializer.get()); mutator.addDeletion(attachment.getAttachmentId(), ATTACHMENT_CF); mutator.execute(); } @Override @Cacheable("attachment-cache") public Attachment findAttachmentById(String attachmentId) { if (attachmentId == null) { return null; } if (log.isDebugEnabled()) { log.debug("Finding attachment : " + attachmentId); } Attachment attachment = this.findAttachmentMetadataById(attachmentId); if (attachment == null) { return null; } ColumnQuery<String, String, byte[]> queryAttachment = HFactory.createColumnQuery(keyspaceOperator, StringSerializer.get(), StringSerializer.get(), BytesArraySerializer.get()); HColumn<String, byte[]> columnAttachment = queryAttachment.setColumnFamily(ATTACHMENT_CF) .setKey(attachmentId) .setName(CONTENT) .execute() .get(); attachment.setContent(columnAttachment.getValue()); return attachment; } @Override public Attachment findAttachmentMetadataById(String attachmentId) { if (attachmentId == null) { return null; } Attachment attachment = new Attachment(); attachment.setAttachmentId(attachmentId); ColumnQuery<String, String, String> queryFilename = HFactory.createColumnQuery(keyspaceOperator, StringSerializer.get(), StringSerializer.get(), StringSerializer.get()); HColumn<String, String> columnFilename = queryFilename.setColumnFamily(ATTACHMENT_CF) .setKey(attachmentId) .setName(FILENAME) .execute() .get(); if (columnFilename != null && columnFilename.getValue() != null) { attachment.setFilename(columnFilename.getValue()); } else { return null; } ColumnQuery<String, String, Long> querySize = HFactory.createColumnQuery(keyspaceOperator, StringSerializer.get(), StringSerializer.get(), LongSerializer.get()); HColumn<String, Long> columnSize = querySize.setColumnFamily(ATTACHMENT_CF) .setKey(attachmentId) .setName(SIZE) .execute() .get(); if (columnSize != null && columnSize.getValue() != null) { attachment.setSize(columnSize.getValue()); } else { return null; } ColumnQuery<String, String, Date> queryCreationDate = HFactory.createColumnQuery(keyspaceOperator, StringSerializer.get(), StringSerializer.get(), DateSerializer.get()); HColumn<String, Date> columnCreationDate = queryCreationDate.setColumnFamily(ATTACHMENT_CF) .setKey(attachmentId) .setName(CREATION_DATE) .execute() .get(); if (columnCreationDate != null && columnCreationDate.getValue() != null) { attachment.setCreationDate(columnCreationDate.getValue()); } else { attachment.setCreationDate(new Date()); } return attachment; } }
3e0ead770176c617fd86a51188eb2086c5980cde
2,124
java
Java
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/plugin-use/org/gradle/plugin/use/resolve/internal/ClassPathPluginResolution.java
bit-man/pushfish-android
5f4fcf56adf5a8cdb6f31d91c315bcd3b3dc93bc
[ "BSD-2-Clause" ]
158
2015-04-18T23:39:02.000Z
2021-07-01T18:28:29.000Z
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/plugin-use/org/gradle/plugin/use/resolve/internal/ClassPathPluginResolution.java
bit-man/pushfish-android
5f4fcf56adf5a8cdb6f31d91c315bcd3b3dc93bc
[ "BSD-2-Clause" ]
31
2015-04-29T18:52:40.000Z
2020-06-29T19:25:24.000Z
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/plugin-use/org/gradle/plugin/use/resolve/internal/ClassPathPluginResolution.java
bit-man/pushfish-android
5f4fcf56adf5a8cdb6f31d91c315bcd3b3dc93bc
[ "BSD-2-Clause" ]
32
2016-01-05T21:58:24.000Z
2021-06-21T21:56:34.000Z
38.618182
156
0.75565
6,230
/* * Copyright 2013 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.gradle.plugin.use.resolve.internal; import org.gradle.api.Plugin; import org.gradle.api.internal.initialization.ClassLoaderScope; import org.gradle.api.internal.plugins.DefaultPluginRegistry; import org.gradle.api.internal.plugins.PluginRegistry; import org.gradle.internal.Factory; import org.gradle.internal.classpath.ClassPath; import org.gradle.internal.reflect.Instantiator; import org.gradle.plugin.internal.PluginId; public class ClassPathPluginResolution implements PluginResolution { private final PluginId pluginId; private final Instantiator instantiator; private final ClassLoaderScope parent; private final Factory<? extends ClassPath> classPathFactory; public ClassPathPluginResolution(Instantiator instantiator, PluginId pluginId, ClassLoaderScope parent, Factory<? extends ClassPath> classPathFactory) { this.pluginId = pluginId; this.instantiator = instantiator; this.parent = parent; this.classPathFactory = classPathFactory; } public PluginId getPluginId() { return pluginId; } public Class<? extends Plugin> resolve() { ClassPath classPath = classPathFactory.create(); ClassLoaderScope loaderScope = parent.createChild(); loaderScope.local(classPath); loaderScope.lock(); PluginRegistry pluginRegistry = new DefaultPluginRegistry(loaderScope.getLocalClassLoader(), instantiator); return pluginRegistry.getTypeForId(pluginId.toString()); } }
3e0eae4ca9bb8138e29628731c166aada2718ff7
293
java
Java
jdk/src/main/java/xyz/mydev/jdk/genericity/complex/repository/MessageRepository.java
FantasyZsp/SpringBoot2.xDemo
e468255d301f019c9f8f2198fd68ad406642b4f8
[ "Apache-2.0" ]
null
null
null
jdk/src/main/java/xyz/mydev/jdk/genericity/complex/repository/MessageRepository.java
FantasyZsp/SpringBoot2.xDemo
e468255d301f019c9f8f2198fd68ad406642b4f8
[ "Apache-2.0" ]
null
null
null
jdk/src/main/java/xyz/mydev/jdk/genericity/complex/repository/MessageRepository.java
FantasyZsp/SpringBoot2.xDemo
e468255d301f019c9f8f2198fd68ad406642b4f8
[ "Apache-2.0" ]
null
null
null
26.636364
117
0.822526
6,231
package xyz.mydev.jdk.genericity.complex.repository; import xyz.mydev.jdk.genericity.complex.msg.StringMessage; import java.time.LocalDateTime; public interface MessageRepository<T extends StringMessage> extends MessageCrudRepository<T, String, LocalDateTime> { String getTableName(); }
3e0eaf394bf772a4a6b8f89df16b60a2db44cf61
2,892
java
Java
app/src/main/java/com/akexorcist/mvpsimple/module/viewer/info/FeedInfoFragment.java
akexorcist/MVCSimple
bca1e7da12fb5fb49b272a0f556b4690cce25fd8
[ "Apache-2.0" ]
1
2016-08-27T11:16:33.000Z
2016-08-27T11:16:33.000Z
app/src/main/java/com/akexorcist/mvpsimple/module/viewer/info/FeedInfoFragment.java
akexorcist/MVCSimple
bca1e7da12fb5fb49b272a0f556b4690cce25fd8
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/akexorcist/mvpsimple/module/viewer/info/FeedInfoFragment.java
akexorcist/MVCSimple
bca1e7da12fb5fb49b272a0f556b4690cce25fd8
[ "Apache-2.0" ]
2
2016-10-07T04:04:15.000Z
2017-04-06T16:34:03.000Z
28.352941
129
0.710235
6,232
package com.akexorcist.mvpsimple.module.viewer.info; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.akexorcist.mvpsimple.R; import com.akexorcist.mvpsimple.network.model.PostList; import org.parceler.Parcels; /** * A simple {@link Fragment} subclass. */ public class FeedInfoFragment extends Fragment implements FeedInfoContractor.View { public static final String KEY_POST_ITEM = "key_post_item"; private FeedInfoContractor.Presenter presenterFeedInfoContractor; private TextView tvTitle; public static FeedInfoFragment newInstance(PostList.Item postItem) { FeedInfoFragment fragment = new FeedInfoFragment(); Bundle bundle = new Bundle(); bundle.putParcelable(KEY_POST_ITEM, Parcels.wrap(postItem)); fragment.setArguments(bundle); return fragment; } public FeedInfoFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_viewer_info, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); bindView(view); setupView(); createPresenter(); if (savedInstanceState == null) { restoreArgument(getArguments()); initialize(); } else { restoreInstanceState(savedInstanceState); restoreView(); } } private void createPresenter() { FeedInfoPresenter.createPresenter(this); } private void bindView(View view) { tvTitle = (TextView) view.findViewById(R.id.tv_title); } private void setupView() { } private void restoreView() { } private void restoreInstanceState(Bundle savedInstanceState) { presenterFeedInfoContractor.setPostItem((PostList.Item) Parcels.unwrap(savedInstanceState.getParcelable(KEY_POST_ITEM))); } private void restoreArgument(Bundle bundle) { presenterFeedInfoContractor.setPostItem((PostList.Item) Parcels.unwrap(bundle.getParcelable(KEY_POST_ITEM))); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(KEY_POST_ITEM, Parcels.wrap(presenterFeedInfoContractor.getPostItem())); } private void initialize() { } @Override public void setPresenter(FeedInfoContractor.Presenter presenter) { this.presenterFeedInfoContractor = presenter; } @Override public void setFeedItemTitle(String title) { tvTitle.setText(title); } }
3e0eb013139115230b7bc036409fb2a8b23a3e9c
229
java
Java
org.opencompare/api-java/src/main/java/org/opencompare/api/java/value/BooleanValue.java
gerbaudg/op
40ddc00534325f8b594c884e01ab248fbf3e5409
[ "Apache-2.0" ]
null
null
null
org.opencompare/api-java/src/main/java/org/opencompare/api/java/value/BooleanValue.java
gerbaudg/op
40ddc00534325f8b594c884e01ab248fbf3e5409
[ "Apache-2.0" ]
null
null
null
org.opencompare/api-java/src/main/java/org/opencompare/api/java/value/BooleanValue.java
gerbaudg/op
40ddc00534325f8b594c884e01ab248fbf3e5409
[ "Apache-2.0" ]
null
null
null
19.083333
45
0.724891
6,233
package org.opencompare.api.java.value; import org.opencompare.api.java.Value; /** * Created by gbecan on 09/10/14. */ public interface BooleanValue extends Value { boolean getValue(); void setValue(boolean value); }
3e0eb02f161747a770f028ba36a1f217b2ba2c8e
1,290
java
Java
src/main/java/org/kettle/trans/steps/cleanse/rules/TitleCaseRule.java
nadment/pdi-cleanse
ee64772168dc2440a5004a27e0d5e5c2b7ec0a39
[ "Apache-2.0" ]
1
2020-06-19T04:09:17.000Z
2020-06-19T04:09:17.000Z
src/main/java/org/kettle/trans/steps/cleanse/rules/TitleCaseRule.java
nadment/pdi-cleanse-plugin
ee64772168dc2440a5004a27e0d5e5c2b7ec0a39
[ "Apache-2.0" ]
null
null
null
src/main/java/org/kettle/trans/steps/cleanse/rules/TitleCaseRule.java
nadment/pdi-cleanse-plugin
ee64772168dc2440a5004a27e0d5e5c2b7ec0a39
[ "Apache-2.0" ]
null
null
null
28.043478
140
0.693023
6,234
package org.kettle.trans.steps.cleanse.rules; import org.kettle.trans.steps.cleanse.CleanseRule; import org.kettle.trans.steps.cleanse.ValueProcessor; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.row.ValueMetaInterface; /** * The rule capitalize the first letter of each phrase. * * @author Nicolas ADMENT * */ @CleanseRule(id = "TitleCase", name = "Title case", category = "Case", description = "The rule capitalize the first letter of each phrase") public class TitleCaseRule implements ValueProcessor { @Override public Object processValue(final ValueMetaInterface valueMeta, final Object object) throws KettleValueException { if (object == null) return null; String value = valueMeta.getString(object); if (value.length() == 0) { return value; } StringBuilder result = new StringBuilder(value.length()); char last = '.'; result.append(Character.toUpperCase(last)); for (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); if (Character.getType(last) == Character.END_PUNCTUATION) { result.append(Character.toTitleCase(ch)); } else { result.append(Character.toLowerCase(ch)); } last = ch; } return result.toString(); } }
3e0eb0afe59dae14656eba98ccaf1218a76199d0
3,600
java
Java
corpus/class/eclipse.jdt.core/521.java
masud-technope/ACER-Replication-Package-ASE2017
cb7318a729eb1403004d451a164c851af2d81f7a
[ "MIT" ]
15
2018-07-10T09:38:31.000Z
2021-11-29T08:28:07.000Z
corpus/class/eclipse.jdt.core/521.java
masud-technope/ACER-Replication-Package-ASE2017
cb7318a729eb1403004d451a164c851af2d81f7a
[ "MIT" ]
3
2018-11-16T02:58:59.000Z
2021-01-20T16:03:51.000Z
corpus/class/eclipse.jdt.core/521.java
masud-technope/ACER-Replication-Package-ASE2017
cb7318a729eb1403004d451a164c851af2d81f7a
[ "MIT" ]
6
2018-06-27T20:19:00.000Z
2022-02-19T02:29:53.000Z
31.304348
102
0.669167
6,235
/******************************************************************************* * Copyright (c) 2013, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.core.dom; import java.util.List; /** * Abstract base class of all AST node types that represent a method reference * expression (added in JLS8 API). * * <pre> * MethodReference: * CreationReference * ExpressionMethodReference * SuperMethodReference * TypeMethodReference * </pre> * <p> * A method reference that is represented by a simple or qualified name, * followed by <code>::</code>, followed by a simple name can be represented * as {@link ExpressionMethodReference} or as {@link TypeMethodReference}. * The ASTParser currently prefers the first form. * </p> * * @see CreationReference * @see ExpressionMethodReference * @see SuperMethodReference * @see TypeMethodReference * @since 3.10 */ @SuppressWarnings({ "rawtypes" }) public abstract class MethodReference extends Expression { /** * The type arguments (element type: {@link Type}). * Defaults to an empty list (see constructor). */ ASTNode.NodeList typeArguments; /** * Creates and returns a structural property descriptor for the "typeArguments" * property declared on the given concrete node type (element type: {@link Type}). * * @return the property descriptor */ static final ChildListPropertyDescriptor internalTypeArgumentsFactory(Class nodeClass) { //$NON-NLS-1$ return new ChildListPropertyDescriptor(nodeClass, "typeArguments", Type.class, NO_CYCLE_RISK); } /** * Returns the structural property descriptor for the "typeArguments" property * of this node (element type: {@link Type}). * * @return the property descriptor */ abstract ChildListPropertyDescriptor internalTypeArgumentsProperty(); /** * Returns the structural property descriptor for the "typeArguments" property * of this node (element type: {@link Type}). * * @return the property descriptor */ public final ChildListPropertyDescriptor getTypeArgumentsProperty() { return internalTypeArgumentsProperty(); } /** * Creates a new AST node for a method reference owned by the given AST. * <p> * N.B. This constructor is package-private. * </p> * * @param ast the AST that is to own this node */ MethodReference(AST ast) { super(ast); this.typeArguments = new ASTNode.NodeList(getTypeArgumentsProperty()); } /** * Returns the live ordered list of type arguments of this method reference. * * @return the live list of type arguments * (element type: {@link Type}) */ public List typeArguments() { return this.typeArguments; } /** * Resolves and returns the binding for the method referenced by this * method reference expression. * <p> * Note that bindings are generally unavailable unless requested when the * AST is being built. * </p> * * @return the method binding, or <code>null</code> if the binding cannot * be resolved */ public IMethodBinding resolveMethodBinding() { return this.ast.getBindingResolver().resolveMethod(this); } }
3e0eb304b1c31765cc9b784890fcd4ec0f8e9b9f
12,618
java
Java
Vacuum Game/A1soln/src/game/VacuumGame.java
Synergy182/Vacuum-Game
084104ca7023bc593c42288ad45ab523b9544295
[ "MIT" ]
null
null
null
Vacuum Game/A1soln/src/game/VacuumGame.java
Synergy182/Vacuum-Game
084104ca7023bc593c42288ad45ab523b9544295
[ "MIT" ]
null
null
null
Vacuum Game/A1soln/src/game/VacuumGame.java
Synergy182/Vacuum-Game
084104ca7023bc593c42288ad45ab523b9544295
[ "MIT" ]
null
null
null
31.078818
93
0.664685
6,236
package game; import sprites.CleanHallway; import sprites.Dumpster; import sprites.Dust; import sprites.DustBall; import sprites.Sprite; import sprites.Vacuum; import sprites.Wall; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Scanner; /** * A class that represents the basic functionality of the vacuum game. * This class is responsible for performing the following operations: * 1. At creation, it initializes the instance variables used to store the * current state of the game. * 2. When a move is specified, it checks if it is a legal move and makes the * move if it is legal. * 3. It reports information about the current state of the game when asked. */ /** * @author siddh * */ public class VacuumGame { private Random random; // a random number generator to move the DustBalls private Grid<Sprite> grid; // the grid private Vacuum vacuum1; // the first player private Vacuum vacuum2; // the second player private List<Dust> dusts; // the dusts private List<DustBall> dustBalls; // the dust balls /** * Creates a new <code>VacuumGame</code> that corresponds to the given input * text file. Assumes that the input file has one or more lines of equal * lengths, and that each character in it (other than newline) is a * character that represents one of the <code>Sprite</code>s in this game. * Uses gridType to implement the grid. * * @param layoutFileName * path to the input grid file * @param gridType * the type of grid implementation to use */ public VacuumGame(String layoutFileName, Constants.GridType gridType) throws IOException { dusts = new ArrayList<>(); dustBalls = new ArrayList<>(); random = new Random(); // open the file, read the contents, and determine dimensions of the // grid int[] dimensions = getDimensions(layoutFileName); int numRows = dimensions[0]; int numColumns = dimensions[1]; if (gridType.equals(Constants.GridType.LIST_GRID)) { grid = new ListGrid<>(numRows, numColumns); } else { grid = new MapGrid<>(numRows, numColumns); } // open the file again, read the contents, and store them in grid Scanner sc = new Scanner(new File(layoutFileName)); for (int row = 0; row < numRows; row++) { String nextLine = sc.nextLine(); /******** * Initialize the grid ********/ // Loop over each line by column for (int col = 0; col < numColumns; col++) { char chr; // Get the character at the given index chr = nextLine.charAt(col); // Set the grid.setCell(row, col, charToSprite(chr, row, col)); } } sc.close(); } /********* * Lots of methods ************/ /** * Return the number of Rows in the grid * * @return the number of Rows in the grid */ public int getNumRows() { return grid.getNumRows(); } /** * Return the number of Columns in the grid * * @return the number of Columns in the grid */ public int getNumColumns() { return grid.getNumColumns(); } /** * Return the Sprite at the given row and column * * @param row the row at which Sprite is located * @param column the column at which Sprite is located * @return the Sprite at the given row and column */ public Sprite getSprite(int row, int column) { return grid.getCell(row, column); } /** * Return the grid * * @return the grid */ public Grid<Sprite> getGrid() { return grid; } /** * Return vacuum 1 * * @return vacuum 1 */ public Vacuum getVacuumOne() { return vacuum1; } /** * Return vacuum 2 * * @return vacuum 2 */ public Vacuum getVacuumTwo() { return vacuum2; } /** * This method will check if the move is valid If the given move is valid * then move the vacuum to the given location based on movement of player * * @param nextMove get the given move */ public void move(char nextMove) { if (nextMove == Constants.P1_LEFT) { Sprite spr = grid.getCell(vacuum1.getRow(), vacuum1.getColumn() + Constants.LEFT); if (spr.getSymbol() != Constants.WALL) { if (spr.getSymbol() != Constants.P2) { Sprite oldspr = vacuum1.getUnder(); vacuum1.setUnder(grid.getCell(vacuum1.getRow(), vacuum1.getColumn() + Constants.LEFT)); grid.setCell(vacuum1.getRow(), vacuum1.getColumn(), oldspr); grid.setCell(vacuum1.getRow(), vacuum1.getColumn() + Constants.LEFT, vacuum1); vacuum1.moveTo(vacuum1.getRow(), vacuum1.getColumn() + Constants.LEFT); validP1Move(spr); } } } else if (nextMove == Constants.P1_RIGHT) { Sprite spr = grid.getCell(vacuum1.getRow(), vacuum1.getColumn() + Constants.RIGHT); if (spr.getSymbol() != Constants.WALL) { if (spr.getSymbol() != Constants.P2) { Sprite oldspr = vacuum1.getUnder(); vacuum1.setUnder(grid.getCell(vacuum1.getRow(), vacuum1.getColumn() + Constants.RIGHT)); grid.setCell(vacuum1.getRow(), vacuum1.getColumn(), oldspr); grid.setCell(vacuum1.getRow(), vacuum1.getColumn() + Constants.RIGHT, vacuum1); vacuum1.moveTo(vacuum1.getRow(), vacuum1.getColumn() + Constants.RIGHT); validP1Move(spr); } } } else if (nextMove == Constants.P1_DOWN) { Sprite spr = grid.getCell(vacuum1.getRow() + Constants.DOWN, vacuum1.getColumn()); if (spr.getSymbol() != Constants.WALL) { if (spr.getSymbol() != Constants.P2) { Sprite oldspr = vacuum1.getUnder(); vacuum1.setUnder(grid.getCell(vacuum1.getRow() + Constants.DOWN, vacuum1.getColumn())); grid.setCell(vacuum1.getRow(), vacuum1.getColumn(), oldspr); grid.setCell(vacuum1.getRow() + Constants.DOWN, vacuum1.getColumn(), vacuum1); vacuum1.moveTo(vacuum1.getRow() + Constants.DOWN, vacuum1.getColumn()); validP1Move(spr); } } } else if (nextMove == Constants.P1_UP) { Sprite spr = grid.getCell(vacuum1.getRow() + Constants.UP, vacuum1.getColumn()); if (spr.getSymbol() != Constants.WALL) { if (spr.getSymbol() != Constants.P2) { Sprite oldspr = vacuum1.getUnder(); vacuum1.setUnder(grid.getCell(vacuum1.getRow() + Constants.UP, vacuum1.getColumn())); grid.setCell(vacuum1.getRow(), vacuum1.getColumn(), oldspr); grid.setCell(vacuum1.getRow() + Constants.UP, vacuum1.getColumn(), vacuum1); vacuum1.moveTo(vacuum1.getRow() + Constants.UP, vacuum1.getColumn()); validP1Move(spr); } } } else if (nextMove == Constants.P2_LEFT) { Sprite spr = grid.getCell(vacuum2.getRow(), vacuum2.getColumn() + Constants.LEFT); if (spr.getSymbol() != Constants.WALL) { if (spr.getSymbol() != Constants.P1) { Sprite oldspr = vacuum2.getUnder(); vacuum2.setUnder(grid.getCell(vacuum2.getRow(), vacuum2.getColumn() + Constants.LEFT)); grid.setCell(vacuum2.getRow(), vacuum2.getColumn(), oldspr); grid.setCell(vacuum2.getRow(), vacuum2.getColumn() + Constants.LEFT, vacuum2); vacuum2.moveTo(vacuum2.getRow(), vacuum2.getColumn() + Constants.LEFT); validP2Move(spr); } } } else if (nextMove == Constants.P2_RIGHT) { Sprite spr = grid.getCell(vacuum2.getRow(), vacuum2.getColumn() + Constants.RIGHT); if (spr.getSymbol() != Constants.WALL) { if (spr.getSymbol() != Constants.P1) { Sprite oldspr = vacuum2.getUnder(); vacuum2.setUnder(grid.getCell(vacuum2.getRow(), vacuum2.getColumn() + Constants.RIGHT)); grid.setCell(vacuum2.getRow(), vacuum2.getColumn(), oldspr); grid.setCell(vacuum2.getRow(), vacuum2.getColumn() + Constants.RIGHT, vacuum2); vacuum2.moveTo(vacuum2.getRow(), vacuum2.getColumn() + Constants.RIGHT); validP2Move(spr); } } } else if (nextMove == Constants.P2_DOWN) { Sprite spr = grid.getCell(vacuum2.getRow() + Constants.DOWN, vacuum2.getColumn()); if (spr.getSymbol() != Constants.WALL) { if (spr.getSymbol() != Constants.P1) { Sprite oldspr = vacuum2.getUnder(); vacuum2.setUnder(grid.getCell(vacuum2.getRow() + Constants.DOWN, vacuum2.getColumn())); grid.setCell(vacuum2.getRow(), vacuum2.getColumn(), oldspr); grid.setCell(vacuum2.getRow() + Constants.DOWN, vacuum2.getColumn(), vacuum2); vacuum2.moveTo(vacuum2.getRow() + Constants.DOWN, vacuum2.getColumn()); validP2Move(spr); } } } else if (nextMove == Constants.P2_UP) { Sprite spr = grid.getCell(vacuum2.getRow() + Constants.UP, vacuum2.getColumn()); if (spr.getSymbol() != Constants.WALL) { if (spr.getSymbol() != Constants.P1) { Sprite oldspr = vacuum2.getUnder(); vacuum2.setUnder(grid.getCell(vacuum2.getRow() + Constants.UP, vacuum2.getColumn())); grid.setCell(vacuum2.getRow(), vacuum2.getColumn(), oldspr); grid.setCell(vacuum2.getRow() + Constants.UP, vacuum2.getColumn(), vacuum2); vacuum2.moveTo(vacuum2.getRow() + Constants.UP, vacuum2.getColumn()); validP2Move(spr); } } } } private void validP2Move(Sprite spr) { if (spr.getSymbol() == Constants.DUMPSTER) { vacuum2.empty(); } else if (spr.getSymbol() == Constants.DUST) { if (vacuum2.clean(Constants.DUST_SCORE)) { dusts.remove(spr); } } else if (spr.getSymbol() == Constants.DUST_BALL) { if (vacuum2.clean(Constants.DUST_BALL_SCORE)) { dustBalls.remove(spr); } } } private void validP1Move(Sprite spr) { if (spr.getSymbol() == Constants.DUMPSTER) { vacuum1.empty(); } else if (spr.getSymbol() == Constants.DUST) { if (vacuum1.clean(Constants.DUST_SCORE)) { dusts.remove(spr); } } else if (spr.getSymbol() == Constants.DUST_BALL) { if (vacuum1.clean(Constants.DUST_BALL_SCORE)) { dustBalls.remove(spr); } } } /** * Return true if all the dirt has been cleaned, so game is finished * * @return true if all the dirt has been cleaned, so game is finished */ public boolean gameOver() { boolean gamefinished = false; // We know game is over when there is no more Dirt in our game if (dusts.isEmpty() && dustBalls.isEmpty()) { gamefinished = true; } return gamefinished; } /** * Return the winner of the game * * @return the winner of the game */ public char getWinner() { char winner; // Check who has the highest score and return the winner if (vacuum1.getScore() > vacuum2.getScore()) { winner = Constants.P1; } else if (vacuum2.getScore() > vacuum1.getScore()) { winner = Constants.P2; } // If both players have same score else { winner = Constants.TIE; } return winner; } /** * Returns the Sprite after taking it's symbol and index values. * * @param symbol * the Sprite that we want to generate from * @param row * the row value of symbol * @param column * the column value of symbol * @return a Sprite */ private Sprite charToSprite(char symbol, int row, int column) { Sprite spr; // Create Sprite Wall if (symbol == Constants.WALL) { spr = new Wall(row, column); } // Create Sprite CleanHallway else if (symbol == Constants.CLEAN) { spr = new CleanHallway(row, column); } // Create Sprite Player 1 else if (symbol == Constants.P1) { spr = new Vacuum(symbol, row, column, Constants.CAPACITY); vacuum1 = (Vacuum) spr; } // Create Sprite Player 2 else if (symbol == Constants.P2) { spr = new Vacuum(symbol, row, column, Constants.CAPACITY); vacuum2 = (Vacuum) spr; } // Create Sprite Dumpster else if (symbol == Constants.DUMPSTER) { spr = new Dumpster(row, column); } // Create Sprite Dust else if (symbol == Constants.DUST) { spr = new Dust(row, column, Constants.DUST_SCORE); dusts.add((Dust) spr); } // Otherwise create Sprite DustBall else { spr = new DustBall(row, column, Constants.DUST_BALL_SCORE); dustBalls.add((DustBall) spr); } return spr; } /** * Returns the dimensions of the grid in the file named layoutFileName. * * @param layoutFileName * path of the input grid file * @return an array [numRows, numCols], where numRows is the number of rows * and numCols is the number of columns in the grid that corresponds * to the given input grid file * @throws IOException * if cannot open file layoutFileName */ private int[] getDimensions(String layoutFileName) throws IOException { Scanner sc = new Scanner(new File(layoutFileName)); // find the number of columns String nextLine = sc.nextLine(); int numCols = nextLine.length(); // find the number of rows int numRows = 1; while (sc.hasNext()) { numRows++; nextLine = sc.nextLine(); } sc.close(); return new int[] { numRows, numCols }; } }
3e0eb37f76879b5e3dd04e6434a8dbc64460cd1a
2,715
java
Java
examples/src/test/java/com/pholser/junit/quickcheck/examples/func/EitherGenerator.java
LALAYANG/junit-quickcheck
14cb34602fb1b970a96d165f43a2739c79a1ef25
[ "MIT" ]
813
2015-01-02T10:35:01.000Z
2022-03-18T09:45:36.000Z
examples/src/test/java/com/pholser/junit/quickcheck/examples/func/EitherGenerator.java
LALAYANG/junit-quickcheck
14cb34602fb1b970a96d165f43a2739c79a1ef25
[ "MIT" ]
218
2015-01-01T14:20:40.000Z
2022-03-07T13:25:07.000Z
examples/src/test/java/com/pholser/junit/quickcheck/examples/func/EitherGenerator.java
LALAYANG/junit-quickcheck
14cb34602fb1b970a96d165f43a2739c79a1ef25
[ "MIT" ]
127
2015-01-23T01:18:26.000Z
2021-12-09T04:18:25.000Z
37.191781
79
0.713444
6,237
/* The MIT License Copyright (c) 2010-2021 Paul R. Holser, Jr. 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.pholser.junit.quickcheck.examples.func; import static com.pholser.junit.quickcheck.examples.func.Either.makeLeft; import static com.pholser.junit.quickcheck.examples.func.Either.makeRight; import static java.util.stream.Collectors.toList; import com.pholser.junit.quickcheck.generator.ComponentizedGenerator; import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import java.util.List; public class EitherGenerator extends ComponentizedGenerator<Either> { public EitherGenerator() { super(Either.class); } @Override public Either<?, ?> generate( SourceOfRandomness random, GenerationStatus status) { return random.nextBoolean() ? makeLeft(componentGenerators().get(0).generate(random, status)) : makeRight(componentGenerators().get(1).generate(random, status)); } @Override public List<Either> doShrink( SourceOfRandomness random, Either larger) { @SuppressWarnings("unchecked") Either<Object, Object> either = (Either<Object, Object>) larger; return either.map( left -> componentGenerators().get(0).shrink(random, left) .stream() .map(Either::makeLeft) .collect(toList()), right -> componentGenerators().get(1).shrink(random, right) .stream() .map(Either::makeRight) .collect(toList())); } @Override public int numberOfNeededComponents() { return 2; } }
3e0eb3945a90d0a05c777030ae4847a3dc288db7
1,203
java
Java
src/main/java/models/standard/blackjack/Hand.java
grrilla/card-practice
38c7a8cfba51ed04a9bd82e55e83d57e791d3f5d
[ "MIT" ]
null
null
null
src/main/java/models/standard/blackjack/Hand.java
grrilla/card-practice
38c7a8cfba51ed04a9bd82e55e83d57e791d3f5d
[ "MIT" ]
null
null
null
src/main/java/models/standard/blackjack/Hand.java
grrilla/card-practice
38c7a8cfba51ed04a9bd82e55e83d57e791d3f5d
[ "MIT" ]
1
2019-05-09T15:19:02.000Z
2019-05-09T15:19:02.000Z
22.277778
67
0.709061
6,238
package models.standard.blackjack; import models.standard.StandardPlayingCard; import models.standard.StandardPlayingCard.StandardRank; import java.util.ArrayList; import java.util.List; import static java.lang.Math.min; import static models.standard.StandardPlayingCard.StandardRank.ACE; public class Hand { private static final int ACE_LOW_VALUE = 1; private static final int ACE_HIGH_VALUE = 11; private static final int FACE_CARD_VALUE = 10; private int lowValue; private int highValue; private List<StandardPlayingCard> cards = new ArrayList<>(); public int getLowValue() { return lowValue; } public int getHighValue() { return highValue; } public List<StandardPlayingCard> getCards() { return cards; } public void addCard(StandardPlayingCard card) { cards.add(card); updateHandValuation(card.getRank()); } private void updateHandValuation(StandardRank rank) { if (rank == ACE) { lowValue += ACE_LOW_VALUE; highValue += ACE_HIGH_VALUE; } else { int value = min(FACE_CARD_VALUE, rank.getValue()); lowValue += value; highValue += value; } } public int size() { return cards.size(); } }
3e0eb3c617733be9412a8de1e286a99def0f0108
6,452
java
Java
RobotCore/src/main/java/com/qualcomm/robotcore/hardware/Blinker.java
cybots5975/cybots2018
082db31bdf9987c05a15d5c1fc8cf6c1bac33412
[ "MIT" ]
2
2018-11-02T19:03:00.000Z
2021-12-10T03:51:41.000Z
RobotCore/src/main/java/com/qualcomm/robotcore/hardware/Blinker.java
cybots5975/cybots2018
082db31bdf9987c05a15d5c1fc8cf6c1bac33412
[ "MIT" ]
null
null
null
RobotCore/src/main/java/com/qualcomm/robotcore/hardware/Blinker.java
cybots5975/cybots2018
082db31bdf9987c05a15d5c1fc8cf6c1bac33412
[ "MIT" ]
null
null
null
34.502674
107
0.57672
6,239
/* Copyright (c) 2016 Robert Atkinson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Robert Atkinson nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESSFOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.qualcomm.robotcore.hardware; import android.graphics.Color; import android.support.annotation.ColorInt; import java.util.Collection; import java.util.concurrent.TimeUnit; /** * {@link Blinker} provides the means to control an LED or a light that can be illuminated in a * sequenced pattern of colors and durations. */ @SuppressWarnings("WeakerAccess") public interface Blinker { /** * Sets the pattern with which this LED or light should illuminate. If the list of steps is longer * than the maximum number supported, then the pattern is truncated. * * @param steps the pattern of colors and durations that the LED or light should illuminate itself with */ void setPattern(Collection<Step> steps); /** * Returns the current blinking pattern * * @return the current blinking pattern */ Collection<Step> getPattern(); /** * Saves the existing pattern such that it can be later restored, then calls setPattern(). * * @param steps the new pattern to be displayed */ void pushPattern(Collection<Step> steps); /** * Returns whether the pattern stack is currently nonempty. * * @return whether the pattern stack is currently nonempty. */ boolean patternStackNotEmpty(); /** * Pops the next pattern off of the stack of saved patterns, if any. * If the stack is empty, then this sets the blinker to a constant black. * * @return whether or not a pattern was removed from the stack (ie: whether * the pattern stack was not empty prior to the call */ boolean popPattern(); /** * Sets the blinker pattern to be a single, unchanging color * * @param color the color with which the LED or light should be illuminated */ void setConstant(@ColorInt int color); /** * Sets the blinker to constant black and frees any internal resources */ void stopBlinking(); /** * Returns the maximum number of {@link Step}s that can be present in a pattern * * @return the maximum number of {@link Step}s that can be present in a pattern */ int getBlinkerPatternMaxLength(); /** * {@link Step} represents a particular color held for a particular length of time. */ class Step { //------------------------------------------------------------------------------------------ // State //------------------------------------------------------------------------------------------ protected @ColorInt int color = 0; protected int msDuration = 0; //------------------------------------------------------------------------------------------ // Construction //------------------------------------------------------------------------------------------ public Step() { } public Step(@ColorInt int color, long duration, TimeUnit unit) { this.color = color & 0xFFFFFF; // strip alpha so that equals() is robust setDuration(duration, unit); } public static Step nullStep() { return new Step(); } //------------------------------------------------------------------------------------------ // Comparing //------------------------------------------------------------------------------------------ @Override public boolean equals(Object them) { if (them instanceof Step) { return this.equals((Step) them); } return false; } public boolean equals(Step step) { return this.color == step.color && this.msDuration == step.msDuration; } @Override public int hashCode() { return ((this.color << 5) | this.msDuration) ^ 0x2EDA /*arbitrary*/; } //------------------------------------------------------------------------------------------ // Accessing //------------------------------------------------------------------------------------------ public boolean isLit() { return Color.red(color) != 0 || Color.green(color) != 0 || Color.blue(color) != 0; } public void setLit(boolean isEnabled) { setColor(isEnabled ? Color.WHITE : Color.BLACK); } public @ColorInt int getColor() { return color; } public void setColor(@ColorInt int color) { this.color = color; } public int getDurationMs() { return msDuration; } public void setDuration(long duration, TimeUnit unit) { this.msDuration = (int) unit.toMillis(duration); } } }
3e0eb4217c836759cb37bcbe668ce569b60cc4ad
8,177
java
Java
src/main/java/com/supervisor/sdk/pgsql/PgBaseScheme.java
my-supervisor/my-supervisor
ba6ecc4a3373cd439586a72a8e9fc035b09a3f2b
[ "CC-BY-3.0" ]
3
2022-01-31T20:40:22.000Z
2022-02-11T04:15:44.000Z
src/main/java/com/supervisor/sdk/pgsql/PgBaseScheme.java
my-supervisor/my-supervisor
ba6ecc4a3373cd439586a72a8e9fc035b09a3f2b
[ "CC-BY-3.0" ]
33
2022-01-31T20:40:16.000Z
2022-02-21T01:57:51.000Z
src/main/java/com/supervisor/sdk/pgsql/PgBaseScheme.java
my-supervisor/my-supervisor
ba6ecc4a3373cd439586a72a8e9fc035b09a3f2b
[ "CC-BY-3.0" ]
null
null
null
29.413669
136
0.693408
6,240
package com.supervisor.sdk.pgsql; import com.google.common.base.CaseFormat; import com.supervisor.sdk.datasource.BaseScheme; import com.supervisor.sdk.metadata.Field; import com.supervisor.sdk.metadata.FieldMetadata; import com.supervisor.sdk.metadata.MethodReferenceUtils; import com.supervisor.sdk.metadata.Recordable; import com.supervisor.sdk.metadata.Relation; import com.supervisor.sdk.pgsql.metadata.PgFieldOfMethod; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Random; public final class PgBaseScheme implements BaseScheme { private static final Random random = new Random(); @Override public <T> String scriptOf(Class<T> clazz) throws IOException { List<FieldMetadata> fields = fieldsOf(clazz); String definition = StringUtils.EMPTY; for (FieldMetadata field : fields) { if(StringUtils.isBlank(definition)) definition = field.definitionScript(); else definition = String.format("%s, %s", definition, field.definitionScript()); } for (FieldMetadata field : fields) { String constraintScript = field.constraintScript(); if (!StringUtils.isBlank(constraintScript)) definition = String.format("%s, %s", definition, constraintScript); } definition = String.format("CREATE TABLE IF NOT EXISTS %s (%s) \r\n" + "WITH (OIDS=FALSE); \r\n" + "COMMENT ON TABLE %s IS '%s';", nameOfClazz(clazz), definition, nameOfClazz(clazz), StringEscapeUtils.escapeSql(labelOfClazz(clazz)) ); for (FieldMetadata field : fields) { String commentScript = field.commentScript(); if (!StringUtils.isBlank(commentScript)) definition = String.format("%s %s;", definition, commentScript); } return definition; } @Override public <T> FieldMetadata fieldOf(Class<T> clazz, MethodReferenceUtils.MethodRefWithoutArg<T> methodRef) throws IOException { return new PgFieldOfMethod(clazz, methodRef); } @Override public <T> FieldMetadata fieldOf(Class<T> clazz, Method m) throws IOException { return new PgFieldOfMethod(clazz, m); } public static String userNameOfClazz(Class<?> annotatedClass) { Recordable rec = annotatedClass.getAnnotation(Recordable.class); return rec.name(); } public static String nameOfClazz(Class<?> annotatedClass) { if(isPartial(annotatedClass)) return nameOfClazz(comodel(annotatedClass)); else { String name = userNameOfClazz(annotatedClass); if(name.equals("NONE")) name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, annotatedClass.getSimpleName()); return name; } } private static String labelOfClazz(Class<?> annotatedClass) { if(isPartial(annotatedClass)) return labelOfClazz(comodel(annotatedClass)); else { Recordable rec = annotatedClass.getAnnotation(Recordable.class); String label = rec.label(); if(label.equals("NONE")) label = nameOfClazz(annotatedClass); return label; } } public static String nameOfMethod(Method m) { Field rec = m.getAnnotation(Field.class); String name = rec.name(); if(name.equals("NONE")) { name = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, m.getName()); if(isForeignKey(m)) name = String.format("%s_id", name); } return name; } public static int orderOf(Method m) { Field rec = m.getAnnotation(Field.class); int order = rec.order(); if(order == -1) order = randomNumberInRange(10, 100); return order; } public static String labelOfMethod(Method m) { Field rec = m.getAnnotation(Field.class); String label = rec.label(); if(label.equals("NONE")) label = nameOfMethod(m); return label; } public static boolean isKey(Method m) { Field rec = m.getAnnotation(Field.class); return rec.isKey(); } public static boolean isAuto(Method m) { Field rec = m.getAnnotation(Field.class); return rec.isAuto(); } public static boolean isField(Method m) { return m.isAnnotationPresent(Field.class); } public static boolean isMandatory(Method m) { Field rec = m.getAnnotation(Field.class); return rec.isMandatory(); } private static boolean forceInherit(Method m) { Field rec = m.getAnnotation(Field.class); return rec.forceInherit(); } private static boolean ignore(Method m) { Field rec = m.getAnnotation(Field.class); return rec.ignore(); } private static boolean inheritFields(Class<?> clazz) { Recordable clazzR = clazz.getAnnotation(Recordable.class); return clazzR.inheritFields(); } public static boolean isForeignKey(Method m) { Field rec = m.getAnnotation(Field.class); return rec.rel() == Relation.MANY2ONE; } public static boolean hasOne2oneRelation(Class<?> clazz) { return !userNameOfClazz(clazz).equals("NONE") && hasComodel(clazz); } public static boolean isPartial(Class<?> clazz) { return userNameOfClazz(clazz).equals("NONE") && hasComodel(clazz); } public static boolean hasComodel(Class<?> clazz) { return comodel(clazz) != Object.class; } public static Class<?> comodel(Class<?> clazz) { Recordable rec = clazz.getAnnotation(Recordable.class); return rec.comodel(); } public static boolean isList(Method m) { return m.getReturnType() == List.class; } public static boolean isMap(Method m) { return m.getReturnType() == Map.class; } private static int randomNumberInRange(int min, int max) { return random.ints(min, (max + 1)).findFirst().getAsInt(); } private static List<FieldMetadata> fieldsOfClazz(Class<?> clazz, boolean own) throws IOException{ List<FieldMetadata> fields = new ArrayList<>(); Method[] methods = clazz.getMethods(); List<Method> declaredMethods = Arrays.asList(clazz.getDeclaredMethods()); for (Method method : methods) { if (isField(method)) { if(ignore(method) || method.isDefault()) continue; boolean isClassField = declaredMethods.stream() .anyMatch( c -> c.getDeclaringClass().isAssignableFrom(method.getDeclaringClass()) && c.getReturnType().isAssignableFrom(method.getReturnType()) ); boolean isClassInheritFields = inheritFields(clazz); boolean isFieldforceInherit = forceInherit(method); boolean additionnal = false; if(!isClassField && !comodel(clazz).isAssignableFrom(method.getDeclaringClass()) && (isClassInheritFields || isFieldforceInherit)) { for (Class<?> i : clazz.getInterfaces()) { if(i.isAssignableFrom(method.getDeclaringClass())) { additionnal = true; break; } } } if(isClassField || (isFieldforceInherit && !own) || (!own && isClassInheritFields && !hasComodel(clazz)) || additionnal) fields.add(new PgFieldOfMethod(clazz, method)); } } fields.sort((c1, c2) -> c1.order().compareTo(c2.order())); return fields; } @Override public <T> String nameOf(Class<T> clazz) throws IOException { return nameOfClazz(clazz); } @Override public <T> List<FieldMetadata> fieldsOf(Class<T> clazz) throws IOException { return fieldsOfClazz(clazz, false); } @Override public <T> String labelOf(Class<T> clazz) throws IOException { return labelOfClazz(clazz); } @Override public <T> String nameOf(Class<T> clazz, MethodReferenceUtils.MethodRefWithoutArg<T> methodRef) throws IOException { Method m = MethodReferenceUtils.getReferencedMethod(clazz, methodRef); return nameOfMethod(m); } @Override public <T> String labelOf(Class<T> clazz, MethodReferenceUtils.MethodRefWithoutArg<T> methodRef) throws IOException { Method m = MethodReferenceUtils.getReferencedMethod(clazz, methodRef); return labelOfMethod(m); } @Override public <T> List<FieldMetadata> ownFieldsOf(Class<T> clazz) throws IOException { return fieldsOfClazz(clazz, true); } }
3e0eb4ec011792c3ecef89063bd1f149a8ab9dc6
11,090
java
Java
raml-tester-client/src/test/java/guru/nidi/ramlproxy/CommandTest.java
nidi3/raml-tester-proxy
44bf119f9de608f6b0d7f1216b9c03d179917f58
[ "Apache-2.0" ]
10
2015-03-25T18:44:16.000Z
2022-03-22T09:06:22.000Z
raml-tester-client/src/test/java/guru/nidi/ramlproxy/CommandTest.java
nidi3/raml-tester-proxy
44bf119f9de608f6b0d7f1216b9c03d179917f58
[ "Apache-2.0" ]
25
2015-01-16T23:53:25.000Z
2015-08-24T16:28:52.000Z
raml-tester-client/src/test/java/guru/nidi/ramlproxy/CommandTest.java
nidi3/raml-tester-proxy
44bf119f9de608f6b0d7f1216b9c03d179917f58
[ "Apache-2.0" ]
2
2015-01-16T23:32:53.000Z
2022-03-22T09:06:23.000Z
40.753676
203
0.641137
6,241
/* * Copyright © 2014 Stefan Niederhauser (upchh@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 guru.nidi.ramlproxy; import com.fasterxml.jackson.databind.ObjectMapper; import guru.nidi.ramlproxy.core.RamlProxyServer; import guru.nidi.ramlproxy.core.ServerOptions; import guru.nidi.ramlproxy.core.ValidatorConfigurator; import guru.nidi.ramlproxy.data.*; import guru.nidi.ramlproxy.report.ReportSaver; import guru.nidi.ramltester.SimpleReportAggregator; import guru.nidi.ramltester.core.RamlReport; import guru.nidi.ramltester.core.Usage; import guru.nidi.ramltester.core.UsageBuilder; import guru.nidi.ramltester.core.UsageItem; import guru.nidi.ramltester.junit.ExpectedUsage; import org.apache.http.HttpResponse; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static guru.nidi.ramlproxy.CollectionUtils.*; import static guru.nidi.ramlproxy.core.Command.*; import static guru.nidi.ramlproxy.core.CommandSender.content; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.*; /** * Client ----> Proxy ----> Mock ----> Filesystem * Test commands on Mock * Test if commands satisfy RAML using Proxy */ public class CommandTest { private HttpSender mockSender = new HttpSender(8091); private HttpSender proxySender = new HttpSender(8090); private static SimpleReportAggregator aggregator = new UnclearableReportAggregator(); private static RamlProxyServer mock, proxy; @ClassRule public static ExpectedUsage expectedUsage = new ExpectedUsage(aggregator, UsageItem.ACTION, UsageItem.FORM_PARAMETER, UsageItem.REQUEST_HEADER, UsageItem.RESOURCE, UsageItem.RESPONSE_CODE, UsageItem.RESPONSE_HEADER); @Before public void init() throws Exception { proxySender.setIgnoreCommands(true); try { mockSender.contentOfGet("/@@@proxy/stop"); } catch (Exception e) { //ignore } mock = RamlProxy.startServerSync( new ServerOptions(mockSender.getPort(), null, new File(Ramls.MOCK_DIR), Ramls.SIMPLE, "http://nidi.guru/raml", new File("target"), null, true, false, 0, 0, ValidatorConfigurator.DEFAULT), new ReportSaver()); proxy = RamlProxy.startServerSync( new ServerOptions(proxySender.getPort(), mockSender.host(), Ramls.COMMAND, null), new ReportSaver(aggregator)); } @After public void end() throws Exception { try { proxySender.setIgnoreCommands(false); final ViolationDatas violations = proxySender.send(REPORTS); assertEquals(1, violations.size()); for (final ViolationData violation : violations.get("raml-proxy")) { assertTrue(violation.getRequestViolations().isEmpty()); assertTrue(violation.getResponseViolations().isEmpty()); } final UsageDatas usages = proxySender.send(USAGE); assertEquals(1, usages.size()); assertNotNull(usages.get("raml-proxy")); for (ReportSaver.ReportInfo info : proxy.getSaver().getReports("raml-proxy")) { final RamlReport report = info.getReport(); assertTrue(report.getRequestViolations() + "\n" + report.getResponseViolations(), report.isEmpty()); } } finally { mock.close(); proxy.close(); } } @Test @SuppressWarnings({"AssertEqualsBetweenInconvertibleTypes", "unchecked"}) public void reports() throws Exception { mockSender.get("v1/data?q=1"); Thread.sleep(10); final HttpResponse res = proxySender.get(REPORTS); final String content = content(res); final Map<String, List<Map<String, Object>>> resAsMap = mapped(content, Map.class); assertEquals(map("simple", list(map( "id", 0, "requestViolations", list(), "request", "GET " + mockSender.url("v1/data") + "?q=1 from 127.0.0.1", "requestHeaders", map( "Connection", list("keep-alive"), "User-Agent", ((Map) resAsMap.get("simple").get(0).get("requestHeaders")).get("User-Agent"), "Host", list("localhost:" + mockSender.getPort()), "Accept-Encoding", list("gzip,deflate")), "responseViolations", list("Response(202) is not defined on action(GET /data)"), "response", "42", "responseHeaders", map("X-meta", list("get!"))))), resAsMap); final ViolationDatas resAsData = mapped(content, ViolationDatas.class); final ViolationDatas datas = new ViolationDatas(); datas.put("simple", list(new ViolationData( 0L, "GET " + mockSender.url("v1/data") + "?q=1 from 127.0.0.1", map( "Connection", list("keep-alive"), "User-Agent", resAsData.get("simple").get(0).getRequestHeaders().get("User-Agent"), "Host", list("localhost:" + mockSender.getPort()), "Accept-Encoding", list("gzip,deflate")), list(), "42", map("X-meta", list("get!")), list("Response(202) is not defined on action(GET /data)")))); assertEquals(datas, resAsData); } @Test public void stop() throws Exception { proxySender.send(STOP); Thread.sleep(200); assertTrue(mock.isStopped()); } @Test @SuppressWarnings("AssertEqualsBetweenInconvertibleTypes") public void usage() throws Exception { mockSender.contentOfGet("v1/data?q=1"); mockSender.contentOfGet("v1/other"); Thread.sleep(10); final HttpResponse res = proxySender.get(USAGE); final String content = content(res); final Map<String, Object> resAsMap = mapped(content, Map.class); assertUsageMap("simple", map( "unusedQueryParameters", list(), "unusedRequestHeaders", list("head in GET /data"), "unusedFormParameters", list("a in POST /data (application/x-www-form-urlencoded)"), "unusedResources", list("/unused"), "unusedActions", list("GET /unused", "POST /data"), "unusedResponseCodes", list("200 in GET /data", "201 in GET /data", "201 in POST /data"), "unusedResponseHeaders", list("rh in GET /data -> 200")), resAsMap); final UsageDatas resAsUsage = mapped(content, UsageDatas.class); assertEquals(1, resAsUsage.size()); final UsageData simple = resAsUsage.get("simple"); assertThat(simple.getUnusedActions(), containsInAnyOrder("GET /unused", "POST /data")); assertThat(simple.getUnusedFormParameters(), containsInAnyOrder("a in POST /data (application/x-www-form-urlencoded)")); assertThat(simple.getUnusedQueryParameters(), containsInAnyOrder()); assertThat(simple.getUnusedRequestHeaders(), containsInAnyOrder("head in GET /data")); assertThat(simple.getUnusedResources(), containsInAnyOrder("/unused")); assertThat(simple.getUnusedResponseCodes(), containsInAnyOrder("200 in GET /data", "201 in GET /data", "201 in POST /data")); assertThat(simple.getUnusedResponseHeaders(), containsInAnyOrder("rh in GET /data -> 200")); } @Test public void clearUsageQuery() throws Exception { mockSender.contentOfGet("v1/data?q=1"); mockSender.contentOfGet("v1/other"); Thread.sleep(10); proxySender.get(PING, "clear-usage=true"); final HttpResponse res = proxySender.get(USAGE); final Map<String, Object> actual = mapped(content(res), Map.class); assertTrue(actual.isEmpty()); } @Test public void clearUsageUrl() throws Exception { mockSender.contentOfGet("v1/data?q=1"); mockSender.contentOfGet("v1/other"); Thread.sleep(10); proxySender.send(CLEAR_USAGE); final HttpResponse res = proxySender.get(USAGE); final Map<String, Object> actual = mapped(content(res), Map.class); assertTrue(actual.isEmpty()); } @Test public void clearReportsUrl() throws Exception { mockSender.contentOfGet("v1/data?q=1"); mockSender.contentOfGet("v1/other"); Thread.sleep(10); proxySender.send(CLEAR_REPORTS); final HttpResponse res = proxySender.get(REPORTS); final Map<String, Object> actual = mapped(content(res), Map.class); assertTrue(actual.isEmpty()); } @Test public void reload() throws Exception { mockSender.get("meta"); Thread.sleep(10); final HttpResponse res = proxySender.get(REPORTS, "clear-reports=true"); final Map<String, List> actual = mapped(content(res), Map.class); assertEquals(1, actual.get("simple").size()); proxySender.send(RELOAD); final HttpResponse res2 = proxySender.get(REPORTS); final Map<String, List> actual2 = mapped(content(res2), Map.class); assertEquals(0, actual2.size()); } @Test public void ping() throws Exception { proxySender.send(PING); } @Test public void validation() throws Exception { final HttpResponse res = proxySender.get(VALIDATE); final String content = content(res); final ValidationData resAsData = mapped(content, ValidationData.class); assertEquals("simple", resAsData.getRamlTitle()); assertEquals("root definition has no documentation", resAsData.getValidationViolations().get(0)); } @SuppressWarnings("unchecked") private <T> T mapped(String source, Class<?> target) throws IOException { return (T) new ObjectMapper().readValue(source, target); } private static class UnclearableReportAggregator extends SimpleReportAggregator { private List<RamlReport> unclearableReports = new ArrayList<>(); @Override public RamlReport addReport(RamlReport report) { unclearableReports.add(report); return super.addReport(report); } @Override public Usage getUsage() { return UsageBuilder.usage(getRaml(), unclearableReports); } } }
3e0eb4fb3832737f73d2932698c803d81aa99209
1,879
java
Java
src/main/java/demo/repository/EmployeeRepository.java
yuzhou2/restful-lambda
47036776721ab7151269edaf3c7273c9e6f21c6c
[ "Apache-2.0" ]
null
null
null
src/main/java/demo/repository/EmployeeRepository.java
yuzhou2/restful-lambda
47036776721ab7151269edaf3c7273c9e6f21c6c
[ "Apache-2.0" ]
null
null
null
src/main/java/demo/repository/EmployeeRepository.java
yuzhou2/restful-lambda
47036776721ab7151269edaf3c7273c9e6f21c6c
[ "Apache-2.0" ]
null
null
null
35.45283
114
0.734965
6,242
package demo.repository; import java.io.IOException; import com.amazonaws.annotation.ThreadSafe; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import demo.model.Employee; @ThreadSafe public final class EmployeeRepository { private DynamoDBMapper dynamodbMapper; public EmployeeRepository() { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); dynamodbMapper = new DynamoDBMapper(client, DynamoDBMapperConfig.SaveBehavior.UPDATE_SKIP_NULL_ATTRIBUTES.config()); } public EmployeeRepository(DynamoDBMapper mapper) { this.dynamodbMapper = mapper; } public Employee getEmployee(String appId, String uuid) throws IllegalAccessException, InstantiationException { Class<? extends Employee> clazz = Employee.getDataType(appId); Employee result = dynamodbMapper.load(clazz, uuid); if (result == null) { result = clazz.newInstance(); result.setUuid(uuid); } return result; } public void removeEmployee(String appId, String uuid) throws IllegalArgumentException, IllegalAccessException, InstantiationException { Employee employee = Employee.getDataType(appId).newInstance(); employee.setUuid(uuid); dynamodbMapper.delete(employee); } public void updateEmployee(String appId, String uuid, String jsonStr) throws IllegalArgumentException, IOException, IllegalAccessException, InstantiationException { Employee employee = Employee.unmarshall(appId, jsonStr); employee.setUuid(uuid); dynamodbMapper.save(employee); } }
3e0eb5536d1317f975c685ddd38523e0d5abd832
405
java
Java
mobile_app1/module955/src/main/java/module955packageJava0/Foo10.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
70
2021-01-22T16:48:06.000Z
2022-02-16T10:37:33.000Z
mobile_app1/module955/src/main/java/module955packageJava0/Foo10.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
16
2021-01-22T20:52:52.000Z
2021-08-09T17:51:24.000Z
mobile_app1/module955/src/main/java/module955packageJava0/Foo10.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
5
2021-01-26T13:53:49.000Z
2021-08-11T20:10:57.000Z
11.25
44
0.577778
6,243
package module955packageJava0; import java.lang.Integer; public class Foo10 { Integer int0; Integer int1; Integer int2; public void foo0() { new module955packageJava0.Foo9().foo5(); } public void foo1() { foo0(); } public void foo2() { foo1(); } public void foo3() { foo2(); } public void foo4() { foo3(); } public void foo5() { foo4(); } }
3e0eb72301c51c2319011b06c0290ac219867ed8
2,984
java
Java
91930-introducao-a-programacao-2/listas/Steffano_Pereira_LISTA_02/src/questao03/TesteControladorFinanceiro.java
SteffanoP/ufrpe-materials
48d374dd41983e062fdf605fb7b59fa6ac6348fd
[ "Unlicense" ]
null
null
null
91930-introducao-a-programacao-2/listas/Steffano_Pereira_LISTA_02/src/questao03/TesteControladorFinanceiro.java
SteffanoP/ufrpe-materials
48d374dd41983e062fdf605fb7b59fa6ac6348fd
[ "Unlicense" ]
1
2021-09-16T13:28:37.000Z
2021-09-16T13:28:37.000Z
91930-introducao-a-programacao-2/listas/Steffano_Pereira_LISTA_02/src/questao03/TesteControladorFinanceiro.java
SteffanoP/ufrpe-materials
48d374dd41983e062fdf605fb7b59fa6ac6348fd
[ "Unlicense" ]
null
null
null
52.350877
124
0.642761
6,244
package questao03; import questao03.despesa.DespesaComAgua; import questao03.despesa.DespesaComEnergia; import questao03.despesa.DespesaComInternet; import questao03.receita.LicencaBasica; import questao03.receita.LicencaEnterprise; import questao03.receita.LicencaPlus; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; public class TesteControladorFinanceiro { public static void main(String[] args) { //Instanciando as despesas Transacao despesaTim = new DespesaComInternet(LocalDateTime.of(2021,5,20,22,19), "Conta TIM",197.26D); Transacao despesaLuz = new DespesaComEnergia(LocalDateTime.of(2021,5,20,22,21), "Conta Celpe",204); Transacao despesaAgua = new DespesaComAgua(LocalDateTime.of(2021,5,20,22,23), "Conta Compesa",32); //Instanciando as Receitas Transacao receitaBasica = new LicencaBasica(LocalDateTime.of(2021,5,20,22,26), "Plano Básico",5); Transacao receitaPlus = new LicencaPlus(LocalDateTime.of(2021,5,20,22,46), "Plano Plus",10); Transacao receitaEnterprise = new LicencaEnterprise(LocalDateTime.of(2021,5,20,22,48), "Plano Enterprise",3); //Criando o Fluxo de Caixa e Empresa FluxoCaixa minhaEmpresa = new FluxoCaixa("Minha Empresa","76.658.370/0001-82"); minhaEmpresa.adicionarTransacao(despesaTim); //668,844 minhaEmpresa.adicionarTransacao(despesaLuz); // minhaEmpresa.adicionarTransacao(despesaAgua); minhaEmpresa.adicionarTransacao(receitaBasica); //+100 minhaEmpresa.adicionarTransacao(receitaPlus); //+350 minhaEmpresa.adicionarTransacao(receitaEnterprise); //+450 LocalDate dataInicio = LocalDate.of(2021,05,18); LocalDate dataFim = LocalDate.of(2021,05,21); System.out.printf("Saldo da Empresa: R$%,.2f\n",minhaEmpresa.saldoAtual()); System.out.printf("Despesas: R$%,.2f\n",minhaEmpresa.calcularDespesas(dataInicio,dataFim)); System.out.printf("Percentual de Despesa: %,.2f%%\n",minhaEmpresa.percentualDespesasNoMes(5,2021)); System.out.printf("Receitas: R$%,.2f\n",minhaEmpresa.calcularReceitas(dataInicio,dataFim)); System.out.printf("Percentual de Receita: %,.2f%%\n",minhaEmpresa.percentualReceitasNoMes(5,2021)); System.out.println("----- Teste listarTransacoesNoMes() -----"); List<Transacao> transacoes = new ArrayList<>(minhaEmpresa.listarTransacoesNoMes(5,2021)); for (Transacao transacao : transacoes) { System.out.printf("%s | %s | %s\n",transacao.getData().toString(),transacao.getTipo(),transacao.getDescricao()); } } }
3e0eb74cf1eada25718d8e1ecc244506798314d7
1,248
java
Java
src/main/java/com/psygate/minecraft/spigot/sovereignty/ruby/sql/util/RecordLocationTypeConverter.java
psygate/ruby
a080854762813628d2180e6f20b6bc3880ddb2a3
[ "MIT" ]
null
null
null
src/main/java/com/psygate/minecraft/spigot/sovereignty/ruby/sql/util/RecordLocationTypeConverter.java
psygate/ruby
a080854762813628d2180e6f20b6bc3880ddb2a3
[ "MIT" ]
null
null
null
src/main/java/com/psygate/minecraft/spigot/sovereignty/ruby/sql/util/RecordLocationTypeConverter.java
psygate/ruby
a080854762813628d2180e6f20b6bc3880ddb2a3
[ "MIT" ]
null
null
null
40.258065
94
0.724359
6,245
/* * Copyright (C) 2016 psygate (https://github.com/psygate) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ package com.psygate.minecraft.spigot.sovereignty.ruby.sql.util; import com.psygate.minecraft.spigot.sovereignty.ruby.events.RecordLocationType; import com.psygate.minecraft.spigot.sovereignty.ruby.events.RecordPlayerType; import org.jooq.impl.EnumConverter; /** * Created by psygate (https://github.com/psygate) on 01.04.2016. */ public class RecordLocationTypeConverter extends EnumConverter<Integer, RecordLocationType> { public RecordLocationTypeConverter() { super(Integer.class, RecordLocationType.class); } }
3e0eb7a0886d538a82c7f487b1cfabba32acba8f
3,869
java
Java
bundles/org.eclipse.emfcloud.modelserver.edit/src/org/eclipse/emfcloud/modelserver/edit/command/SetCommandContribution.java
eneufeld/emfcloud-modelserver
adfed022c2810b8560556ca8f37f2efeb943ad77
[ "MIT" ]
null
null
null
bundles/org.eclipse.emfcloud.modelserver.edit/src/org/eclipse/emfcloud/modelserver/edit/command/SetCommandContribution.java
eneufeld/emfcloud-modelserver
adfed022c2810b8560556ca8f37f2efeb943ad77
[ "MIT" ]
null
null
null
bundles/org.eclipse.emfcloud.modelserver.edit/src/org/eclipse/emfcloud/modelserver/edit/command/SetCommandContribution.java
eneufeld/emfcloud-modelserver
adfed022c2810b8560556ca8f37f2efeb943ad77
[ "MIT" ]
null
null
null
43.965909
111
0.720083
6,246
/******************************************************************************** * Copyright (c) 2021 EclipseSource and others. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * https://www.eclipse.org/legal/epl-2.0, or the MIT License which is * available at https://opensource.org/licenses/MIT. * * SPDX-License-Identifier: EPL-2.0 OR MIT ********************************************************************************/ package org.eclipse.emfcloud.modelserver.edit.command; import static com.google.common.collect.Iterables.getFirst; import static java.util.Collections.singleton; import static org.eclipse.emf.common.notify.Notification.NO_INDEX; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.edit.command.CommandParameter; import org.eclipse.emf.edit.command.SetCommand; import org.eclipse.emf.edit.domain.EditingDomain; import org.eclipse.emfcloud.modelserver.command.CCommand; import org.eclipse.emfcloud.modelserver.command.CCommandFactory; import org.eclipse.emfcloud.modelserver.common.codecs.DecodingException; import org.eclipse.emfcloud.modelserver.common.codecs.EncodingException; import org.eclipse.emfcloud.modelserver.edit.EMFCommandType; import org.eclipse.emfcloud.modelserver.edit.util.CommandUtil; public class SetCommandContribution extends BasicCommandContribution<SetCommand> { @Override protected CCommand toClient(final SetCommand command, final CCommand origin) throws EncodingException { return clientCommand(command); } @Override protected SetCommand toServer(final URI modelUri, final EditingDomain domain, final CCommand command) throws DecodingException { return serverCommand(domain, command); } public static SetCommand serverCommand(final EditingDomain domain, final CCommand command) { EObject owner = command.getOwner(); EStructuralFeature feature = owner.eClass().getEStructuralFeature(command.getFeature()); Object value; if (feature instanceof EAttribute) { EDataType dataType = ((EAttribute) feature).getEAttributeType(); value = command.getDataValues().isEmpty() ? null : EcoreUtil.createFromString(dataType, command.getDataValues().get(0)); } else { value = getFirst(command.getObjectValues(), null); } int index = command.getIndices().isEmpty() ? NO_INDEX : command.getIndices().get(0); return (SetCommand) SetCommand.create(domain, owner, feature, value, index); } public static CCommand clientCommand(final SetCommand command) { return clientCommand(command.getOwner(), command.getFeature(), command.getIndex(), command.getValue()); } public static CCommand clientCommand(final EObject owner, final EStructuralFeature feature, final Object value) { return clientCommand(owner, feature, CommandParameter.NO_INDEX, value); } public static CCommand clientCommand(final EObject owner, final EStructuralFeature feature, final int index, final Object value) { CCommand result = CCommandFactory.eINSTANCE.createCommand(); result.setType(EMFCommandType.SET); result.setOwner(owner); result.setFeature(feature.getName()); result.getIndices().add(index); if (feature instanceof EAttribute) { EDataType dataType = ((EAttribute) feature).getEAttributeType(); CommandUtil.collectCommandValues(singleton(value), dataType, result); } else { CommandUtil.collectCommandEObjects(singleton(value), result, true); } return result; } }
3e0eb7df385aa73878fd98cb1be887b72f742f4a
1,353
java
Java
common/src/main/java/com/dremio/common/config/SabotConfigurationException.java
geetek/dremio-oss
812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2
[ "Apache-2.0" ]
1,085
2017-07-19T15:08:38.000Z
2022-03-29T13:35:07.000Z
common/src/main/java/com/dremio/common/config/SabotConfigurationException.java
geetek/dremio-oss
812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2
[ "Apache-2.0" ]
20
2017-07-19T20:16:27.000Z
2021-12-02T10:56:25.000Z
common/src/main/java/com/dremio/common/config/SabotConfigurationException.java
geetek/dremio-oss
812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2
[ "Apache-2.0" ]
398
2017-07-19T18:12:58.000Z
2022-03-30T09:37:40.000Z
32.214286
110
0.756837
6,247
/* * Copyright (C) 2017-2019 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.common.config; public class SabotConfigurationException extends RuntimeException { public SabotConfigurationException() { super(); } public SabotConfigurationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public SabotConfigurationException(String message, Throwable cause) { super(message, cause); } public SabotConfigurationException(String message) { super(message); } public SabotConfigurationException(Throwable cause) { super(cause); } static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SabotConfigurationException.class); }
3e0eb7e3e2ec655e7149a38f71533eba35edc985
255
java
Java
app/src/main/java/ml/puredark/hviewer/configs/PasteEEConfig.java
XFY9326/H-Viewer
3fc4aa29e59dc4afcdee574416fae0a136e6bd03
[ "Apache-2.0" ]
2,044
2016-08-08T12:46:55.000Z
2022-03-26T20:52:18.000Z
app/src/main/java/ml/puredark/hviewer/configs/PasteEEConfig.java
dss16694/H-Viewer
3313b6d43b2837b5cebf8f1b93e1bf60cba9f607
[ "Apache-2.0" ]
121
2016-08-15T21:20:13.000Z
2022-03-14T22:27:05.000Z
app/src/main/java/ml/puredark/hviewer/configs/PasteEEConfig.java
dss16694/H-Viewer
3313b6d43b2837b5cebf8f1b93e1bf60cba9f607
[ "Apache-2.0" ]
337
2016-08-08T13:54:46.000Z
2022-03-09T03:26:05.000Z
23.181818
75
0.729412
6,248
package ml.puredark.hviewer.configs; /** * Created by PureDark on 2016/9/27. */ public class PasteEEConfig { public final static String apiUrl = "https://paste.ee/api"; public final static String appkey = "caf86f4uutaoxfysmf7anj01xl6sv3ps"; }
3e0eb8059d0b227ef1d447c5928748f306edcf2d
4,784
java
Java
omakase/src/main/java/org/projectomakase/omakase/job/rest/v1/interceptor/PostJobInterceptor.java
projectomakase/omakase
08d63c2f08e4632ca14996963895cefb7cea2766
[ "Apache-2.0" ]
1
2016-05-13T09:59:39.000Z
2016-05-13T09:59:39.000Z
omakase/src/main/java/org/projectomakase/omakase/job/rest/v1/interceptor/PostJobInterceptor.java
projectomakase/omakase
08d63c2f08e4632ca14996963895cefb7cea2766
[ "Apache-2.0" ]
2
2019-07-02T17:28:26.000Z
2022-02-09T23:00:37.000Z
omakase/src/main/java/org/projectomakase/omakase/job/rest/v1/interceptor/PostJobInterceptor.java
projectomakase/omakase
08d63c2f08e4632ca14996963895cefb7cea2766
[ "Apache-2.0" ]
2
2016-07-13T15:51:01.000Z
2019-11-20T00:47:19.000Z
38.580645
195
0.729097
6,249
/* * #%L * omakase * %% * Copyright (C) 2015 Project Omakase 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. * #L% */ package org.projectomakase.omakase.job.rest.v1.interceptor; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.CaseFormat; import org.projectomakase.omakase.Omakase; import org.projectomakase.omakase.exceptions.InvalidPropertyException; import org.projectomakase.omakase.job.JobType; import org.projectomakase.omakase.rest.JsonStrings; import org.projectomakase.omakase.job.rest.v1.model.JobModel; import javax.inject.Inject; import javax.ws.rs.ext.ReaderInterceptor; import javax.ws.rs.ext.ReaderInterceptorContext; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Optional; /** * ReaderInterceptor implementation used to modify the JSON payload of POST /jobs prior to deserializing into {@link JobModel} * <p> * Determines the job configuration class from the job type and add it to the JSON payload so that it can be correctly deserialized. Assumes the configuration class name conforms to the following * pattern org.projectomakase.omakase.job.rest.v1.model. + UpperCamel + JobConfigurationModel and the job tye confirms to UPPER_UNDERSCORE e.g. type = INGEST class = * org.projectomakase.omakase.job.rest.v1.model.IngestJobConfigurationModel * </p> * <p> * Wraps the status in a status object if it is included in the payload. * </p> * * @author Richard Lucas */ @PostJob public class PostJobInterceptor implements ReaderInterceptor { private static final String PACKAGE = "org.projectomakase.omakase.job.rest.v1.model."; private static final String CLASS_SUFFIX = "JobConfigurationModel"; @Omakase @Inject ObjectMapper objectMapper; @Override public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException { String json = JsonStrings.inputStreamToString(context.getInputStream()); JsonStrings.isNotNullOrEmpty(json); JsonNode jsonNode = objectMapper.readValue(json, JsonNode.class); addJobTypeImplementationToPayload(jsonNode); wrapStatusInObject(jsonNode); ByteArrayOutputStream resultAsByteArray = new ByteArrayOutputStream(); objectMapper.writeValue(resultAsByteArray, jsonNode); context.setInputStream(new ByteArrayInputStream(resultAsByteArray.toByteArray())); return context.proceed(); } private static void addJobTypeImplementationToPayload(JsonNode jsonNode) throws JsonMappingException { JsonNode typeNode = jsonNode.get("type"); String type; if (typeNode != null) { type = typeNode.asText(); } else { throw new JsonMappingException("'type' is a required property"); } try { JobType.valueOf(type); } catch (IllegalArgumentException e) { throw new InvalidPropertyException("Unsupported job type", e); } JsonNode configurationNode = jsonNode.get("configuration"); if (configurationNode == null) { throw new JsonMappingException("'configuration' is a required property"); } // the @class property is used by jackson to deserialize the configuration in the JSON payload into the correct model object ((ObjectNode) jsonNode.get("configuration")).put("@class", getConfigurationClassName(type)); } private static void wrapStatusInObject(JsonNode jsonNode) { // Modify the POST jobs payload to wrap status in a status object Optional.ofNullable(jsonNode.get("status")).ifPresent(status -> { ((ObjectNode) jsonNode).remove("status"); ObjectNode statusModel = ((ObjectNode) jsonNode).putObject("status"); statusModel.put("current", status.textValue()); }); } private static String getConfigurationClassName(String type) { String formatted = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, type); return PACKAGE + formatted + CLASS_SUFFIX; } }
3e0eb88d5e390ff1de5b0e1f63c9dee280daf6bd
325
java
Java
SSM/MyBatis/learn_01/src/main/java/com/rzhylj/dao/StudentDAO.java
qvtu/spring
72ba5050411ecba759461021b8d5d4df4dc715ac
[ "MIT" ]
null
null
null
SSM/MyBatis/learn_01/src/main/java/com/rzhylj/dao/StudentDAO.java
qvtu/spring
72ba5050411ecba759461021b8d5d4df4dc715ac
[ "MIT" ]
null
null
null
SSM/MyBatis/learn_01/src/main/java/com/rzhylj/dao/StudentDAO.java
qvtu/spring
72ba5050411ecba759461021b8d5d4df4dc715ac
[ "MIT" ]
null
null
null
17.105263
51
0.707692
6,250
package com.rzhylj.dao; import com.rzhylj.entity.Student; import java.util.List; /** * Copyright (C), 2019-2022, Kkoo * Author: kkoo * Date: 2022/2/26 11:14 PM * FileName: StudentDAO */ public interface StudentDAO { public Student searchStu(Integer stuId); public List<Student> searchCls(Integer stuCls); }
3e0eb89ad8df62c789282e5a8a0ddbb50c1b2845
4,014
java
Java
ExtractedJars/iRobot_com.irobot.home/javafiles/com/irobot/core/WebServiceLegalTermsCallback$CppProxy.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/iRobot_com.irobot.home/javafiles/com/irobot/core/WebServiceLegalTermsCallback$CppProxy.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/iRobot_com.irobot.home/javafiles/com/irobot/core/WebServiceLegalTermsCallback$CppProxy.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
32.112
101
0.581465
6,251
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.irobot.core; import java.util.concurrent.atomic.AtomicBoolean; // Referenced classes of package com.irobot.core: // WebServiceLegalTermsCallback private static final class WebServiceLegalTermsCallback$CppProxy extends WebServiceLegalTermsCallback { private native void nativeDestroy(long l); private native void native_onEULAUrlReceived(long l, String s); private native void native_onPrivacyPolicyUrlReceived(long l, String s); private native void native_onTermsAndConditionsUrlReceived(long l, String s); public void destroy() { if(!destroyed.getAndSet(true)) //* 0 0:aload_0 //* 1 1:getfield #26 <Field AtomicBoolean destroyed> //* 2 4:iconst_1 //* 3 5:invokevirtual #45 <Method boolean AtomicBoolean.getAndSet(boolean)> //* 4 8:ifne 19 nativeDestroy(nativeRef); // 5 11:aload_0 // 6 12:aload_0 // 7 13:getfield #35 <Field long nativeRef> // 8 16:invokespecial #47 <Method void nativeDestroy(long)> // 9 19:return } protected void finalize() { destroy(); // 0 0:aload_0 // 1 1:invokevirtual #50 <Method void destroy()> ((Object)this).finalize(); // 2 4:aload_0 // 3 5:invokespecial #54 <Method void Object.finalize()> // 4 8:return } public void onEULAUrlReceived(String s) { native_onEULAUrlReceived(nativeRef, s); // 0 0:aload_0 // 1 1:aload_0 // 2 2:getfield #35 <Field long nativeRef> // 3 5:aload_1 // 4 6:invokespecial #57 <Method void native_onEULAUrlReceived(long, String)> // 5 9:return } public void onPrivacyPolicyUrlReceived(String s) { native_onPrivacyPolicyUrlReceived(nativeRef, s); // 0 0:aload_0 // 1 1:aload_0 // 2 2:getfield #35 <Field long nativeRef> // 3 5:aload_1 // 4 6:invokespecial #60 <Method void native_onPrivacyPolicyUrlReceived(long, String)> // 5 9:return } public void onTermsAndConditionsUrlReceived(String s) { native_onTermsAndConditionsUrlReceived(nativeRef, s); // 0 0:aload_0 // 1 1:aload_0 // 2 2:getfield #35 <Field long nativeRef> // 3 5:aload_1 // 4 6:invokespecial #63 <Method void native_onTermsAndConditionsUrlReceived(long, String)> // 5 9:return } static final boolean $assertionsDisabled = false; private final AtomicBoolean destroyed = new AtomicBoolean(false); private final long nativeRef; static { // 0 0:return } private WebServiceLegalTermsCallback$CppProxy(long l) { // 0 0:aload_0 // 1 1:invokespecial #19 <Method void WebServiceLegalTermsCallback()> // 2 4:aload_0 // 3 5:new #21 <Class AtomicBoolean> // 4 8:dup // 5 9:iconst_0 // 6 10:invokespecial #24 <Method void AtomicBoolean(boolean)> // 7 13:putfield #26 <Field AtomicBoolean destroyed> if(l == 0L) //* 8 16:lload_1 //* 9 17:lconst_0 //* 10 18:lcmp //* 11 19:ifne 32 { throw new RuntimeException("nativeRef is zero"); // 12 22:new #28 <Class RuntimeException> // 13 25:dup // 14 26:ldc1 #30 <String "nativeRef is zero"> // 15 28:invokespecial #33 <Method void RuntimeException(String)> // 16 31:athrow } else { nativeRef = l; // 17 32:aload_0 // 18 33:lload_1 // 19 34:putfield #35 <Field long nativeRef> return; // 20 37:return } } }
3e0eb8d7f10000827c8724d1c3feaf43b14a06d9
2,211
java
Java
message-gateway/src/main/java/com/schoolguard/messages/gateway/weixin/TemplateMessageData.java
zt6220493/netty-check
49535dc1f95f12e4e521b3d563192100d248984f
[ "Apache-2.0" ]
null
null
null
message-gateway/src/main/java/com/schoolguard/messages/gateway/weixin/TemplateMessageData.java
zt6220493/netty-check
49535dc1f95f12e4e521b3d563192100d248984f
[ "Apache-2.0" ]
2
2021-01-21T01:34:45.000Z
2021-12-09T22:40:43.000Z
message-gateway/src/main/java/com/schoolguard/messages/gateway/weixin/TemplateMessageData.java
zt6220493/netty-check
49535dc1f95f12e4e521b3d563192100d248984f
[ "Apache-2.0" ]
null
null
null
29.878378
104
0.674355
6,252
/* * 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 com.schoolguard.messages.gateway.weixin; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.Map; /** * * @author Rogers */ public class TemplateMessageData implements MessageBody { /* {{first.DATA}} 班级:{{keyword1.DATA}} 通知人:{{keyword2.DATA}} 时间:{{keyword3.DATA}} 通知内容:{{keyword4.DATA}} {{remark.DATA}} */ protected static final String topColor = "#4A8BF5"; protected static final String valueColor = "#173177"; protected static final JsonNodeFactory nodeFactory = JsonNodeFactory.instance; protected String toUser; protected String url; private final String templateId; protected Map<String, String> dataMap; public TemplateMessageData(String toUser, String url, String templateId, Map<String, String> data) { this.toUser = toUser; this.url = url; this.templateId = templateId; this.dataMap = data; } @Override public JsonNode toJson() { ObjectNode rootNode = nodeFactory.objectNode(); rootNode.put("touser", this.toUser); rootNode.put("template_id", this.templateId); rootNode.put("url", this.url); rootNode.put("topcolor", TemplateMessageData.topColor); rootNode.set("data", getMessageData()); return rootNode; } protected JsonNode getMessageData() { ObjectNode dataNode = nodeFactory.objectNode(); for (String key : this.dataMap.keySet()) { setDataField(dataNode, key, this.dataMap.get(key)); } return dataNode; } protected ObjectNode setDataField(ObjectNode dataNode, String fieldName, String value) { ObjectNode valueNode = nodeFactory.objectNode(); valueNode.put("color", TemplateMessageData.valueColor); valueNode.put("value", value); dataNode.set(fieldName, valueNode); return dataNode; } }
3e0eb9caecb9f9da7a3d189cd24e89433e9301a3
3,940
java
Java
ui/cli/dataloader/src/java/com/echothree/ui/cli/dataloader/util/data/handler/party/NameSuffixesHandler.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
1
2020-09-01T08:39:01.000Z
2020-09-01T08:39:01.000Z
ui/cli/dataloader/src/java/com/echothree/ui/cli/dataloader/util/data/handler/party/NameSuffixesHandler.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
null
null
null
ui/cli/dataloader/src/java/com/echothree/ui/cli/dataloader/util/data/handler/party/NameSuffixesHandler.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
1
2020-05-31T08:34:46.000Z
2020-05-31T08:34:46.000Z
42.365591
120
0.624365
6,253
// -------------------------------------------------------------------------------- // Copyright 2002-2021 Echo Three, 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.echothree.ui.cli.dataloader.util.data.handler.party; import com.echothree.control.user.party.common.PartyUtil; import com.echothree.control.user.party.common.PartyService; import com.echothree.control.user.party.common.form.CreateNameSuffixForm; import com.echothree.control.user.party.common.form.PartyFormFactory; import com.echothree.control.user.party.common.result.CreateNameSuffixResult; import com.echothree.ui.cli.dataloader.util.data.InitialDataParser; import com.echothree.ui.cli.dataloader.util.data.handler.BaseHandler; import com.echothree.util.common.command.CommandResult; import com.echothree.util.common.command.ExecutionResult; import javax.naming.NamingException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class NameSuffixesHandler extends BaseHandler { PartyService partyService; /** Creates a new instance of NameSuffixesHandler */ public NameSuffixesHandler(InitialDataParser initialDataParser, BaseHandler parentHandler) { super(initialDataParser, parentHandler); try { partyService = PartyUtil.getHome(); } catch (NamingException ne) { // TODO: Handle Exception } } @Override public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException { if(localName.equals("nameSuffix")) { String description = null; String isDefault = null; String sortOrder = null; int count = attrs.getLength(); for(int i = 0; i < count; i++) { if(attrs.getQName(i).equals("description")) description = attrs.getValue(i); else if(attrs.getQName(i).equals("isDefault")) isDefault = attrs.getValue(i); else if(attrs.getQName(i).equals("sortOrder")) sortOrder = attrs.getValue(i); } try { if(initialDataParser.getNameSuffixes().get(description) == null) { CreateNameSuffixForm form = PartyFormFactory.getCreateNameSuffixForm(); form.setDescription(description); form.setIsDefault(isDefault); form.setSortOrder(sortOrder); CommandResult commandResult = partyService.createNameSuffix(initialDataParser.getUserVisit(), form); ExecutionResult executionResult = commandResult.getExecutionResult(); CreateNameSuffixResult result = (CreateNameSuffixResult)executionResult.getResult(); initialDataParser.addNameSuffix(result.getNameSuffixId(), description); } } catch (Exception e) { throw new SAXException(e); } } } @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if(localName.equals("nameSuffixes")) { initialDataParser.popHandler(); } } }
3e0eb9d4fd2c6c5ce03adcefe58e938dd91a94b0
841
java
Java
swift/web/src/main/java/edu/mayo/mprc/swift/webservice/FieldsOnlyJacksonVisibility.java
raymond301/swift
15468b25c67288ac0bdcbe55ced0d3edf5c145f6
[ "Apache-2.0" ]
1
2022-02-09T23:18:40.000Z
2022-02-09T23:18:40.000Z
swift/web/src/main/java/edu/mayo/mprc/swift/webservice/FieldsOnlyJacksonVisibility.java
raymond301/swift
15468b25c67288ac0bdcbe55ced0d3edf5c145f6
[ "Apache-2.0" ]
7
2020-06-30T22:53:57.000Z
2022-02-01T00:56:04.000Z
swift/web/src/main/java/edu/mayo/mprc/swift/webservice/FieldsOnlyJacksonVisibility.java
raymond301/swift
15468b25c67288ac0bdcbe55ced0d3edf5c145f6
[ "Apache-2.0" ]
1
2015-02-25T06:57:58.000Z
2015-02-25T06:57:58.000Z
32.346154
71
0.796671
6,254
package edu.mayo.mprc.swift.webservice; import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; import org.codehaus.jackson.map.introspect.VisibilityChecker; import org.codehaus.jackson.map.introspect.VisibilityChecker.Std; import org.springframework.stereotype.Component; /** * We configure Jackson to only look for fields, just like XStream. * <p/> * We return a visibility checker with getters/setters disabled and use * it to create a custom Jackson serializer. * * @author Roman Zenka */ @Component("fieldsOnlyJacksonChecker") public final class FieldsOnlyJacksonVisibility { public VisibilityChecker checker() { return Std.defaultInstance().withFieldVisibility(Visibility.ANY) .withGetterVisibility(Visibility.NONE) .withIsGetterVisibility(Visibility.NONE) .withSetterVisibility(Visibility.NONE); } }
3e0ebb6ceb1dffffacc95a6e7376a6080122ee21
1,323
java
Java
autoconfigure/src/main/java/info/developerblog/spring/cloud/marathon/actuator/MarathonEndpoint.java
i-Taozi/spring-cloud-marathon
e79fdeff8f3243891a62a3961c6f6179ec3d2f6c
[ "MIT" ]
33
2016-07-08T07:27:58.000Z
2020-05-25T10:01:29.000Z
autoconfigure/src/main/java/info/developerblog/spring/cloud/marathon/actuator/MarathonEndpoint.java
i-Taozi/spring-cloud-marathon
e79fdeff8f3243891a62a3961c6f6179ec3d2f6c
[ "MIT" ]
16
2016-07-11T09:04:20.000Z
2019-03-19T16:02:46.000Z
autoconfigure/src/main/java/info/developerblog/spring/cloud/marathon/actuator/MarathonEndpoint.java
i-Taozi/spring-cloud-marathon
e79fdeff8f3243891a62a3961c6f6179ec3d2f6c
[ "MIT" ]
20
2016-07-08T17:09:46.000Z
2021-11-04T08:58:43.000Z
25.941176
74
0.684807
6,255
package info.developerblog.spring.cloud.marathon.actuator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import lombok.Builder; import lombok.Data; import lombok.extern.slf4j.Slf4j; import mesosphere.marathon.client.Marathon; import mesosphere.marathon.client.model.v2.GetServerInfoResponse; import mesosphere.marathon.client.model.v2.VersionedApp; /** * Created by aleksandr on 12.08.16. */ @Slf4j @Endpoint(id = "marathon") public class MarathonEndpoint { private Marathon marathon; @Autowired public MarathonEndpoint(Marathon marathon) { this.marathon = marathon; } @ReadOperation public MarathonData info() { try { return MarathonData.builder() .serverInfo(marathon.getServerInfo()) .apps(marathon.getApps().getApps()) .build(); } catch (Exception e) { log.error(e.getMessage(), e); } return MarathonData.builder().build(); } @Data @Builder public static class MarathonData { GetServerInfoResponse serverInfo; List<VersionedApp> apps; } }
3e0ebc136b477ac3eb605582007183df454cfca0
4,227
java
Java
engine/src/main/java/io/zeebe/engine/processor/TypedCommandWriterImpl.java
Jatish-Khanna/zeebe
7f2f80da6046911c8108d3921835c8620734686b
[ "Apache-2.0" ]
null
null
null
engine/src/main/java/io/zeebe/engine/processor/TypedCommandWriterImpl.java
Jatish-Khanna/zeebe
7f2f80da6046911c8108d3921835c8620734686b
[ "Apache-2.0" ]
2
2021-08-09T21:00:53.000Z
2021-12-14T20:56:23.000Z
engine/src/main/java/io/zeebe/engine/processor/TypedCommandWriterImpl.java
Jatish-Khanna/zeebe
7f2f80da6046911c8108d3921835c8620734686b
[ "Apache-2.0" ]
null
null
null
33.816
95
0.748521
6,256
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.0. You may not use this file * except in compliance with the Zeebe Community License 1.0. */ package io.zeebe.engine.processor; import static io.zeebe.engine.processor.TypedEventRegistry.EVENT_REGISTRY; import io.zeebe.dispatcher.Dispatcher; import io.zeebe.logstreams.log.LogStreamBatchWriter; import io.zeebe.logstreams.log.LogStreamBatchWriter.LogEntryBuilder; import io.zeebe.logstreams.log.LogStreamBatchWriterImpl; import io.zeebe.msgpack.UnpackedObject; import io.zeebe.protocol.Protocol; import io.zeebe.protocol.impl.record.RecordMetadata; import io.zeebe.protocol.record.RecordType; import io.zeebe.protocol.record.RejectionType; import io.zeebe.protocol.record.ValueType; import io.zeebe.protocol.record.intent.Intent; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; public class TypedCommandWriterImpl implements TypedCommandWriter { protected final Consumer<RecordMetadata> noop = m -> {}; protected final Map<Class<? extends UnpackedObject>, ValueType> typeRegistry; protected RecordMetadata metadata = new RecordMetadata(); protected LogStreamBatchWriter batchWriter; protected long sourceRecordPosition = -1; public TypedCommandWriterImpl(int partitionId, final Dispatcher dispatcher) { metadata.protocolVersion(Protocol.PROTOCOL_VERSION); this.batchWriter = new LogStreamBatchWriterImpl(partitionId, dispatcher); this.typeRegistry = new HashMap<>(); EVENT_REGISTRY.forEach((e, c) -> typeRegistry.put(c, e)); } public void configureSourceContext(final long sourceRecordPosition) { this.sourceRecordPosition = sourceRecordPosition; } protected void initMetadata( final RecordType type, final Intent intent, final UnpackedObject value) { metadata.reset(); final ValueType valueType = typeRegistry.get(value.getClass()); if (valueType == null) { // usually happens when the record is not registered at the TypedStreamEnvironment throw new RuntimeException("Missing value type mapping for record: " + value.getClass()); } metadata.recordType(type).valueType(valueType).intent(intent); } protected void appendRecord( final long key, final RecordType type, final Intent intent, final UnpackedObject value, final Consumer<RecordMetadata> additionalMetadata) { appendRecord(key, type, intent, RejectionType.NULL_VAL, "", value, additionalMetadata); } protected void appendRecord( final long key, final RecordType type, final Intent intent, final RejectionType rejectionType, final String rejectionReason, final UnpackedObject value, final Consumer<RecordMetadata> additionalMetadata) { final LogEntryBuilder event = batchWriter.event(); if (sourceRecordPosition >= 0) { batchWriter.sourceRecordPosition(sourceRecordPosition); } initMetadata(type, intent, value); metadata.rejectionType(rejectionType); metadata.rejectionReason(rejectionReason); additionalMetadata.accept(metadata); if (key >= 0) { event.key(key); } else { event.keyNull(); } event.metadataWriter(metadata).valueWriter(value).done(); } @Override public void appendNewCommand(final Intent intent, final UnpackedObject value) { appendRecord(-1, RecordType.COMMAND, intent, value, noop); } @Override public void appendFollowUpCommand( final long key, final Intent intent, final UnpackedObject value) { appendRecord(key, RecordType.COMMAND, intent, value, noop); } @Override public void appendFollowUpCommand( final long key, final Intent intent, final UnpackedObject value, final Consumer<RecordMetadata> metadata) { appendRecord(key, RecordType.COMMAND, intent, value, metadata); } @Override public void reset() { batchWriter.reset(); } @Override public long flush() { return batchWriter.tryWrite(); } }
3e0ebc94194507d4c5f55a9fc85f8425bce35cbe
1,231
java
Java
src/com/robo/mvp/guice/GuicePresenterFactory.java
robo-creative/robo-mvp-guice
9f1978e39facd56b0f7012e6c7586a87703deaae
[ "Apache-2.0" ]
null
null
null
src/com/robo/mvp/guice/GuicePresenterFactory.java
robo-creative/robo-mvp-guice
9f1978e39facd56b0f7012e6c7586a87703deaae
[ "Apache-2.0" ]
null
null
null
src/com/robo/mvp/guice/GuicePresenterFactory.java
robo-creative/robo-mvp-guice
9f1978e39facd56b0f7012e6c7586a87703deaae
[ "Apache-2.0" ]
null
null
null
28.627907
80
0.748985
6,257
/** * Copyright (c) 2016 Robo Creative - https://robo-creative.github.io. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.robo.mvp.guice; import com.google.inject.Injector; import com.robo.mvp.Presenter; import com.robo.mvp.PresenterFactory; /** * Provides an implementation of {@link PresenterFactory}. Uses Guice's injector * to resolve presenter instances. * * @author robo-admin. * */ public class GuicePresenterFactory implements PresenterFactory { private final Injector mInjector; public GuicePresenterFactory(Injector injector) { mInjector = injector; } public Presenter create(Class<? extends Presenter> presenterType) { return mInjector.getInstance(presenterType); } }
3e0ebcf1ea874093b05e17e593191f7497b6ed5a
1,827
java
Java
app/src/main/java/com/bearbunny/controllerdemo/BackgroundProcessManager.java
peter10110/Android-SteamVR-controller
931d22cf9e02b73ee90107c7fdba06d9da29b3ab
[ "MIT" ]
23
2017-04-30T11:28:26.000Z
2021-08-31T15:16:31.000Z
app/src/main/java/com/bearbunny/controllerdemo/BackgroundProcessManager.java
abrarrobotics/Android-SteamVR-controller
931d22cf9e02b73ee90107c7fdba06d9da29b3ab
[ "MIT" ]
2
2017-07-08T18:22:20.000Z
2018-10-14T03:28:52.000Z
app/src/main/java/com/bearbunny/controllerdemo/BackgroundProcessManager.java
abrarrobotics/Android-SteamVR-controller
931d22cf9e02b73ee90107c7fdba06d9da29b3ab
[ "MIT" ]
7
2018-05-23T19:51:24.000Z
2022-03-08T13:45:03.000Z
27.681818
93
0.631089
6,258
package com.bearbunny.controllerdemo; import android.app.Activity; import android.util.Log; import java.util.Timer; import java.util.TimerTask; /** * Created by Peter on 2016.12.19.. */ public class BackgroundProcessManager { private Timer sendDataOverWifiTimer; private ControllerDataProvider dataProvider; private SendDataThroughWifi wifiModeProvider; private Activity activity; private boolean sendingOnWifi = false; public BackgroundProcessManager(Activity activity, ControllerDataProvider dataProvider) { this.activity = activity; this.dataProvider = dataProvider; } public boolean getWifiSendingState() { return sendingOnWifi; } public void StartDataSendOnWifi(long interval, String targetIP) { if (!sendingOnWifi) { Log.d("Bg process manager", "Star send on WiFi"); sendingOnWifi = true; if (sendDataOverWifiTimer == null) { wifiModeProvider = new SendDataThroughWifi(activity, dataProvider); wifiModeProvider.InitSendThroughWifi(targetIP); } sendDataOverWifiTimer = new Timer(); sendDataOverWifiTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { wifiModeProvider.SendData(); } }, 0l, interval); } } public void StopDataSendOnWifi() { Log.d("Bg process manager", "Stop send on WiFi"); sendingOnWifi = false; if (sendDataOverWifiTimer != null) { sendDataOverWifiTimer.cancel(); } } public void ResetDataSenDOnWifi() { StopDataSendOnWifi(); sendDataOverWifiTimer = null; } public void OnStop() { StopDataSendOnWifi(); } }
3e0ebd7bf1971b4bfb366570b7ea35ab69930818
375
java
Java
src/genericsExercises/genericsProblem/MyClass.java
VladimirMetodiev/JavaDevelopment
0192b8923805b87ce07040d655644aeed764cf18
[ "MIT" ]
null
null
null
src/genericsExercises/genericsProblem/MyClass.java
VladimirMetodiev/JavaDevelopment
0192b8923805b87ce07040d655644aeed764cf18
[ "MIT" ]
null
null
null
src/genericsExercises/genericsProblem/MyClass.java
VladimirMetodiev/JavaDevelopment
0192b8923805b87ce07040d655644aeed764cf18
[ "MIT" ]
null
null
null
17.045455
52
0.597333
6,259
package genericsExercises.genericsProblem; public class MyClass<E> { private E attribute; MyClass(E var){ this.attribute = var; } public E get(){ return this.attribute; } public void set(E value){ this.attribute = value; } public static<E> boolean equals(E obj1, E obj2){ return obj1.equals(obj2); } }
3e0ebe352f429e0ad124304b67d7af753df2d88a
2,231
java
Java
lib/LWJGL/lwjgl-source-2/src/java/org/lwjgl/DefaultSysImplementation.java
mk12/mycraft
ee734d45deece8aac52fd8cdca24c498e03f990f
[ "MIT" ]
23
2015-01-20T13:59:20.000Z
2022-02-02T16:43:34.000Z
lib/LWJGL/lwjgl-source-2/src/java/org/lwjgl/DefaultSysImplementation.java
Tominous/mycraft
ee734d45deece8aac52fd8cdca24c498e03f990f
[ "MIT" ]
null
null
null
lib/LWJGL/lwjgl-source-2/src/java/org/lwjgl/DefaultSysImplementation.java
Tominous/mycraft
ee734d45deece8aac52fd8cdca24c498e03f990f
[ "MIT" ]
9
2015-04-29T17:32:31.000Z
2019-06-09T13:51:12.000Z
38.724138
78
0.740873
6,260
/* * Copyright (c) 2002-2008 LWJGL Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'LWJGL' nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.lwjgl; /** * * @author elias_naur <upchh@example.com> * @version $Revision: 3426 $ * $Id: DefaultSysImplementation.java 3426 2010-10-01 22:20:14Z spasi $ */ abstract class DefaultSysImplementation implements SysImplementation { public native int getJNIVersion(); public native int getPointerSize(); public native void setDebug(boolean debug); public long getTimerResolution() { return 1000; } public boolean has64Bit() { return false; } public abstract long getTime(); public abstract void alert(String title, String message); public abstract String getClipboard(); }
3e0ebea44fd924d629b91f32d02409f96c5c1320
12,019
java
Java
source/ocotillo/graph/layout/locator/intervaltree/IntervalTreeLocator.java
EngAAlex/MultiDynNos
1ab191b3bb4898621298576a4a48d09c7fea4cd5
[ "Apache-2.0" ]
null
null
null
source/ocotillo/graph/layout/locator/intervaltree/IntervalTreeLocator.java
EngAAlex/MultiDynNos
1ab191b3bb4898621298576a4a48d09c7fea4cd5
[ "Apache-2.0" ]
null
null
null
source/ocotillo/graph/layout/locator/intervaltree/IntervalTreeLocator.java
EngAAlex/MultiDynNos
1ab191b3bb4898621298576a4a48d09c7fea4cd5
[ "Apache-2.0" ]
null
null
null
30.122807
126
0.591896
6,261
/** * Copyright © 2014-2016 Paolo Simonetto * * 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 ocotillo.graph.layout.locator.intervaltree; import java.util.Collection; import java.util.HashSet; import java.util.Set; import ocotillo.geometry.Box; import ocotillo.geometry.Geom; import ocotillo.geometry.GeomE; import ocotillo.geometry.IntervalBox; import ocotillo.graph.Edge; import ocotillo.graph.Element; import ocotillo.graph.ElementAttribute; import ocotillo.graph.Graph; import ocotillo.graph.GraphWithElements; import ocotillo.graph.Node; import ocotillo.graph.Observer; import ocotillo.graph.layout.locator.ElementLocatorAbst; import ocotillo.structures.MultidimIntervalTree; /** * Locator based on multilevel interval trees. */ public class IntervalTreeLocator extends ElementLocatorAbst { private final MultidimIntervalTree<Boxed<Node>> nodeTree; private final MultidimIntervalTree<Boxed<Edge>> edgeTree; private final boolean autoSync; private Observer.GraphElements elementObserver; private Observer.ElementAttributeChanges<Node> nodePositionObserver; private Observer.ElementAttributeChanges<Node> nodeSizeObserver; private Observer.ElementAttributeChanges<Edge> edgePointsObserver; private Observer.ElementAttributeChanges<Edge> edgeWitdhObserver; /** * Builder for interval tree locator. */ public static class ItlBuilder { private final Graph graph; private final NodePolicy nodePolicy; private final EdgePolicy edgePolicy; private GeomE geometry = Geom.e2D; private boolean autoSync = true; /** * Construct an interval tree locator builder. * * @param graph the graph. * @param nodePolicy the node policy. * @param edgePolicy the edge policy. */ public ItlBuilder(Graph graph, NodePolicy nodePolicy, EdgePolicy edgePolicy) { this.graph = graph; this.nodePolicy = nodePolicy; this.edgePolicy = edgePolicy; } /** * Indicates the Euclidean geometry to be used. * * @param geometry the geometry. * @return this builder. */ public ItlBuilder withGeometry(GeomE geometry) { this.geometry = geometry; return this; } /** * Enables automatic synchronisation. * * @return this builder. */ public ItlBuilder enableAutoSync() { this.autoSync = true; return this; } /** * Disables automatic synchronisation. The structure must be updated * using rebuild. * * @return this builder. */ public ItlBuilder disableAutoSync() { this.autoSync = false; return this; } /** * Generates the interval tree locator. * * @return the locator. */ public IntervalTreeLocator build() { return new IntervalTreeLocator(graph, geometry, nodePolicy, edgePolicy, autoSync); } } /** * Builds an interval tree locator. * * @param graph the graph. * @param geometry the geometry to be used. * @param nodePolicy the node policy. * @param edgePolicy the edge policy. * @param autoSync the autoSync status. */ private IntervalTreeLocator(Graph graph, GeomE geometry, NodePolicy nodePolicy, EdgePolicy edgePolicy, boolean autoSync) { super(graph, geometry, nodePolicy, edgePolicy); this.nodeTree = new MultidimIntervalTree<>(geomDim); this.edgeTree = new MultidimIntervalTree<>(geomDim); this.autoSync = autoSync; build(); if (autoSync) { elementObserver = new ElementObserver(graph); nodePositionObserver = new NodePositionObserver(nodePositions); nodeSizeObserver = new NodeSizeObserver(nodeSizes); edgePointsObserver = new EdgeAttributeObserver(edgePoints); edgeWitdhObserver = new EdgeAttributeObserver(edgeWidths); } } /** * Initialises the structure by adding all nodes and edges boxes. */ private void build() { nodeTree.clear(); edgeTree.clear(); nodeBoxes.clear(); edgeBoxes.clear(); if (nodePolicy != NodePolicy.ignoreNodes) { for (Node node : graph.nodes()) { updateBox(node); } } if (edgePolicy != EdgePolicy.ignoreEdges) { for (Edge edge : graph.edges()) { updateBox(edge); } } } @Override protected Box computeBox(Node node) { Box standardBox = super.computeBox(node); return new Boxed<>(node, IntervalBox.newInstance(standardBox)); } @Override protected Box computeBox(Edge edge) { Box standardBox = super.computeBox(edge); return new Boxed<>(edge, IntervalBox.newInstance(standardBox)); } @Override @SuppressWarnings("unchecked") protected void updateBox(Node node) { if (nodeBoxes.containsKey(node)) { Box nodeBox = nodeBoxes.get(node); nodeTree.delete((Boxed<Node>) nodeBox); } if (graph.has(node)) { super.updateBox(node); nodeTree.insert((Boxed<Node>) getBox(node)); } } @Override @SuppressWarnings("unchecked") protected void updateBox(Edge edge) { if (edgeBoxes.containsKey(edge)) { Box edgeBox = edgeBoxes.get(edge); edgeTree.delete((Boxed<Edge>) edgeBox); } if (graph.has(edge)) { super.updateBox(edge); edgeTree.insert((Boxed<Edge>) getBox(edge)); } } @Override public void rebuild() { if (!autoSync) { build(); } } @Override public Collection<Node> getNodesPartiallyInBox(Box box) { return unwrap(nodeTree.getAllOverlapping(IntervalBox.newInstance(box))); } @Override public Collection<Node> getNodesFullyInBox(Box box) { return unwrap(nodeTree.getAllContainedIn(IntervalBox.newInstance(box))); } @Override public Collection<Edge> getEdgesPartiallyInBox(Box box) { return unwrap(edgeTree.getAllOverlapping(IntervalBox.newInstance(box))); } @Override public Collection<Edge> getEdgesFullyInBox(Box box) { return unwrap(edgeTree.getAllContainedIn(IntervalBox.newInstance(box))); } @Override public void close() { if (autoSync) { elementObserver.unregister(); nodePositionObserver.unregister(); nodeSizeObserver.unregister(); edgePointsObserver.unregister(); edgeWitdhObserver.unregister(); } } /** * Unwraps elements from their Boxed container. * * @param <T> the type of element handled. * @param wrappedCollection the wrapped collection. * @return the unwrapped collection. */ private <T extends Element> Collection<T> unwrap(Collection<Boxed<T>> wrappedCollection) { Collection<T> result = new HashSet<>(wrappedCollection.size()); for (Boxed<T> wrappedElement : wrappedCollection) { result.add(wrappedElement.element); } return result; } /** * Wrapper for graph elements that allow them to be inserted in * multidimensional interval trees. * * @param <T> the type of element handled. */ private static class Boxed<T extends Element> extends Box implements MultidimIntervalTree.Data { private final T element; private final IntervalBox box; /** * Builds the wrapper. * * @param node the node. * @param box its box. */ private Boxed(T node, IntervalBox box) { super(box); this.element = node; this.box = box; } /** * Returns the element. * * @return the element. */ public T element() { return element; } @Override public IntervalBox intervalBox() { return box; } } /** * Observer for element insertion or removal. */ private class ElementObserver extends Observer.GraphElements { public ElementObserver(GraphWithElements observedGraph) { super(observedGraph); } @Override public void theseElementsChanged(Collection<Element> changedElements) { if (changedElements.size() > (nodeTree.size() + edgeTree.size()) * 0.5) { build(); } else { for (Element element : changedElements) { if (element instanceof Node) { updateBox((Node) element); } else if (element instanceof Edge) { updateBox((Edge) element); } } } } } /** * Observer for changes in node size attribute. */ private class NodePositionObserver extends Observer.ElementAttributeChanges<Node> { public NodePositionObserver(ElementAttribute<Node, ?> attributeObserved) { super(attributeObserved); } @Override public void update(Collection<Node> changedElements) { if (changedElements.size() > (nodeTree.size() + edgeTree.size()) * 0.4) { build(); } else { Set<Edge> changedEdges = new HashSet<>(); for (Node node : changedElements) { updateBox(node); changedEdges.addAll(graph.inOutEdges(node)); } for (Edge edge : changedEdges) { updateBox(edge); } } } @Override public void updateAll() { build(); } } /** * Observer for changes in node size attribute. */ private class NodeSizeObserver extends Observer.ElementAttributeChanges<Node> { public NodeSizeObserver(ElementAttribute<Node, ?> attributeObserved) { super(attributeObserved); } @Override public void update(Collection<Node> changedElements) { if (changedElements.size() > (nodeTree.size() + edgeTree.size()) * 0.6) { build(); } else { for (Node node : changedElements) { updateBox(node); } } } @Override public void updateAll() { build(); } } /** * Observer for changes in relevant edge attributes. */ private class EdgeAttributeObserver extends Observer.ElementAttributeChanges<Edge> { public EdgeAttributeObserver(ElementAttribute<Edge, ?> attributeObserved) { super(attributeObserved); } @Override public void update(Collection<Edge> changedElements) { if (changedElements.size() > (edgeTree.size() + edgeTree.size()) * 0.6) { build(); } else { for (Edge edge : changedElements) { updateBox(edge); } } } @Override public void updateAll() { build(); } } }
3e0ebf0ebe2c025d15baf5c71c0bddd14ba0c9b9
1,693
java
Java
src/main/java/codes/biscuit/skyblockaddons/asm/hooks/EntityLivingBaseHook.java
TimoLob/SkyblockAddons
cf4930c75762e1f36948c0633d56c86a92f4d50c
[ "MIT" ]
1
2019-11-02T05:24:36.000Z
2019-11-02T05:24:36.000Z
src/main/java/codes/biscuit/skyblockaddons/asm/hooks/EntityLivingBaseHook.java
TimoLob/SkyblockAddons
cf4930c75762e1f36948c0633d56c86a92f4d50c
[ "MIT" ]
null
null
null
src/main/java/codes/biscuit/skyblockaddons/asm/hooks/EntityLivingBaseHook.java
TimoLob/SkyblockAddons
cf4930c75762e1f36948c0633d56c86a92f4d50c
[ "MIT" ]
1
2019-11-01T10:21:09.000Z
2019-11-01T10:21:09.000Z
40.309524
177
0.673952
6,262
package codes.biscuit.skyblockaddons.asm.hooks; import codes.biscuit.skyblockaddons.SkyblockAddons; import codes.biscuit.skyblockaddons.core.Feature; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.IProjectile; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.passive.EntityWolf; import net.minecraft.util.AxisAlignedBB; import java.util.List; public class EntityLivingBaseHook { public static void onResetHurtTime(EntityLivingBase entity) { if (entity == Minecraft.getMinecraft().thePlayer) { SkyblockAddons main = SkyblockAddons.getInstance(); if (!main.getUtils().isOnSkyblock() || !main.getConfigValues().isEnabled(Feature.COMBAT_TIMER_DISPLAY)) { return; } Minecraft mc = Minecraft.getMinecraft(); List<Entity> nearEntities = mc.theWorld.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(mc.thePlayer.posX - 3, mc.thePlayer.posY - 2, mc.thePlayer.posZ - 3, mc.thePlayer.posX + 3, mc.thePlayer.posY + 2, mc.thePlayer.posZ + 3)); boolean foundPossibleAttacker = false; for (Entity nearEntity : nearEntities) { if (nearEntity instanceof EntityMob || nearEntity instanceof EntityWolf || nearEntity instanceof IProjectile) { foundPossibleAttacker = true; break; } } if (foundPossibleAttacker) { SkyblockAddons.getInstance().getUtils().setLastDamaged(System.currentTimeMillis()); } } } }
3e0ebf52be041ca815bc12bcc91a64eefee23f47
1,445
java
Java
app/services/ErrorCodes.java
gmobiler/accordions-server
48f39420db62dfcfe065206d636a3337a5930a17
[ "CC0-1.0" ]
null
null
null
app/services/ErrorCodes.java
gmobiler/accordions-server
48f39420db62dfcfe065206d636a3337a5930a17
[ "CC0-1.0" ]
null
null
null
app/services/ErrorCodes.java
gmobiler/accordions-server
48f39420db62dfcfe065206d636a3337a5930a17
[ "CC0-1.0" ]
null
null
null
57.8
169
0.779931
6,263
package services; //Usa inteiros para representar error codes para não retornar strings e alguém descobrir a api só enviando erros public class ErrorCodes { //Para ServicesController public static final int ERROR_CODE_BODY_EMPTY =5000 ; public static final int ERROR_CODE_METODO_NAO_ENCONTRADO = 5001; //A string de validação embutida no id está em um formato inválido para o login public static final int ERROR_CODE_SV_NAO_ENCONTRADO_COOKIE=5008 ; //A string de valdação da requisição possui uma sintaxe invalida public static final int ERROR_CODE_SV_REQUEST_SINTAXE_INVALIDA =5007 ; //A string de valdação da requisição possui uma sintaxe invalida //Para login public static final int ERROR_CODE_CAMPO_ID_NAO_ENCOTRANDO = 5002; public static final int ERROR_CODE_STRING_VALIDACAO_LOGIN_ID_INVALIDO = 5003; //A string de validação embutida no id está em um formato inválido para o login public static final int ERROR_CODE_USUARIO_INEXISTENTE = 5004; //Não encontrou o usuario solicitado no banco //Pos login public static final int ERROR_CODE_SESSION_SEM_USUARIO_POS_LOGIN = 5009; public static final int ERROR_CODE_USUARIO_INEXISTENTE_POS_LOGIN = 5010; //Falhas no método encode() e decode() public static final int ERROR_CODE_CRYPTO_MANAGER_DECODE_EXCEPTION = 5005; public static final int ERROR_CODE_CRYPTO_MANAGER_ENCODE_EXCEPTION = 5006; }
3e0ec0348821c8d2ae36e7427a37cfa552c56beb
2,220
java
Java
is-lnu-rest-api/src/main/java/org/lnu/is/web/rest/controller/address/type/AddressTypeController.java
JLLeitschuh/ums-backend
363213ff0f8d6a350a3ce559940c5707ad71bfd6
[ "Apache-2.0" ]
14
2015-05-26T11:16:30.000Z
2019-08-16T08:21:24.000Z
is-lnu-rest-api/src/main/java/org/lnu/is/web/rest/controller/address/type/AddressTypeController.java
JLLeitschuh/ums-backend
363213ff0f8d6a350a3ce559940c5707ad71bfd6
[ "Apache-2.0" ]
16
2015-05-26T18:29:05.000Z
2016-04-21T19:11:55.000Z
is-lnu-rest-api/src/main/java/org/lnu/is/web/rest/controller/address/type/AddressTypeController.java
JLLeitschuh/ums-backend
363213ff0f8d6a350a3ce559940c5707ad71bfd6
[ "Apache-2.0" ]
12
2015-07-09T16:11:18.000Z
2020-02-11T05:42:27.000Z
38.947368
128
0.805856
6,264
package org.lnu.is.web.rest.controller.address.type; import javax.annotation.Resource; import org.lnu.is.facade.facade.Facade; import org.lnu.is.resource.address.type.AddressTypeResource; import org.lnu.is.resource.search.PagedRequest; import org.lnu.is.resource.search.PagedResultResource; import org.lnu.is.web.rest.constant.Request; import org.lnu.is.web.rest.controller.BaseController; import org.lnu.is.web.rest.controller.PagedController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.wordnik.swagger.annotations.ApiModel; import com.wordnik.swagger.annotations.ApiOperation; /** * Address types controller. * * @author ROMA * */ @RestController @RequestMapping("/addresstypes") @ApiModel(value = "Address Types", description = "Address Types") public class AddressTypeController extends BaseController implements PagedController<AddressTypeResource, AddressTypeResource> { private static final Logger LOG = LoggerFactory.getLogger(AddressTypeController.class); @Resource(name = "addressTypeFacade") private Facade<AddressTypeResource, AddressTypeResource, Long> facade; @Override @ResponseStatus(HttpStatus.OK) @RequestMapping(method = RequestMethod.GET) @ApiOperation(value = "Get All Address Types") public PagedResultResource<AddressTypeResource> getPagedResource(final PagedRequest<AddressTypeResource> request) { LOG.info("Getting PagedResultResource for Address Tyoe with offset: {}, limit: {}", request.getOffset(), request.getLimit()); return facade.getResources(request); } @Override @ResponseStatus(HttpStatus.OK) @RequestMapping(value = Request.ID, method = RequestMethod.GET) @ApiOperation(value = "Get Address Types by id") public AddressTypeResource getResource(@PathVariable("id") final Long id) { LOG.info("Getting address type resource:{}", id); return facade.getResource(id); } }
3e0ec135b85a26a2ebeee50deced7595781aee08
3,650
java
Java
modules/transit-gateway-apis/src/main/java/com/ibm/cloud/networking/transit_gateway_apis/v1/model/PrefixFilterCust.java
cacarrilloc/networking-java-sdk
228fbf7fc08c0f531d31be06a365c73ec37adb6b
[ "Apache-2.0" ]
null
null
null
modules/transit-gateway-apis/src/main/java/com/ibm/cloud/networking/transit_gateway_apis/v1/model/PrefixFilterCust.java
cacarrilloc/networking-java-sdk
228fbf7fc08c0f531d31be06a365c73ec37adb6b
[ "Apache-2.0" ]
null
null
null
modules/transit-gateway-apis/src/main/java/com/ibm/cloud/networking/transit_gateway_apis/v1/model/PrefixFilterCust.java
cacarrilloc/networking-java-sdk
228fbf7fc08c0f531d31be06a365c73ec37adb6b
[ "Apache-2.0" ]
null
null
null
24.333333
120
0.660548
6,265
/* * (C) Copyright IBM Corp. 2022. * * 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.ibm.cloud.networking.transit_gateway_apis.v1.model; import java.util.Date; import com.google.gson.annotations.SerializedName; import com.ibm.cloud.sdk.core.service.model.GenericModel; /** * prefix filter. */ public class PrefixFilterCust extends GenericModel { /** * Whether to permit or deny prefix filter. */ public interface Action { /** permit. */ String PERMIT = "permit"; /** deny. */ String DENY = "deny"; } protected String action; protected String before; @SerializedName("created_at") protected Date createdAt; protected Long ge; protected String id; protected Long le; protected String prefix; @SerializedName("updated_at") protected Date updatedAt; /** * Gets the action. * * Whether to permit or deny prefix filter. * * @return the action */ public String getAction() { return action; } /** * Gets the before. * * Identifier of prefix filter that handles the ordering and follow semantics: * - When a filter reference another filter in it's before field, then the filter making the reference is applied * before * the referenced filter. For example: if filter A references filter B in its before field, A is applied before B. * - When a new filter is added that has the same before as an existing filter, then the older filter will have its * before * field updated to point to the new filter. Starting with the above example: if filter C is added and it references * B in its * before field, then A's before field should be modified to point to C, so the order of application would be A, C * and finally B. * - A filter that has an empty before reference will be applied last (though the date order mentioned above will * still apply). * So continuing the above examples, if filter B has an empty before field, then it will be applied last, but if * filter D * is created with an empty before field, then B's before field will be modified to point to D, so B will be applied * before D. * * @return the before */ public String getBefore() { return before; } /** * Gets the createdAt. * * The date and time that this prefix filter was created. * * @return the createdAt */ public Date getCreatedAt() { return createdAt; } /** * Gets the ge. * * IP Prefix GE. * * @return the ge */ public Long getGe() { return ge; } /** * Gets the id. * * Prefix Filter identifier. * * @return the id */ public String getId() { return id; } /** * Gets the le. * * IP Prefix LE. * * @return the le */ public Long getLe() { return le; } /** * Gets the prefix. * * IP Prefix. * * @return the prefix */ public String getPrefix() { return prefix; } /** * Gets the updatedAt. * * The date and time that this prefix filter was last updated. * * @return the updatedAt */ public Date getUpdatedAt() { return updatedAt; } }
3e0ec16e8287db77e01da2464f756a4c2717d915
141
java
Java
Application/04 Factory Pattern/TVFactory/HaierTVFactory.java
Naccl/DesignPattern
070a669d24b5e5f6d3dd4b3481f9eb4b8bdebc54
[ "MIT" ]
1
2021-03-17T01:32:50.000Z
2021-03-17T01:32:50.000Z
Application/04 Factory Pattern/TVFactory/HaierTVFactory.java
Naccl/DesignPattern
070a669d24b5e5f6d3dd4b3481f9eb4b8bdebc54
[ "MIT" ]
null
null
null
Application/04 Factory Pattern/TVFactory/HaierTVFactory.java
Naccl/DesignPattern
070a669d24b5e5f6d3dd4b3481f9eb4b8bdebc54
[ "MIT" ]
null
null
null
15.666667
50
0.716312
6,266
public class HaierTVFactory implements TVFactory { public TV produce() { System.out.println("海尔工厂生产海尔电视"); return new HaierTV(); } }
3e0ec281bcf4f2a942f962a5922b224788026ac0
6,204
java
Java
models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaCapabilityAssignment.java
onap/policy-models
567201748af88c9120e623e531ace50382060e00
[ "Apache-2.0" ]
5
2019-10-02T14:13:17.000Z
2021-10-15T15:11:56.000Z
models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaCapabilityAssignment.java
onap/policy-models
567201748af88c9120e623e531ace50382060e00
[ "Apache-2.0" ]
null
null
null
models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaCapabilityAssignment.java
onap/policy-models
567201748af88c9120e623e531ace50382060e00
[ "Apache-2.0" ]
3
2019-11-26T02:37:11.000Z
2020-11-21T09:02:51.000Z
34.853933
114
0.687621
6,267
/*- * ============LICENSE_START======================================================= * Copyright (C) 2020-2021 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ package org.onap.policy.models.tosca.simple.concepts; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Lob; import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NonNull; import org.onap.policy.common.parameters.annotations.NotNull; import org.onap.policy.common.utils.coder.YamlJsonTranslator; import org.onap.policy.models.base.PfConcept; import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfUtils; import org.onap.policy.models.base.validation.annotations.PfMin; import org.onap.policy.models.tosca.authorative.concepts.ToscaCapabilityAssignment; /** * Class to represent the parameter in TOSCA definition. */ @Entity @Table(name = "ToscaCapabilityAssignment") @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @Data @EqualsAndHashCode(callSuper = false) public class JpaToscaCapabilityAssignment extends JpaToscaWithTypeAndStringProperties<ToscaCapabilityAssignment> { private static final long serialVersionUID = 1675770231921107988L; private static final String AUTHORATIVE_UNBOUNDED_LITERAL = "UNBOUNDED"; private static final Integer JPA_UNBOUNDED_VALUE = -1; private static final YamlJsonTranslator YAML_JSON_TRANSLATOR = new YamlJsonTranslator(); @ElementCollection @Lob private Map<@NotNull String, @NotNull String> attributes; @ElementCollection private List<@NotNull @PfMin(value = 0, allowed = -1) Integer> occurrences; /** * The Default Constructor creates a {@link JpaToscaCapabilityAssignment} object with a null key. */ public JpaToscaCapabilityAssignment() { this(new PfConceptKey()); } /** * The Key Constructor creates a {@link JpaToscaCapabilityAssignment} object with the given concept key. * * @param key the key */ public JpaToscaCapabilityAssignment(@NonNull final PfConceptKey key) { super(key); } /** * Copy constructor. * * @param copyConcept the concept to copy from */ public JpaToscaCapabilityAssignment(final JpaToscaCapabilityAssignment copyConcept) { super(copyConcept); this.attributes = copyConcept.attributes == null ? null : new LinkedHashMap<>(copyConcept.attributes); this.occurrences = copyConcept.occurrences == null ? null : new ArrayList<>(copyConcept.occurrences); } /** * Authorative constructor. * * @param authorativeConcept the authorative concept to copy from */ public JpaToscaCapabilityAssignment(@NonNull final ToscaCapabilityAssignment authorativeConcept) { super(authorativeConcept); } @Override public ToscaCapabilityAssignment toAuthorative() { var toscaCapabilityAssignment = new ToscaCapabilityAssignment(); super.setToscaEntity(toscaCapabilityAssignment); super.toAuthorative(); toscaCapabilityAssignment.setAttributes( PfUtils.mapMap(attributes, attribute -> YAML_JSON_TRANSLATOR.fromYaml(attribute, Object.class))); toscaCapabilityAssignment.setOccurrences(PfUtils.mapList(occurrences, occurrence -> { if (occurrence.equals(JPA_UNBOUNDED_VALUE)) { return AUTHORATIVE_UNBOUNDED_LITERAL; } else { return occurrence; } })); return toscaCapabilityAssignment; } @Override public void fromAuthorative(ToscaCapabilityAssignment toscaCapabilityAssignment) { super.fromAuthorative(toscaCapabilityAssignment); attributes = PfUtils.mapMap(toscaCapabilityAssignment.getAttributes(), YAML_JSON_TRANSLATOR::toYaml); occurrences = PfUtils.mapList(toscaCapabilityAssignment.getOccurrences(), occurrence -> { if (occurrence.equals(AUTHORATIVE_UNBOUNDED_LITERAL)) { return JPA_UNBOUNDED_VALUE; } else { return ((Number) occurrence).intValue(); } }); } @Override protected Object deserializePropertyValue(String propValue) { return YAML_JSON_TRANSLATOR.fromYaml(propValue, Object.class); } @Override protected String serializePropertyValue(Object propValue) { return YAML_JSON_TRANSLATOR.toYaml(propValue); } @Override public void clean() { super.clean(); attributes = PfUtils.mapMap(attributes, String::trim); } @Override public int compareTo(final PfConcept otherConcept) { if (this == otherConcept) { return 0; } int result = super.compareTo(otherConcept); if (result != 0) { return result; } final JpaToscaCapabilityAssignment other = (JpaToscaCapabilityAssignment) otherConcept; result = PfUtils.compareMaps(attributes, other.attributes); if (result != 0) { return result; } return PfUtils.compareCollections(occurrences, other.occurrences); } }
3e0ec29c95942206b14cf49090d396de94568f6d
3,901
java
Java
test/com/facebook/buck/python/PythonTestIntegrationTest.java
vine/buck
6fb6d444e43f07d3c2dc7a76c8fca09a07ec9706
[ "Apache-2.0" ]
null
null
null
test/com/facebook/buck/python/PythonTestIntegrationTest.java
vine/buck
6fb6d444e43f07d3c2dc7a76c8fca09a07ec9706
[ "Apache-2.0" ]
null
null
null
test/com/facebook/buck/python/PythonTestIntegrationTest.java
vine/buck
6fb6d444e43f07d3c2dc7a76c8fca09a07ec9706
[ "Apache-2.0" ]
null
null
null
36.457944
103
0.738272
6,268
/* * Copyright 2014-present Facebook, 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.facebook.buck.python; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import com.facebook.buck.cli.FakeBuckConfig; import com.facebook.buck.io.ExecutableFinder; import com.facebook.buck.testutil.TestConsole; import com.facebook.buck.testutil.integration.DebuggableTemporaryFolder; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.ProjectWorkspace.ProcessResult; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.ProcessExecutor; import com.facebook.buck.util.VersionStringComparator; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; public class PythonTestIntegrationTest { @Rule public DebuggableTemporaryFolder tmp = new DebuggableTemporaryFolder(); public ProjectWorkspace workspace; @Before public void setUp() throws IOException { workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "python_test", tmp); workspace.setUp(); } @Test public void testPythonTest() throws IOException { // This test should pass. ProcessResult result1 = workspace.runBuckCommand("test", "//:test-success"); result1.assertSuccess(); workspace.resetBuildLogFile(); // This test should fail. ProcessResult result2 = workspace.runBuckCommand("test", "//:test-failure"); result2.assertTestFailure(); assertThat( "`buck test` should fail because test_that_fails() failed.", result2.getStderr(), containsString("test_that_fails")); } @Test public void testPythonTestEnv() throws IOException { // Test if setting environment during test execution works ProcessResult result = workspace.runBuckCommand("test", "//:test-env"); result.assertSuccess(); } @Test public void testPythonSkippedResult() throws IOException, InterruptedException { assumePythonVersionIsAtLeast("2.7", "unittest skip support was added in Python-2.7"); ProcessResult result = workspace.runBuckCommand("test", "//:test-skip").assertSuccess(); assertThat(result.getStderr(), containsString("1 Skipped")); } @Test public void testPythonTestTimeout() throws IOException { ProcessResult result = workspace.runBuckCommand("test", "//:test-spinning"); String stderr = result.getStderr(); result.assertSpecialExitCode("test should fail", 42); assertTrue(stderr, stderr.contains("Following test case timed out: //:test-spinning")); } private void assumePythonVersionIsAtLeast(String expectedVersion, String message) throws InterruptedException { PythonVersion actualVersion = new PythonBuckConfig(FakeBuckConfig.builder().build(), new ExecutableFinder()) .getPythonEnvironment(new ProcessExecutor(new TestConsole())) .getPythonVersion(); assumeTrue( String.format( "Needs at least Python-%s, but found Python-%s: %s", expectedVersion, actualVersion, message), new VersionStringComparator().compare(actualVersion.getVersionString(), expectedVersion) >= 0); } }
3e0ec2e41c7637239a15d306ef68fe9c4a5cdef9
2,147
java
Java
app/src/main/java/com/udacity/gradle/builditbigger/EndpointsAsyncTask.java
ramezmikhael/udacity-buildItBigger
5246cba8bb7751dd04b44af225ff632bfa8edb24
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/udacity/gradle/builditbigger/EndpointsAsyncTask.java
ramezmikhael/udacity-buildItBigger
5246cba8bb7751dd04b44af225ff632bfa8edb24
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/udacity/gradle/builditbigger/EndpointsAsyncTask.java
ramezmikhael/udacity-buildItBigger
5246cba8bb7751dd04b44af225ff632bfa8edb24
[ "Apache-2.0" ]
null
null
null
33.030769
127
0.672566
6,269
package com.udacity.gradle.builditbigger; import android.content.Context; import android.os.AsyncTask; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.udacity.gradle.builditbigger.backend.myApi.MyApi; import java.io.IOException; import java.lang.ref.WeakReference; /** * Created by RamezReda on 4/28/2018. */ /* * I would use AsyncTaskLoader instead but the rubric says AsyncTask! */ class EndpointsAsyncTask extends AsyncTask<Context, Void, String> { private static MyApi myApiService = null; private WeakReference<Context> context; private final PostExecuteListener mListener; public EndpointsAsyncTask(PostExecuteListener listener) { mListener = listener; } @Override protected String doInBackground(Context... params) { if(myApiService == null) { MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null) .setRootUrl("http://10.0.2.2:8080/_ah/api/") .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() { @Override public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException { abstractGoogleClientRequest.setDisableGZipContent(true); } }); myApiService = builder.build(); } context = new WeakReference<>(params[0]); try { return myApiService.getJoke().execute().getData(); } catch (IOException e) { return e.getMessage(); } } @Override protected void onPostExecute(String result) { mListener.executeFinished(result); } public interface PostExecuteListener { void executeFinished(String result); } }
3e0ec320082ee213dace41d3406947b75d29dfc4
364
java
Java
alien4cloud-tosca/src/main/java/org/alien4cloud/tosca/model/definitions/TimeInterval.java
opentelekomcloud/alien4cloud
9e7ded4590aea53000d1c1fc13e25b1b3a3d6cc5
[ "Apache-2.0" ]
76
2015-01-30T15:45:35.000Z
2022-02-16T05:37:43.000Z
alien4cloud-tosca/src/main/java/org/alien4cloud/tosca/model/definitions/TimeInterval.java
opentelekomcloud/alien4cloud
9e7ded4590aea53000d1c1fc13e25b1b3a3d6cc5
[ "Apache-2.0" ]
134
2015-01-05T12:00:56.000Z
2022-03-22T08:40:46.000Z
alien4cloud-tosca/src/main/java/org/alien4cloud/tosca/model/definitions/TimeInterval.java
opentelekomcloud/alien4cloud
9e7ded4590aea53000d1c1fc13e25b1b3a3d6cc5
[ "Apache-2.0" ]
83
2015-02-19T22:17:03.000Z
2022-01-27T13:35:06.000Z
22.75
133
0.766484
6,270
package org.alien4cloud.tosca.model.definitions; import lombok.Getter; import lombok.Setter; import java.util.Date; /** * Represents a time interval data structure in TOSCA. Note that Time interval is not a primitive type but is used in policy trigger. */ @Getter @Setter public class TimeInterval { private String startTime; private String endTime; }
3e0ec390635815f77cd622b3fda20ab1a21e44ed
6,071
java
Java
drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/rule/visitors/CopyExpressionVisitor.java
kedzie/drools-android
60bc9bddf66dad9cf48c48f56024abfb1744155f
[ "Apache-2.0" ]
6
2015-01-11T20:48:03.000Z
2021-08-14T09:59:48.000Z
drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/rule/visitors/CopyExpressionVisitor.java
kedzie/drools-android
60bc9bddf66dad9cf48c48f56024abfb1744155f
[ "Apache-2.0" ]
1
2015-06-14T21:10:43.000Z
2015-06-15T00:42:35.000Z
drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/rule/visitors/CopyExpressionVisitor.java
kedzie/drools-android
60bc9bddf66dad9cf48c48f56024abfb1744155f
[ "Apache-2.0" ]
2
2016-02-14T21:52:28.000Z
2017-04-04T20:27:34.000Z
37.94375
104
0.569264
6,271
/* * Copyright 2014 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.workbench.models.datamodel.rule.visitors; import java.util.HashMap; import java.util.Map; import org.drools.workbench.models.datamodel.rule.ExpressionCollection; import org.drools.workbench.models.datamodel.rule.ExpressionCollectionIndex; import org.drools.workbench.models.datamodel.rule.ExpressionField; import org.drools.workbench.models.datamodel.rule.ExpressionFieldVariable; import org.drools.workbench.models.datamodel.rule.ExpressionFormLine; import org.drools.workbench.models.datamodel.rule.ExpressionGlobalVariable; import org.drools.workbench.models.datamodel.rule.ExpressionMethod; import org.drools.workbench.models.datamodel.rule.ExpressionMethodParameter; import org.drools.workbench.models.datamodel.rule.ExpressionPart; import org.drools.workbench.models.datamodel.rule.ExpressionText; import org.drools.workbench.models.datamodel.rule.ExpressionUnboundFact; import org.drools.workbench.models.datamodel.rule.ExpressionVariable; import org.drools.workbench.models.datamodel.rule.ExpressionVisitor; public class CopyExpressionVisitor implements ExpressionVisitor { private ExpressionPart root; private ExpressionPart curr; public CopyExpressionVisitor() { } public ExpressionPart copy( ExpressionPart part ) { root = null; curr = null; part.accept( this ); return root; } public void visit( ExpressionPart part ) { throw new RuntimeException( "Can't copy an abstract class: " + ExpressionPart.class.getName() ); } public void visit( ExpressionField part ) { add( new ExpressionField( part.getName(), part.getClassType(), part.getGenericType(), part.getParametricType() ) ); moveNext( part ); } public void visit( ExpressionMethod part ) { ExpressionMethod method = new ExpressionMethod( part.getName(), part.getClassType(), part.getGenericType(), part.getParametricType() ); copyMethodParams( part, method ); add( method ); moveNext( part ); } public void visit( ExpressionVariable part ) { add( new ExpressionVariable( part.getName(), part.getFactType() ) ); moveNext( part ); } public void visit( ExpressionFieldVariable part ) { add( new ExpressionFieldVariable( part.getName(), part.getClassType() ) ); moveNext( part ); } public void visit( ExpressionUnboundFact part ) { add( new ExpressionUnboundFact( part.getFactType() ) ); moveNext( part ); } public void visit( ExpressionCollection part ) { add( new ExpressionCollection( part.getName(), part.getClassType(), part.getGenericType(), part.getParametricType() ) ); moveNext( part ); } public void visit( ExpressionCollectionIndex part ) { ExpressionCollectionIndex method = new ExpressionCollectionIndex( part.getName(), part.getClassType(), part.getGenericType(), part.getParametricType() ); copyMethodParams( part, method ); add( method ); moveNext( part ); } public void visit( ExpressionText part ) { add( new ExpressionText( part.getName(), part.getClassType(), part.getGenericType() ) ); moveNext( part ); } @Override public void visit( ExpressionMethodParameter part ) { add( new ExpressionMethodParameter( part.getName(), part.getClassType(), part.getGenericType() ) ); moveNext( part ); } public void visit( ExpressionGlobalVariable part ) { add( new ExpressionGlobalVariable( part.getName(), part.getClassType(), part.getGenericType(), part.getParametricType() ) ); moveNext( part ); } private void copyMethodParams( ExpressionMethod part, ExpressionMethod method ) { Map<String, ExpressionFormLine> params = new HashMap<String, ExpressionFormLine>(); for ( Map.Entry<String, ExpressionFormLine> entry : part.getParams().entrySet() ) { params.put( entry.getKey(), new ExpressionFormLine( entry.getValue() ) ); } method.setParams( params ); } private void moveNext( ExpressionPart ep ) { if ( ep.getNext() != null ) { ep.getNext().accept( this ); } } private void add( ExpressionPart p ) { if ( root == null ) { root = p; curr = p; } else { curr.setNext( p ); curr = p; } } }
3e0ec4180739ce44a4d16cc317610d2f07085b10
1,874
java
Java
back-end/src/main/java/it/polito/ai/es2/dtos/validators/TeamVmConstrainsValidator.java
P1100/Virtual-Labs
871fc1fa4296a67a932d893203686652fd6feff5
[ "MIT" ]
null
null
null
back-end/src/main/java/it/polito/ai/es2/dtos/validators/TeamVmConstrainsValidator.java
P1100/Virtual-Labs
871fc1fa4296a67a932d893203686652fd6feff5
[ "MIT" ]
null
null
null
back-end/src/main/java/it/polito/ai/es2/dtos/validators/TeamVmConstrainsValidator.java
P1100/Virtual-Labs
871fc1fa4296a67a932d893203686652fd6feff5
[ "MIT" ]
null
null
null
34.703704
104
0.622199
6,272
package it.polito.ai.es2.dtos.validators; import it.polito.ai.es2.entities.Team; import it.polito.ai.es2.entities.VM; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class TeamVmConstrainsValidator implements ConstraintValidator<TeamVmConstrains, VM> { @Override public void initialize(TeamVmConstrains constraintAnnotation) { } @Override public boolean isValid(VM vm, ConstraintValidatorContext context) { Team t = vm.getTeam(); if (t == null) return true; int countVcput = 0; int countDisk = 0; int countRam = 0; int countRunningVM = 0; int countTotVM = 0; for (VM v : vm.getTeam().getVms()) { countVcput += v.getVcpu(); countRam += v.getRam(); countDisk += v.getDisk(); countRunningVM += v.isActive() ? 1 : 0; countTotVM += 1; } StringBuilder sb = new StringBuilder(); if (countVcput > t.getMaxVcpu()) { sb.append(countVcput + " is bigger than team max vcpu " + t.getMaxVcpu() + " \n"); } if (countDisk > t.getMaxDisk()) { sb.append(countDisk + " is bigger than team max disk " + t.getMaxDisk() + " \n"); } if (countRam > t.getMaxRam()) { sb.append(countRam + " is bigger than team max ram " + t.getMaxRam() + " \n"); } if (countRunningVM > t.getMaxRunningVm()) { sb.append("Max running VM limit reached: " + countRunningVM + "/" + t.getMaxRunningVm() + " \n"); } if (countTotVM > t.getMaxTotVm()) { sb.append("Max VM limit reached: " + countTotVM + "/" + t.getMaxTotVm() + " \n"); } if (sb.length() > 0) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(sb.toString()).addConstraintViolation(); return false; } return true; } }
3e0ec46dfad315c8d84b72d56f9f61b836390776
4,037
java
Java
apps/cfm/src/test/java/org/onosproject/cfm/web/MepLtCreateCodecTest.java
tohotforice/onos
02f4c0eb0a193bfd22ca43767cffe68b54f22148
[ "Apache-2.0" ]
1,091
2015-01-06T11:10:40.000Z
2022-03-30T09:09:05.000Z
apps/cfm/src/test/java/org/onosproject/cfm/web/MepLtCreateCodecTest.java
tohotforice/onos
02f4c0eb0a193bfd22ca43767cffe68b54f22148
[ "Apache-2.0" ]
39
2015-02-13T19:58:32.000Z
2022-03-02T02:38:07.000Z
apps/cfm/src/test/java/org/onosproject/cfm/web/MepLtCreateCodecTest.java
tohotforice/onos
02f4c0eb0a193bfd22ca43767cffe68b54f22148
[ "Apache-2.0" ]
914
2015-01-05T19:42:35.000Z
2022-03-30T09:25:18.000Z
38.447619
94
0.667823
6,273
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.cfm.web; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.Before; import org.junit.Test; import org.onosproject.cfm.CfmCodecContext; import org.onosproject.incubator.net.l2monitoring.cfm.DefaultMepLtCreate; import org.onosproject.incubator.net.l2monitoring.cfm.MepLtCreate; import org.onosproject.incubator.net.l2monitoring.cfm.identifier.MepId; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.BitSet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class MepLtCreateCodecTest { ObjectMapper mapper; CfmCodecContext context; @Before public void setUp() throws Exception { mapper = new ObjectMapper(); context = new CfmCodecContext(); } @Test public void testDecodeMepLtCreateMepId() throws JsonProcessingException, IOException { String linktraceString = "{\"linktrace\": { " + "\"remoteMepId\": 20," + "\"defaultTtl\": 21," + "\"transmitLtmFlags\": \"use-fdb-only\"}}"; InputStream input = new ByteArrayInputStream( linktraceString.getBytes(StandardCharsets.UTF_8)); JsonNode cfg = mapper.readTree(input); MepLtCreate mepLtCreate = context .codec(MepLtCreate.class).decode((ObjectNode) cfg, context); assertNull(mepLtCreate.remoteMepAddress()); assertEquals(20, mepLtCreate.remoteMepId().id().shortValue()); assertEquals(21, mepLtCreate.defaultTtl().intValue()); assertEquals(BitSet.valueOf(new byte[]{1}), mepLtCreate.transmitLtmFlags()); } @Test public void testDecodeMepLtCreateInvalidTransmitLtmFlags() throws JsonProcessingException, IOException { String linktraceString = "{\"linktrace\": { " + "\"remoteMepId\": 20," + "\"transmitLtmFlags\": \"1\"}}"; InputStream input = new ByteArrayInputStream( linktraceString.getBytes(StandardCharsets.UTF_8)); JsonNode cfg = mapper.readTree(input); try { context.codec(MepLtCreate.class).decode((ObjectNode) cfg, context); } catch (IllegalArgumentException e) { assertEquals("Expecting value 'use-fdb-only' or '' " + "for transmitLtmFlags", e.getMessage()); } } @Test public void testEncodeMepLtCreate() { MepId mepId1 = MepId.valueOf((short) 1); MepLtCreate mepLtCreate1 = DefaultMepLtCreate .builder(mepId1) .defaultTtl((short) 20) .transmitLtmFlags(BitSet.valueOf(new byte[]{1})) .build(); ObjectMapper mapper = new ObjectMapper(); CfmCodecContext context = new CfmCodecContext(); ObjectNode node = mapper.createObjectNode(); node.set("linktrace", context.codec(MepLtCreate.class).encode(mepLtCreate1, context)); assertEquals("{\"linktrace\":{" + "\"remoteMepId\":1," + "\"defaultTtl\":20," + "\"transmitLtmFlags\":\"use-fdb-only\"}}", node.toString()); } }
3e0ec472286971487b69d72ccdd95c4a364a1a43
3,357
java
Java
src/tools/android/java/com/google/devtools/build/android/ziputils/DexMapper.java
c-parsons/bazel
c4893c39d747c7ac9152da76a9a626e7cdacb456
[ "Apache-2.0" ]
2
2018-02-20T12:56:23.000Z
2021-06-06T11:35:03.000Z
src/tools/android/java/com/google/devtools/build/android/ziputils/DexMapper.java
c-parsons/bazel
c4893c39d747c7ac9152da76a9a626e7cdacb456
[ "Apache-2.0" ]
14
2021-06-12T01:31:36.000Z
2021-06-23T21:33:54.000Z
src/tools/android/java/com/google/devtools/build/android/ziputils/DexMapper.java
turkdevops/bazel
0fda3b97907553cabadf04d7be7af89bf2ae4c05
[ "Apache-2.0" ]
3
2018-02-20T12:56:28.000Z
2021-06-12T01:25:03.000Z
34.255102
100
0.670539
6,274
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.android.ziputils; import com.google.devtools.common.options.Option; import com.google.devtools.common.options.OptionsBase; import com.google.devtools.common.options.OptionsParser; import java.util.List; /** * Command-line entry point for dex mapper utility, that maps an applications classes (given in * one or more input jar files), to one or more output jars, that may then be compiled separately. * This class performs command line parsing and delegates to an {@link SplitZip} instance. * * <p>The result of compiling each output archive can be consolidated using the dex reducer utility. */ public class DexMapper { /** * @param args the command line arguments */ public static void main(String[] args) { OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class); optionsParser.parseAndExitUponError(args); Options options = optionsParser.getOptions(Options.class); List<String> inputs = options.inputJars; List<String> outputs = options.outputJars; String filterFile = options.mainDexFilter; String resourceFile = options.outputResources; try { new SplitZip() .setVerbose(false) .useDefaultEntryDate() .addInputs(inputs) .addOutputs(outputs) .setMainClassListFile(filterFile) .setResourceFile(resourceFile) .run() .close(); } catch (Exception ex) { System.err.println("Caught exception" + ex.getMessage()); ex.printStackTrace(System.out); System.exit(1); } } /** * Commandline options. */ public static class Options extends OptionsBase { @Option(name = "input_jar", defaultValue = "null", category = "input", allowMultiple = true, abbrev = 'i', help = "Input file to read classes and jars from. Classes in " + " earlier files override those in later ones.") public List<String> inputJars; @Option(name = "output_jar", defaultValue = "null", category = "output", allowMultiple = true, abbrev = 'o', help = "Output file to write. Each argument is one shard. " + "Output files are filled in the order specified.") public List<String> outputJars; @Option(name = "main_dex_filter", defaultValue = "null", category = "input", abbrev = 'f', help = "List of classes to include in the first output file.") public String mainDexFilter; @Option(name = "output_resources", defaultValue = "null", category = "output", abbrev = 'r', help = "File to write the Java resources to.") public String outputResources; } }
3e0ec5abd15a303a7348876b5df9089f80c3d74b
19,433
java
Java
openjdk/langtools/src/share/classes/com/sun/tools/javac/file/Paths.java
liumapp/compiling-jvm
962f37e281f4d9ec03486d9380c43b7260790eaa
[ "Apache-2.0" ]
184
2015-01-04T03:38:20.000Z
2022-03-30T05:47:21.000Z
openjdk/langtools/src/share/classes/com/sun/tools/javac/file/Paths.java
liumapp/compiling-jvm
962f37e281f4d9ec03486d9380c43b7260790eaa
[ "Apache-2.0" ]
1
2016-01-17T09:18:17.000Z
2016-01-17T09:18:17.000Z
openjdk/langtools/src/share/classes/com/sun/tools/javac/file/Paths.java
liumapp/compiling-jvm
962f37e281f4d9ec03486d9380c43b7260790eaa
[ "Apache-2.0" ]
101
2015-01-16T23:46:31.000Z
2022-03-30T05:47:06.000Z
34.763864
91
0.587609
6,275
/* * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tools.javac.file; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.StringTokenizer; import java.util.zip.ZipFile; import javax.tools.JavaFileManager.Location; import com.sun.tools.javac.code.Lint; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Options; import static javax.tools.StandardLocation.*; import static com.sun.tools.javac.main.OptionName.*; /** This class converts command line arguments, environment variables * and system properties (in File.pathSeparator-separated String form) * into a boot class path, user class path, and source path (in * Collection<String> form). * * <p><b>This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> */ public class Paths { /** The context key for the todo list */ protected static final Context.Key<Paths> pathsKey = new Context.Key<Paths>(); /** Get the Paths instance for this context. * @param context the context * @return the Paths instance for this context */ public static Paths instance(Context context) { Paths instance = context.get(pathsKey); if (instance == null) instance = new Paths(context); return instance; } /** The log to use for warning output */ private Log log; /** Collection of command-line options */ private Options options; /** Handler for -Xlint options */ private Lint lint; /** Access to (possibly cached) file info */ private FSInfo fsInfo; protected Paths(Context context) { context.put(pathsKey, this); pathsForLocation = new HashMap<Location,Path>(16); setContext(context); } void setContext(Context context) { log = Log.instance(context); options = Options.instance(context); lint = Lint.instance(context); fsInfo = FSInfo.instance(context); } /** Whether to warn about non-existent path elements */ private boolean warn; private Map<Location, Path> pathsForLocation; private boolean inited = false; // TODO? caching bad? /** * rt.jar as found on the default bootclass path. If the user specified a * bootclasspath, null is used. */ private File defaultBootClassPathRtJar = null; /** * Is bootclasspath the default? */ private boolean isDefaultBootClassPath; Path getPathForLocation(Location location) { Path path = pathsForLocation.get(location); if (path == null) setPathForLocation(location, null); return pathsForLocation.get(location); } void setPathForLocation(Location location, Iterable<? extends File> path) { // TODO? if (inited) throw new IllegalStateException // TODO: otherwise reset sourceSearchPath, classSearchPath as needed Path p; if (path == null) { if (location == CLASS_PATH) p = computeUserClassPath(); else if (location == PLATFORM_CLASS_PATH) p = computeBootClassPath(); // sets isDefaultBootClassPath else if (location == ANNOTATION_PROCESSOR_PATH) p = computeAnnotationProcessorPath(); else if (location == SOURCE_PATH) p = computeSourcePath(); else // no defaults for other paths p = null; } else { if (location == PLATFORM_CLASS_PATH) { defaultBootClassPathRtJar = null; isDefaultBootClassPath = false; } p = new Path(); for (File f: path) p.addFile(f, warn); // TODO: is use of warn appropriate? } pathsForLocation.put(location, p); } public boolean isDefaultBootClassPath() { lazy(); return isDefaultBootClassPath; } protected void lazy() { if (!inited) { warn = lint.isEnabled(Lint.LintCategory.PATH); pathsForLocation.put(PLATFORM_CLASS_PATH, computeBootClassPath()); pathsForLocation.put(CLASS_PATH, computeUserClassPath()); pathsForLocation.put(SOURCE_PATH, computeSourcePath()); inited = true; } } public Collection<File> bootClassPath() { lazy(); return Collections.unmodifiableCollection(getPathForLocation(PLATFORM_CLASS_PATH)); } public Collection<File> userClassPath() { lazy(); return Collections.unmodifiableCollection(getPathForLocation(CLASS_PATH)); } public Collection<File> sourcePath() { lazy(); Path p = getPathForLocation(SOURCE_PATH); return p == null || p.size() == 0 ? null : Collections.unmodifiableCollection(p); } boolean isDefaultBootClassPathRtJar(File file) { return file.equals(defaultBootClassPathRtJar); } /** * Split a path into its elements. Empty path elements will be ignored. * @param path The path to be split * @return The elements of the path */ private static Iterable<File> getPathEntries(String path) { return getPathEntries(path, null); } /** * Split a path into its elements. If emptyPathDefault is not null, all * empty elements in the path, including empty elements at either end of * the path, will be replaced with the value of emptyPathDefault. * @param path The path to be split * @param emptyPathDefault The value to substitute for empty path elements, * or null, to ignore empty path elements * @return The elements of the path */ private static Iterable<File> getPathEntries(String path, File emptyPathDefault) { ListBuffer<File> entries = new ListBuffer<File>(); int start = 0; while (start <= path.length()) { int sep = path.indexOf(File.pathSeparatorChar, start); if (sep == -1) sep = path.length(); if (start < sep) entries.add(new File(path.substring(start, sep))); else if (emptyPathDefault != null) entries.add(emptyPathDefault); start = sep + 1; } return entries; } private class Path extends LinkedHashSet<File> { private static final long serialVersionUID = 0; private boolean expandJarClassPaths = false; private Set<File> canonicalValues = new HashSet<File>(); public Path expandJarClassPaths(boolean x) { expandJarClassPaths = x; return this; } /** What to use when path element is the empty string */ private File emptyPathDefault = null; public Path emptyPathDefault(File x) { emptyPathDefault = x; return this; } public Path() { super(); } public Path addDirectories(String dirs, boolean warn) { boolean prev = expandJarClassPaths; expandJarClassPaths = true; try { if (dirs != null) for (File dir : getPathEntries(dirs)) addDirectory(dir, warn); return this; } finally { expandJarClassPaths = prev; } } public Path addDirectories(String dirs) { return addDirectories(dirs, warn); } private void addDirectory(File dir, boolean warn) { if (!dir.isDirectory()) { if (warn) log.warning(Lint.LintCategory.PATH, "dir.path.element.not.found", dir); return; } File[] files = dir.listFiles(); if (files == null) return; for (File direntry : files) { if (isArchive(direntry)) addFile(direntry, warn); } } public Path addFiles(String files, boolean warn) { if (files != null) { for (File file : getPathEntries(files, emptyPathDefault)) addFile(file, warn); } return this; } public Path addFiles(String files) { return addFiles(files, warn); } public void addFile(File file, boolean warn) { if (contains(file)) { // discard duplicates return; } if (! fsInfo.exists(file)) { /* No such file or directory exists */ if (warn) { log.warning(Lint.LintCategory.PATH, "path.element.not.found", file); } super.add(file); return; } File canonFile = fsInfo.getCanonicalFile(file); if (canonicalValues.contains(canonFile)) { /* Discard duplicates and avoid infinite recursion */ return; } if (fsInfo.isFile(file)) { /* File is an ordinary file. */ if (!isArchive(file)) { /* Not a recognized extension; open it to see if it looks like a valid zip file. */ try { ZipFile z = new ZipFile(file); z.close(); if (warn) { log.warning(Lint.LintCategory.PATH, "unexpected.archive.file", file); } } catch (IOException e) { // FIXME: include e.getLocalizedMessage in warning if (warn) { log.warning(Lint.LintCategory.PATH, "invalid.archive.file", file); } return; } } } /* Now what we have left is either a directory or a file name conforming to archive naming convention */ super.add(file); canonicalValues.add(canonFile); if (expandJarClassPaths && fsInfo.isFile(file)) addJarClassPath(file, warn); } // Adds referenced classpath elements from a jar's Class-Path // Manifest entry. In some future release, we may want to // update this code to recognize URLs rather than simple // filenames, but if we do, we should redo all path-related code. private void addJarClassPath(File jarFile, boolean warn) { try { for (File f: fsInfo.getJarClassPath(jarFile)) { addFile(f, warn); } } catch (IOException e) { log.error("error.reading.file", jarFile, JavacFileManager.getMessage(e)); } } } private Path computeBootClassPath() { defaultBootClassPathRtJar = null; Path path = new Path(); String bootclasspathOpt = options.get(BOOTCLASSPATH); String endorseddirsOpt = options.get(ENDORSEDDIRS); String extdirsOpt = options.get(EXTDIRS); String xbootclasspathPrependOpt = options.get(XBOOTCLASSPATH_PREPEND); String xbootclasspathAppendOpt = options.get(XBOOTCLASSPATH_APPEND); path.addFiles(xbootclasspathPrependOpt); if (endorseddirsOpt != null) path.addDirectories(endorseddirsOpt); else path.addDirectories(System.getProperty("java.endorsed.dirs"), false); if (bootclasspathOpt != null) { path.addFiles(bootclasspathOpt); } else { // Standard system classes for this compiler's release. String files = System.getProperty("sun.boot.class.path"); path.addFiles(files, false); File rt_jar = new File("rt.jar"); for (File file : getPathEntries(files)) { if (new File(file.getName()).equals(rt_jar)) defaultBootClassPathRtJar = file; } } path.addFiles(xbootclasspathAppendOpt); // Strictly speaking, standard extensions are not bootstrap // classes, but we treat them identically, so we'll pretend // that they are. if (extdirsOpt != null) path.addDirectories(extdirsOpt); else path.addDirectories(System.getProperty("java.ext.dirs"), false); isDefaultBootClassPath = (xbootclasspathPrependOpt == null) && (bootclasspathOpt == null) && (xbootclasspathAppendOpt == null); return path; } private Path computeUserClassPath() { String cp = options.get(CLASSPATH); // CLASSPATH environment variable when run from `javac'. if (cp == null) cp = System.getProperty("env.class.path"); // If invoked via a java VM (not the javac launcher), use the // platform class path if (cp == null && System.getProperty("application.home") == null) cp = System.getProperty("java.class.path"); // Default to current working directory. if (cp == null) cp = "."; return new Path() .expandJarClassPaths(true) // Only search user jars for Class-Paths .emptyPathDefault(new File(".")) // Empty path elt ==> current directory .addFiles(cp); } private Path computeSourcePath() { String sourcePathArg = options.get(SOURCEPATH); if (sourcePathArg == null) return null; return new Path().addFiles(sourcePathArg); } private Path computeAnnotationProcessorPath() { String processorPathArg = options.get(PROCESSORPATH); if (processorPathArg == null) return null; return new Path().addFiles(processorPathArg); } /** The actual effective locations searched for sources */ private Path sourceSearchPath; public Collection<File> sourceSearchPath() { if (sourceSearchPath == null) { lazy(); Path sourcePath = getPathForLocation(SOURCE_PATH); Path userClassPath = getPathForLocation(CLASS_PATH); sourceSearchPath = sourcePath != null ? sourcePath : userClassPath; } return Collections.unmodifiableCollection(sourceSearchPath); } /** The actual effective locations searched for classes */ private Path classSearchPath; public Collection<File> classSearchPath() { if (classSearchPath == null) { lazy(); Path bootClassPath = getPathForLocation(PLATFORM_CLASS_PATH); Path userClassPath = getPathForLocation(CLASS_PATH); classSearchPath = new Path(); classSearchPath.addAll(bootClassPath); classSearchPath.addAll(userClassPath); } return Collections.unmodifiableCollection(classSearchPath); } /** The actual effective locations for non-source, non-class files */ private Path otherSearchPath; Collection<File> otherSearchPath() { if (otherSearchPath == null) { lazy(); Path userClassPath = getPathForLocation(CLASS_PATH); Path sourcePath = getPathForLocation(SOURCE_PATH); if (sourcePath == null) otherSearchPath = userClassPath; else { otherSearchPath = new Path(); otherSearchPath.addAll(userClassPath); otherSearchPath.addAll(sourcePath); } } return Collections.unmodifiableCollection(otherSearchPath); } /** Is this the name of an archive file? */ private boolean isArchive(File file) { String n = file.getName().toLowerCase(); return fsInfo.isFile(file) && (n.endsWith(".jar") || n.endsWith(".zip")); } /** * Utility method for converting a search path string to an array * of directory and JAR file URLs. * * Note that this method is called by apt and the DocletInvoker. * * @param path the search path string * @return the resulting array of directory and JAR file URLs */ public static URL[] pathToURLs(String path) { StringTokenizer st = new StringTokenizer(path, File.pathSeparator); URL[] urls = new URL[st.countTokens()]; int count = 0; while (st.hasMoreTokens()) { URL url = fileToURL(new File(st.nextToken())); if (url != null) { urls[count++] = url; } } if (urls.length != count) { URL[] tmp = new URL[count]; System.arraycopy(urls, 0, tmp, 0, count); urls = tmp; } return urls; } /** * Returns the directory or JAR file URL corresponding to the specified * local file name. * * @param file the File object * @return the resulting directory or JAR file URL, or null if unknown */ private static URL fileToURL(File file) { String name; try { name = file.getCanonicalPath(); } catch (IOException e) { name = file.getAbsolutePath(); } name = name.replace(File.separatorChar, '/'); if (!name.startsWith("/")) { name = "/" + name; } // If the file does not exist, then assume that it's a directory if (!file.isFile()) { name = name + "/"; } try { return new URL("file", "", name); } catch (MalformedURLException e) { throw new IllegalArgumentException(file.toString()); } } }
3e0ec5b5c5c05ca17d778a448fc9e2f726b129fc
3,898
java
Java
smart-metastore/src/main/java/org/smartdata/metastore/dao/UserInfoDao.java
lipppppp/SSM
ad0a487530cc87098e2e7ed33322365132818fc5
[ "Apache-2.0" ]
199
2017-04-19T06:37:24.000Z
2022-03-31T12:14:22.000Z
smart-metastore/src/main/java/org/smartdata/metastore/dao/UserInfoDao.java
lipppppp/SSM
ad0a487530cc87098e2e7ed33322365132818fc5
[ "Apache-2.0" ]
1,091
2017-04-14T07:09:55.000Z
2022-01-20T11:15:54.000Z
smart-metastore/src/main/java/org/smartdata/metastore/dao/UserInfoDao.java
lipppppp/SSM
ad0a487530cc87098e2e7ed33322365132818fc5
[ "Apache-2.0" ]
170
2017-04-14T03:45:30.000Z
2022-03-31T12:14:24.000Z
34.192982
98
0.728579
6,276
/** * 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.smartdata.metastore.dao; import org.smartdata.model.UserInfo; import org.smartdata.utils.StringUtil; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import javax.sql.DataSource; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; public class UserInfoDao { private static final String TABLE_NAME = "user_info"; private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public UserInfoDao(DataSource dataSource) { this.dataSource = dataSource; } public List<UserInfo> getAll() { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return jdbcTemplate.query("SELECT * FROM " + TABLE_NAME, new UserInfoRowMapper()); } public boolean containsUserName(String name) { return !list(name).isEmpty(); } private List<UserInfo> list(String name) { return new JdbcTemplate(dataSource) .query( "SELECT * FROM " + TABLE_NAME + " WHERE user_name = ?", new Object[] {name}, new UserInfoRowMapper()); } public UserInfo getByUserName(String name) { List<UserInfo> infos = list(name); return infos.isEmpty() ? null : infos.get(0); } public void delete(String name) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); final String sql = "DELETE FROM " + TABLE_NAME + " WHERE user_name = ?"; jdbcTemplate.update(sql, name); } public void insert(UserInfo userInfo) { SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource); simpleJdbcInsert.setTableName(TABLE_NAME); simpleJdbcInsert.execute(toMap(new UserInfo(userInfo.getUserName(), StringUtil.toSHA512String(userInfo.getUserPassword())))); } public boolean authentic (UserInfo userInfo) { UserInfo origin = getByUserName(userInfo.getUserName()); return origin.equals(userInfo); } public int newPassword(UserInfo userInfo) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); String sql = "UPDATE " + TABLE_NAME + " SET user_password = ? WHERE user_name = ?"; return jdbcTemplate.update(sql, StringUtil.toSHA512String(userInfo.getUserPassword()), userInfo.getUserName()); } public void deleteAll() { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); final String sql = "DELETE FROM " + TABLE_NAME; jdbcTemplate.execute(sql); } private Map<String, Object> toMap(UserInfo userInfo) { Map<String, Object> parameters = new HashMap<>(); parameters.put("user_name", userInfo.getUserName()); parameters.put("user_password", userInfo.getUserPassword()); return parameters; } class UserInfoRowMapper implements RowMapper<UserInfo> { @Override public UserInfo mapRow(ResultSet resultSet, int i) throws SQLException { return new UserInfo(resultSet.getString("user_name"), resultSet.getString("user_password")); } } }
3e0ec68e27b41c5b3523638fb9e4e8d3a1f72f99
3,019
java
Java
src/main/java/com/appian/intellij/k/settings/KServerSpec.java
austin-gartside/q-intellij-plugin
0d0853dde24d227924a62a854612b016924ae964
[ "Apache-2.0" ]
13
2018-08-07T13:12:08.000Z
2022-03-16T03:41:35.000Z
src/main/java/com/appian/intellij/k/settings/KServerSpec.java
austin-gartside/q-intellij-plugin
0d0853dde24d227924a62a854612b016924ae964
[ "Apache-2.0" ]
34
2018-07-17T02:38:22.000Z
2021-04-15T00:23:01.000Z
src/main/java/com/appian/intellij/k/settings/KServerSpec.java
austin-gartside/q-intellij-plugin
0d0853dde24d227924a62a854612b016924ae964
[ "Apache-2.0" ]
17
2018-08-18T08:32:13.000Z
2021-09-20T02:30:50.000Z
24.346774
138
0.666446
6,277
package com.appian.intellij.k.settings; import java.io.IOException; import java.util.Objects; import java.util.function.Function; import org.jetbrains.annotations.NotNull; import com.intellij.util.xmlb.annotations.Transient; import kx.c; public class KServerSpec implements Cloneable { private String name; private String host; private int port; private boolean useTLS; private String user; private String password; private String authDriverName; @SuppressWarnings("unused") //required for serialization public KServerSpec() { } public String getHost() { return host; } public int getPort() { return port; } public boolean useTLS() { return useTLS; } @Transient // do not persist in plain text xml public String getUser() { return user; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Transient // do not persist in plain text xml public String getPassword() { return password; } public String getId() { return (name == null ? "" : name) + " [" + (user == null || user.isEmpty() ? "" : user + "@") + host + ":" + port + "]"; } public String toString() { return getId(); } @SuppressWarnings("unused") // needed for serialization public void setHost(String host) { this.host = Objects.requireNonNull(host); } @SuppressWarnings("unused") // needed for serialization public void setPort(int port) { this.port = port; } @SuppressWarnings("unused") // needed for serialization public void setUseTLS(boolean useTLS) { this.useTLS = useTLS; } @SuppressWarnings({"unused", "WeakerAccess"}) // needed for serialization public void setUser(String user) { this.user = user; } @SuppressWarnings({"unused", "WeakerAccess"}) // needed for serialization public void setPassword(String password) { this.password = password; } public String getAuthDriverName() { return authDriverName; } public void setAuthDriverName(String authDriverName) { this.authDriverName = authDriverName; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } KServerSpec that = (KServerSpec)o; return Objects.equals(name, that.name) && port == that.port && useTLS == that.useTLS && host.equals(that.host) && Objects.equals(user, that.user) && Objects.equals(password, that.password) && Objects.equals(authDriverName, that.authDriverName); } @NotNull public c createConnection(Function<String, String> authenticator) throws c.KException, IOException { return new c(getHost(), getPort(), authenticator.apply(getUser() +":" + getPassword() + "@" + getHost() + ":" + getPort()), useTLS()); } @Override public KServerSpec clone() { try { return (KServerSpec)super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } }
3e0ec6d3489165888b1075c893a8cbbc62b3573e
2,956
java
Java
ocraft-s2client-protocol/src/test/java/com/github/ocraft/s2client/protocol/debug/DebugGameStateTest.java
Slugger2k/ocraft-s2client
128f62c15265b702f694ddae8fbff30ddb00dc53
[ "MIT" ]
45
2017-11-18T15:31:56.000Z
2022-02-20T11:26:16.000Z
ocraft-s2client-protocol/src/test/java/com/github/ocraft/s2client/protocol/debug/DebugGameStateTest.java
Slugger2k/ocraft-s2client
128f62c15265b702f694ddae8fbff30ddb00dc53
[ "MIT" ]
44
2017-11-25T07:49:12.000Z
2022-01-04T18:36:14.000Z
ocraft-s2client-protocol/src/test/java/com/github/ocraft/s2client/protocol/debug/DebugGameStateTest.java
Slugger2k/ocraft-s2client
128f62c15265b702f694ddae8fbff30ddb00dc53
[ "MIT" ]
23
2018-05-23T22:17:36.000Z
2021-11-12T20:03:10.000Z
48.459016
106
0.735453
6,278
package com.github.ocraft.s2client.protocol.debug; /*- * #%L * ocraft-s2client-protocol * %% * Copyright (C) 2017 - 2018 Ocraft Project * %% * 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. * #L% */ import SC2APIProtocol.Debug; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; class DebugGameStateTest { @ParameterizedTest(name = "\"{0}\" serializes to {1}") @MethodSource(value = "gameStateMappings") void serializesToSc2Api(DebugGameState gameState, Debug.DebugGameState expectedSc2ApiDebugGameState) { assertThat(gameState.toSc2Api()).isEqualTo(expectedSc2ApiDebugGameState); } private static Stream<Arguments> gameStateMappings() { return Stream.of( Arguments.of(DebugGameState.SHOW_MAP, Debug.DebugGameState.show_map), Arguments.of(DebugGameState.CONTROL_ENEMY, Debug.DebugGameState.control_enemy), Arguments.of(DebugGameState.FOOD, Debug.DebugGameState.food), Arguments.of(DebugGameState.FREE, Debug.DebugGameState.free), Arguments.of(DebugGameState.ALL_RESOURCES, Debug.DebugGameState.all_resources), Arguments.of(DebugGameState.GOD, Debug.DebugGameState.god), Arguments.of(DebugGameState.MINERALS, Debug.DebugGameState.minerals), Arguments.of(DebugGameState.GAS, Debug.DebugGameState.gas), Arguments.of(DebugGameState.COOLDOWN, Debug.DebugGameState.cooldown), Arguments.of(DebugGameState.TECH_TREE, Debug.DebugGameState.tech_tree), Arguments.of(DebugGameState.UPGRADE, Debug.DebugGameState.upgrade), Arguments.of(DebugGameState.FAST_BUILD, Debug.DebugGameState.fast_build)); } }
3e0ec6da8513a13b1f92a69a6e45082966da0353
1,949
java
Java
src/main/java/io/github/luisibanez/java/training/exercises/classes/Dog.java
luisibanez/java-in-a-nutshell
1f3b7d03f1acbcbe8d6b44ff8849ec8f4dab3784
[ "Apache-2.0" ]
null
null
null
src/main/java/io/github/luisibanez/java/training/exercises/classes/Dog.java
luisibanez/java-in-a-nutshell
1f3b7d03f1acbcbe8d6b44ff8849ec8f4dab3784
[ "Apache-2.0" ]
null
null
null
src/main/java/io/github/luisibanez/java/training/exercises/classes/Dog.java
luisibanez/java-in-a-nutshell
1f3b7d03f1acbcbe8d6b44ff8849ec8f4dab3784
[ "Apache-2.0" ]
null
null
null
18.214953
69
0.633658
6,279
/** * This class implements the abstraction of a Dog, man's best friend. */ package io.github.luisibanez.java.training.exercises.classes; public class Dog { private double weight; // measured in poinds private int age; // measured in integer years private double speed; // measured in meters per second private static double walkingSpeed = 1.4; public static double walkingSpeed() { return walkingSpeed; } public static void bark() { System.out.println("Whoof!"); } public static void whineForFood() { System.out.println("Feed me, or I will eat your sandwich!"); } public enum HairColor { BLACK, WHITE, YELLOW, BROWN } public enum HairLength { SHORT, LONG, VERYLONG } private HairColor hairColor; private HairLength hairLength; public HairColor hairColor() { return this.hairColor; } public HairLength hairLength() { return this.hairLength; } public double weight() { return this.weight; } public int age() { return this.age; } public void setHairColor(HairColor color) { this.hairColor = color; } public void setHairLength(HairLength length) { this.hairLength = length; } public void setAge(int age) { this.age = age; } public void setWeight(double weight) { this.weight = weight; } public void walk() { this.speed = walkingSpeed(); // set walking speed } public void sit() { this.speed = 0.0; // stop moving } public void sleep() { this.speed = 0.0; System.out.println("Zzzzzz"); } public void eat() { this.speed = 0.0; System.out.println("Munch, munch!"); } public void aDogsDay() { this.sleep(); this.whineForFood(); this.eat(); this.walk(); this.bark(); this.sit(); this.sleep(); } public double speed() { return this.speed; } public void setSpeed(double speed) { this.speed = speed; } }
3e0ec79b1701c1022e2f1638a39010de5c3630e6
217
java
Java
grpcmaven/src/test/java/com/himanshu/grpcmaven/GrpcmavenApplicationTests.java
himanshuntwk/spring-projects
af334dc20480826735666f59ae36ed30e253987d
[ "MIT" ]
null
null
null
grpcmaven/src/test/java/com/himanshu/grpcmaven/GrpcmavenApplicationTests.java
himanshuntwk/spring-projects
af334dc20480826735666f59ae36ed30e253987d
[ "MIT" ]
null
null
null
grpcmaven/src/test/java/com/himanshu/grpcmaven/GrpcmavenApplicationTests.java
himanshuntwk/spring-projects
af334dc20480826735666f59ae36ed30e253987d
[ "MIT" ]
null
null
null
15.5
60
0.792627
6,280
package com.himanshu.grpcmaven; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class GrpcmavenApplicationTests { @Test void contextLoads() { } }
3e0ec7ffceff559e249031136d69bd4d2543aa69
394
java
Java
app/src/main/java/pl/edu/amu/wmi/secretmessageapp/config/ConfigListener.java
dagi12/secret-message-app
6e715497cdb1ed18362599c098599904235e110a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/pl/edu/amu/wmi/secretmessageapp/config/ConfigListener.java
dagi12/secret-message-app
6e715497cdb1ed18362599c098599904235e110a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/pl/edu/amu/wmi/secretmessageapp/config/ConfigListener.java
dagi12/secret-message-app
6e715497cdb1ed18362599c098599904235e110a
[ "Apache-2.0" ]
null
null
null
19.238095
71
0.74505
6,281
package pl.edu.amu.wmi.secretmessageapp.config; import android.support.v4.app.Fragment; import pl.edu.amu.wmi.secretmessageapp.cipher.KeyAlias; /** * @author Eryk Mariankowski <ychag@example.com> on 30.11.17. */ public interface ConfigListener { void onRegistered(); void onMessageSaved(Fragment fragment); void onLoggedIn(); void onAuthChanged(KeyAlias forMethod); }
3e0ec8a6d56da34eccf1a68e3afc1c99da53d862
9,106
java
Java
src/main/java/com/pixmeow/mc/mod/togglelib/brand/SanYing.java
PixCraft-MC/ToggleLib
27fe03f77baeab5f45dda1cce7325b5a99166a92
[ "MIT" ]
null
null
null
src/main/java/com/pixmeow/mc/mod/togglelib/brand/SanYing.java
PixCraft-MC/ToggleLib
27fe03f77baeab5f45dda1cce7325b5a99166a92
[ "MIT" ]
null
null
null
src/main/java/com/pixmeow/mc/mod/togglelib/brand/SanYing.java
PixCraft-MC/ToggleLib
27fe03f77baeab5f45dda1cce7325b5a99166a92
[ "MIT" ]
null
null
null
34.104869
187
0.523501
6,282
package com.pixmeow.mc.mod.togglelib.brand; import com.pixmeow.mc.mod.togglelib.utils.Component.Button; import com.pixmeow.mc.mod.togglelib.utils.Component.Handler; import com.pixmeow.mc.mod.togglelib.utils.Component.Switch; import net.java.games.input.Component; import net.java.games.input.Controller; import net.java.games.input.Event; import org.jetbrains.annotations.NotNull; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; public class SanYing { public static String name = "San Ying Controller"; public static int version = 1; public static String author = "PixMeow"; public static Map<Component, com.pixmeow.mc.mod.togglelib.utils.Component> componentMap = new LinkedHashMap<>(); public static Component btnHorn; public static Component btnConstSpeed; public static Component btnAtsConfirm; public static Component swtDirection; public static ToggleStatus status = new ToggleStatus(); static Handler handler = new Handler(status); public static void init(@NotNull Controller controller) { // todo need check the status of the toggle input plug-in Handler.HandlerData.init(); for (Component component : controller.getComponents()) { switch (component.getIdentifier().getName()) { case "y": swtDirection = component; componentMap.put(component, new Switch(status, swtDirection)); break; case "0": btnHorn = component; componentMap.put(component, new Button(status, btnHorn, Button.Type.HORN)); break; case "1": btnAtsConfirm = component; componentMap.put(component, new Button(status, btnAtsConfirm, Button.Type.ATS)); break; case "2": btnConstSpeed = component; componentMap.put(component, new Button(status, btnConstSpeed, Button.Type.CONST)); break; case "6": case "7": case "8": case "9": handler.register(component); componentMap.put(component, handler); break; } } handler.finish(); } public static void on(Event event) { Component component = event.getComponent(); if (component.equals(btnHorn)) ((Button) componentMap.get(component)).on(event.getValue(), Button.Type.HORN); else if (component.equals(btnAtsConfirm)) ((Button) componentMap.get(component)).on(event.getValue(), Button.Type.ATS); else if (component.equals(btnConstSpeed)) ((Button) componentMap.get(component)).on(event.getValue(), Button.Type.CONST); else if (component.equals(swtDirection)) ((Switch) componentMap.get(component)).on(event.getValue()); else if (handler.hasComp(component)) { try { ((Handler) componentMap.get(component)).on(component); } catch (Exception e) { e.printStackTrace(); } } } public static class ToggleStatus { private static ToggleStatus current; Direction direction = Direction.Unknown; ToggleLevel level = ToggleLevel.Unknown; private boolean horn; private boolean ats; private boolean constSpeed; public ToggleStatus() { } private ToggleStatus(ToggleStatus old) { this.level = old.level; this.horn = old.horn; this.ats = old.ats; this.constSpeed = old.constSpeed; this.direction = old.direction; } public static ToggleStatus get() { return current; } public ToggleStatus copy() { return new ToggleStatus(this); } public boolean setConstSpeed(boolean constSpeed) { if (constSpeed) { this.constSpeed = !this.constSpeed; ToggleStatus.current = this; return true; } return false; } public boolean setLevel(com.pixmeow.mc.mod.togglelib.utils.Component.Handler.HandlerValue v) { if (v.value != ToggleLevel.Unknown.value && this.level.value != v.value) { this.level = ToggleLevel.getLevel(v.value); ToggleStatus.current = this; return true; } return false; } public boolean isHorn() { return horn; } public void setHorn(boolean horn) { this.horn = horn; ToggleStatus.current = this; } public boolean isAts() { return ats; } public void setAts(boolean ats) { this.ats = ats; ToggleStatus.current = this; } public boolean isConstSpeed() { return constSpeed; } public Direction getDirection() { return direction; } public void setDirection(Direction direction) { this.direction = direction; ToggleStatus.current = this; } public ToggleLevel getLevel() { return level; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ToggleStatus)) return false; ToggleStatus that = (ToggleStatus) o; return isHorn() == that.isHorn() && isAts() == that.isAts() && isConstSpeed() == that.isConstSpeed() && getDirection() == that.getDirection() && getLevel() == that.getLevel(); } @Override public int hashCode() { return Objects.hash(isHorn(), isAts(), isConstSpeed(), getDirection(), getLevel()); } @Override public String toString() { return "ToggleStatus{" + "horn=" + horn + ", ats=" + ats + ", constSpeed=" + constSpeed + ", direction=" + direction + ", level=" + level + '}'; } public enum Direction { Forward(-1, "Forward"), OFF(0, "Stop"), Backward(1, "Backward"), Unknown(-2, "Unknown"); int value; String name; Direction(int value, String name) { this.value = value; this.name = name; } public static Direction getDirector(float value) { for (Direction i : Direction.values()) { if (i.value == (int) value) return i; } return Unknown; } public String getName() { return name; } } public enum ToggleLevel { Unknown(-10, "--", Integer.parseInt("55555", 16)), EB(-9, "EB", Integer.parseInt("FF5555", 16)), B8(-8, "B8", Integer.parseInt("CA7A2C", 16)), B7(-7, "B7", Integer.parseInt("00A7e", 16)), B6(-6, "B6", Integer.parseInt("00A7e", 16)), B5(-5, "B5", Integer.parseInt("00A7e", 16)), B4(-4, "B4", Integer.parseInt("00A7e", 16)), B3(-3, "B3", Integer.parseInt("00A7e", 16)), B2(-2, "B2", Integer.parseInt("00A7e", 16)), B1(-1, "B1", Integer.parseInt("00A7e", 16)), N(0, "N", Integer.parseInt("00AA00", 16)), P1(1, "P1", Integer.parseInt("66BAB7", 16)), P2(2, "P2", Integer.parseInt("66BAB7", 16)), P3(3, "P3", Integer.parseInt("66BAB7", 16)), P4(4, "P4", Integer.parseInt("66BAB7", 16)), P5(5, "P5", Integer.parseInt("66BAB7", 16)); int value; String name; int color = Integer.parseInt("FFFFFF", 16); ToggleLevel(int value, String name) { this.value = value; this.name = name; } ToggleLevel(int value, String name, int color) { this(value, name); } public static ToggleLevel getLevel(int value) { for (ToggleLevel i : ToggleLevel.values()) { if (i.value == value) return i; } return Unknown; } public static ToggleLevel getLevel(com.pixmeow.mc.mod.togglelib.utils.Component.Handler.HandlerValue value) { for (ToggleLevel i : ToggleLevel.values()) { if (i.value == value.value) return i; } return Unknown; } public String getName() { return name; } public int getColor() { return color; } public int getValue() { return value; } } } }
3e0ec8b6751f6f2018fcb015af13ab6b626cf377
6,535
java
Java
Demo/Android/MpTestDemo/src/mo/android/common/FSurfaceConfigChooser.java
favedit/MoCross
2a550b3d41b0c33c44c66dd595e84b0e4ee95b08
[ "Apache-2.0" ]
3
2016-10-26T11:48:58.000Z
2017-10-24T18:35:17.000Z
Demo/Android/MpTestInstance/src/mo/android/common/FSurfaceConfigChooser.java
favedit/MoCross
2a550b3d41b0c33c44c66dd595e84b0e4ee95b08
[ "Apache-2.0" ]
null
null
null
Demo/Android/MpTestInstance/src/mo/android/common/FSurfaceConfigChooser.java
favedit/MoCross
2a550b3d41b0c33c44c66dd595e84b0e4ee95b08
[ "Apache-2.0" ]
6
2015-03-24T06:40:20.000Z
2019-03-18T13:56:13.000Z
45.699301
252
0.594032
6,283
package mo.android.common; import android.opengl.GLSurfaceView; import android.util.Log; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLDisplay; //============================================================ public class FSurfaceConfigChooser implements GLSurfaceView.EGLConfigChooser { private static final boolean DEBUG = false; private static String TAG = "FSurfaceConfigChooser"; protected int mRedSize; protected int mGreenSize; protected int mBlueSize; protected int mAlphaSize; protected int mDepthSize; protected int mStencilSize; private int[] mValue = new int[1]; private static int EGL_OPENGL_ES2_BIT = 4; private static int[] s_configAttribs2 = {EGL10.EGL_RED_SIZE, 4, EGL10.EGL_GREEN_SIZE, 4, EGL10.EGL_BLUE_SIZE, 4, EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL10.EGL_NONE}; //============================================================ public FSurfaceConfigChooser(int r, int g, int b, int a, int depth, int stencil){ mRedSize = r; mGreenSize = g; mBlueSize = b; mAlphaSize = a; mDepthSize = depth; mStencilSize = stencil; } //============================================================ @Override public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display){ int[] num_config = new int[1]; egl.eglChooseConfig(display, s_configAttribs2, null, 0, num_config); int numConfigs = num_config[0]; if(numConfigs <= 0){ throw new IllegalArgumentException("No configs match configSpec"); } EGLConfig[] configs = new EGLConfig[numConfigs]; egl.eglChooseConfig(display, s_configAttribs2, configs, numConfigs, num_config); if(DEBUG){ printConfigs(egl, display, configs); } return chooseConfig(egl, display, configs); } //============================================================ public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs){ for(EGLConfig config : configs){ int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0); int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); if(d < mDepthSize || s < mStencilSize){ continue; } int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0); int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0); int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0); int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0); if(r == mRedSize && g == mGreenSize && b == mBlueSize && a == mAlphaSize) return config; } return null; } //============================================================ private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue){ if(egl.eglGetConfigAttrib(display, config, attribute, mValue)){ return mValue[0]; } return defaultValue; } //============================================================ private void printConfigs(EGL10 egl, EGLDisplay display, EGLConfig[] configs){ int numConfigs = configs.length; Log.w(TAG, String.format("%d configurations", numConfigs)); for(int i = 0; i < numConfigs; i++){ Log.w(TAG, String.format("Configuration %d:\n", i)); printConfig(egl, display, configs[i]); } } //============================================================ private void printConfig(EGL10 egl, EGLDisplay display, EGLConfig config){ String[] names = {"EGL_BUFFER_SIZE", "EGL_ALPHA_SIZE", "EGL_BLUE_SIZE", "EGL_GREEN_SIZE", "EGL_RED_SIZE", "EGL_DEPTH_SIZE", "EGL_STENCIL_SIZE", "EGL_CONFIG_CAVEAT", "EGL_CONFIG_ID", "EGL_LEVEL", "EGL_MAX_PBUFFER_HEIGHT", "EGL_MAX_PBUFFER_PIXELS", "EGL_MAX_PBUFFER_WIDTH", "EGL_NATIVE_RENDERABLE", "EGL_NATIVE_VISUAL_ID", "EGL_NATIVE_VISUAL_TYPE", "EGL_PRESERVED_RESOURCES", "EGL_SAMPLES", "EGL_SAMPLE_BUFFERS", "EGL_SURFACE_TYPE", "EGL_TRANSPARENT_TYPE", "EGL_TRANSPARENT_RED_VALUE", "EGL_TRANSPARENT_GREEN_VALUE", "EGL_TRANSPARENT_BLUE_VALUE", "EGL_BIND_TO_TEXTURE_RGB", "EGL_BIND_TO_TEXTURE_RGBA", "EGL_MIN_SWAP_INTERVAL", "EGL_MAX_SWAP_INTERVAL", "EGL_LUMINANCE_SIZE", "EGL_ALPHA_MASK_SIZE", "EGL_COLOR_BUFFER_TYPE", "EGL_RENDERABLE_TYPE", "EGL_CONFORMANT"}; int[] attributes = {EGL10.EGL_BUFFER_SIZE, EGL10.EGL_ALPHA_SIZE, EGL10.EGL_BLUE_SIZE, EGL10.EGL_GREEN_SIZE, EGL10.EGL_RED_SIZE, EGL10.EGL_DEPTH_SIZE, EGL10.EGL_STENCIL_SIZE, EGL10.EGL_CONFIG_CAVEAT, EGL10.EGL_CONFIG_ID, EGL10.EGL_LEVEL, EGL10.EGL_MAX_PBUFFER_HEIGHT, EGL10.EGL_MAX_PBUFFER_PIXELS, EGL10.EGL_MAX_PBUFFER_WIDTH, EGL10.EGL_NATIVE_RENDERABLE, EGL10.EGL_NATIVE_VISUAL_ID, EGL10.EGL_NATIVE_VISUAL_TYPE, 0x3030, // EGL10.EGL_PRESERVED_RESOURCES, EGL10.EGL_SAMPLES, EGL10.EGL_SAMPLE_BUFFERS, EGL10.EGL_SURFACE_TYPE, EGL10.EGL_TRANSPARENT_TYPE, EGL10.EGL_TRANSPARENT_RED_VALUE, EGL10.EGL_TRANSPARENT_GREEN_VALUE, EGL10.EGL_TRANSPARENT_BLUE_VALUE, 0x3039, // EGL10.EGL_BIND_TO_TEXTURE_RGB, 0x303A, // EGL10.EGL_BIND_TO_TEXTURE_RGBA, 0x303B, // EGL10.EGL_MIN_SWAP_INTERVAL, 0x303C, // EGL10.EGL_MAX_SWAP_INTERVAL, EGL10.EGL_LUMINANCE_SIZE, EGL10.EGL_ALPHA_MASK_SIZE, EGL10.EGL_COLOR_BUFFER_TYPE, EGL10.EGL_RENDERABLE_TYPE, 0x3042 // EGL10.EGL_CONFORMANT }; int[] value = new int[1]; for(int i = 0; i < attributes.length; i++){ String name = names[i]; int attribute = attributes[i]; if(egl.eglGetConfigAttrib(display, config, attribute, value)){ Log.w(TAG, String.format(" %s: %d\n", name, value[0])); }else{ // Log.w(TAG, String.format(" %s: failed\n", name)); while(egl.eglGetError() != EGL10.EGL_SUCCESS) ; } } } }
3e0eca340423bf063a3f58b5faa7b200ee9ac617
1,729
java
Java
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/web/rulebuilder/service/RuleBuilderFieldService.java
nanthakumarm/BroadleafCommerce
3f74d1e9a840e6bce0208fa48d8111cc9663b25f
[ "Apache-2.0" ]
1
2020-04-03T20:49:40.000Z
2020-04-03T20:49:40.000Z
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/web/rulebuilder/service/RuleBuilderFieldService.java
nanthakumarm/BroadleafCommerce
3f74d1e9a840e6bce0208fa48d8111cc9663b25f
[ "Apache-2.0" ]
11
2020-06-15T21:05:08.000Z
2022-02-01T01:01:29.000Z
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/web/rulebuilder/service/RuleBuilderFieldService.java
trombka/blc-tmp
d0d12902509c872cb20d00771eebb03caea49bf1
[ "Apache-2.0" ]
2
2016-03-09T18:25:52.000Z
2020-04-03T20:49:44.000Z
33.25
117
0.779063
6,284
/* * #%L * BroadleafCommerce Open Admin Platform * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.broadleafcommerce.openadmin.web.rulebuilder.service; import org.broadleafcommerce.common.presentation.client.SupportedFieldType; import org.broadleafcommerce.openadmin.web.rulebuilder.dto.FieldDTO; import org.broadleafcommerce.openadmin.web.rulebuilder.dto.FieldData; import org.broadleafcommerce.openadmin.web.rulebuilder.dto.FieldWrapper; import java.util.List; /** * @author Elbert Bautista (elbertbautista) */ public interface RuleBuilderFieldService extends Cloneable { public String getName(); public FieldWrapper buildFields(); public FieldDTO getField(String fieldName); public SupportedFieldType getSupportedFieldType(String fieldName); public SupportedFieldType getSecondaryFieldType(String fieldName); public List<FieldData> getFields(); public void setFields(List<FieldData> fields); public RuleBuilderFieldService clone() throws CloneNotSupportedException; public void setRuleBuilderFieldServiceExtensionManager(RuleBuilderFieldServiceExtensionManager extensionManager); }
3e0eca469595c805b9c09216dfbfc8fdbb3d65c4
981
java
Java
src/main/java/edu/utah/ece/async/Verilog2LPN/CompilationOptions.java
MyersResearchGroup/Verilog2LPN
6b73adf2c7f6a789ba027884096b21d0fce4a7a9
[ "MIT" ]
null
null
null
src/main/java/edu/utah/ece/async/Verilog2LPN/CompilationOptions.java
MyersResearchGroup/Verilog2LPN
6b73adf2c7f6a789ba027884096b21d0fce4a7a9
[ "MIT" ]
null
null
null
src/main/java/edu/utah/ece/async/Verilog2LPN/CompilationOptions.java
MyersResearchGroup/Verilog2LPN
6b73adf2c7f6a789ba027884096b21d0fce4a7a9
[ "MIT" ]
null
null
null
20.4375
81
0.701325
6,285
package edu.utah.ece.async.Verilog2LPN; import java.io.File; import java.util.ArrayList; import java.util.List; public class CompilationOptions { private List<File> files; public CompilationOptions(String[] cmdline) throws CompilationOptionsException { this.files = new ArrayList<>(); for(String argument : cmdline) { // For now, assume all arguments are files File fileArgument = new File(argument); addFile(fileArgument); } } public CompilationOptions() { this.files = new ArrayList<>(); } public void addFile(File file) throws CompilationOptionsException { if(!file.exists()) { throw new CompilationOptionsException(); } if(file.isFile()) { files.add(file); } if(file.isDirectory()) { addDirectory(file); } } public void addDirectory(File directory) throws CompilationOptionsException { for(File file : directory.listFiles()) { addFile(file); } } public List<File> getFiles() { return this.files; } }
3e0ecadb98d21b28ed34010aab4e3398cbb77497
7,485
java
Java
client/oim-client-core/back/manager/ChatManage.java
oimchat/oim-fx
741af182a1ada70ce088bff13defcd85a2e145d9
[ "MIT" ]
379
2018-03-06T12:28:09.000Z
2022-03-27T02:42:05.000Z
client/oim-client-core/back/manager/ChatManage.java
justinelock/oim-fx
741af182a1ada70ce088bff13defcd85a2e145d9
[ "MIT" ]
2
2018-06-19T10:22:45.000Z
2018-11-17T03:16:11.000Z
client/oim-client-core/back/manager/ChatManage.java
justinelock/oim-fx
741af182a1ada70ce088bff13defcd85a2e145d9
[ "MIT" ]
130
2018-04-16T11:12:04.000Z
2022-03-01T07:55:15.000Z
30.55102
207
0.728925
6,286
package com.oim.core.business.manager; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.oim.core.business.box.PersonalBox; import com.oim.core.business.box.UserDataBox; import com.oim.core.business.sender.ChatSender; import com.oim.core.business.view.ChatListView; import com.only.common.result.Info; import com.only.general.annotation.parameter.Define; import com.only.net.action.Back; import com.only.net.data.action.DataBackActionAdapter; import com.onlyxiahui.app.base.AppContext; import com.onlyxiahui.app.base.component.AbstractManager; import com.onlyxiahui.im.bean.Group; import com.onlyxiahui.im.bean.UserData; import com.onlyxiahui.im.message.data.PageData; import com.onlyxiahui.im.message.data.chat.Content; import com.onlyxiahui.im.message.data.chat.history.UserChatHistoryData; import com.onlyxiahui.im.message.data.query.ChatQuery; /** * 对聊天相关的一些管理,如不同用户聊天界面 * * @author XiaHui * @date 2015年3月16日 下午1:37:57 */ public class ChatManage extends AbstractManager { Map<String, Boolean> userChatLoadMap = new HashMap<String, Boolean>(); Map<String, List<String>> messageIdMap = new HashMap<String, List<String>>(); Map<String, List<Content>> userChatMap = new HashMap<String, List<Content>>(); Map<String, List<GroupChatData>> groupChatMap = new HashMap<String, List<GroupChatData>>(); public ChatManage(AppContext appContext) { super(appContext); initEvent(); } private void initEvent() { } public void putUserMessageId(String userId, String messageId) { List<String> ids = messageIdMap.get(userId); if (null == ids) { ids = new ArrayList<String>(); messageIdMap.put(userId, ids); } ids.add(0, messageId); int size = ids.size(); if (size > 50) { ids.remove(size - 1); } } public void putUserCaht(String userId, Content content) { List<Content> list = userChatMap.get(userId); if (list == null) { list = new ArrayList<Content>(); userChatMap.put(userId, list); } list.add(content); } public void putGroupCaht(String groupId, UserData userData, Content content) { List<GroupChatData> list = groupChatMap.get(groupId); if (list == null) { list = new ArrayList<GroupChatData>(); groupChatMap.put(groupId, list); } list.add(new GroupChatData(userData, content)); } public boolean isGroupChatShowing(String groupId) { ChatListView chatListView = appContext.getSingleView(ChatListView.class); return chatListView.isGroupChatShowing(groupId); } public boolean isUserChatShowing(String userId) { ChatListView chatListView = appContext.getSingleView(ChatListView.class); return chatListView.isUserChatShowing(userId); } public void userChat(boolean isOwn, UserData userData, Content content) { ChatListView chatListView = appContext.getSingleView(ChatListView.class); chatListView.userChat(isOwn, userData, content); } public void groupChat(Group group, UserData userData, Content content) { ChatListView chatListView = appContext.getSingleView(ChatListView.class); chatListView.groupChat(group, userData, content); } public void showCahtFrame(UserData userData) { ChatListView chatListView = appContext.getSingleView(ChatListView.class); chatListView.show(userData); chatListView.setVisible(true); PromptManage pm = this.appContext.getManager(PromptManage.class); pm.showUserHeadPulse(userData.getId(), false);// 停止头像跳动 pm.remove(userData.getId());// 系统托盘停止跳动 } public void showCahtFrame(Group group) { ChatListView chatListView = appContext.getSingleView(ChatListView.class); chatListView.show(group); chatListView.setVisible(true); PromptManage pm = this.appContext.getManager(PromptManage.class); pm.showGroupHeadPulse(group.getId(), false);// 停止头像跳动 pm.remove(group.getId());// 系统托盘停止跳动 } public void showUserCaht(UserData userData) { String userId = userData.getId(); List<Content> list = userChatMap.remove(userData.getId()); ChatManage chatManage = this.appContext.getManager(ChatManage.class); if (null != userData && list != null && !list.isEmpty()) { for (Content content : list) { chatManage.userChat(false, userData, content); } } if (!userChatLoadMap.containsKey(userId)) { List<String> ids = messageIdMap.get(userId); if (null == ids || ids.size() < 50) { showChatHistory(userData); } userChatLoadMap.put(userId, true); ChatSender cs = appContext.getSender(ChatSender.class); cs.updateUserOfflineMessageToRead(userData.getId()); } } public void showChatHistory(final UserData userData) { DataBackActionAdapter dataBackAction = new DataBackActionAdapter() { @Override public void lost() { } @Override public void timeOut() { } @Back public void back(Info info, @Define("sendUserId") String sendUserId, @Define("receiveUserId") String receiveUserId, @Define("contents") List<UserChatHistoryData> contents, @Define("page") PageData page) { if (info.isSuccess()) { if (null != contents && !contents.isEmpty()) { ChatListView view = appContext.getSingleView(ChatListView.class); List<String> ids = messageIdMap.get(userData.getId()); Map<String, String> idMap = new HashMap<String, String>(); if (null != ids) { for (String id : ids) { idMap.put(id, id); } } List<UserChatHistoryData> list = new ArrayList<UserChatHistoryData>(); for (UserChatHistoryData content : contents) { String messageKey = content.getMessageKey(); if (!idMap.containsKey(messageKey)) { list.add(content); } } view.userChatHistory(userData, list); } } } }; PersonalBox pb=appContext.getBox(PersonalBox.class); UserData sendUser = pb.getUserData(); PageData page = new PageData(); page.setPageSize(50); page.setPageNumber(1); ChatSender ds = appContext.getSender(ChatSender.class); ds.queryUserChatLog(sendUser.getId(), userData.getId(), new ChatQuery(), page, dataBackAction); // ChatManage chatManage = appContext.getManage(ChatManage.class); // chatManage.showCahtFrame(userData); } public void showGroupCaht(Group group) { List<GroupChatData> list = groupChatMap.remove(group.getId()); ChatManage chatManage = this.appContext.getManager(ChatManage.class); if (null != group && list != null && !list.isEmpty()) { for (GroupChatData ucd : list) { chatManage.groupChat(group, ucd.userData, ucd.content); } } } public void showShake(String sendUserId) { } class GroupChatData { private UserData userData; private Content content; public GroupChatData(UserData userData, Content content) { this.userData = userData; this.content = content; } public UserData getUserData() { return userData; } public void setUserData(UserData userData) { this.userData = userData; } public Content getContent() { return content; } public void setContent(Content content) { this.content = content; } } public void updateGroupUserList(String groupId) { ChatListView chatListView = appContext.getSingleView(ChatListView.class); chatListView.updateGroupUserList(groupId); } public void doShake(String sendUserId) { UserDataBox ub = appContext.getBox(UserDataBox.class); UserData userData = ub.getUserData(sendUserId); if (null == userData) {// 如果发送抖动的不是好友,暂时不支持抖动 return; } ChatListView chatListView = appContext.getSingleView(ChatListView.class); chatListView.doShake(userData); } }
3e0ecb9dc92f79041771cb1dc70dc5dd2d9219fa
467
java
Java
SungBeanPark/java/Homework/third/src/Homework8.java
sknyuki/Homework
21c4ba9c93a93cc3840efc239d372f892b5bfba7
[ "MIT" ]
37
2021-12-20T11:24:09.000Z
2022-03-23T11:49:50.000Z
SungBeanPark/java/Homework/third/src/Homework8.java
sknyuki/Homework
21c4ba9c93a93cc3840efc239d372f892b5bfba7
[ "MIT" ]
39
2021-12-22T17:35:55.000Z
2022-03-15T13:17:01.000Z
SungBeanPark/java/Homework/third/src/Homework8.java
sknyuki/Homework
21c4ba9c93a93cc3840efc239d372f892b5bfba7
[ "MIT" ]
33
2021-12-20T11:24:33.000Z
2022-01-25T02:00:49.000Z
29.1875
63
0.438972
6,287
public class Homework8 { public static void main(String[] args) { // 1 ~ 100까지 숫자를 순회환다. // 2 ~ 10 사이의 랜덤한 숫자를 선택하고 이 숫자의 배수를 출력해보도록 한다 int min = 2; int max = 10; int rand = (int)(Math.random()* (max - min + 1) + min); System.out.println("랜덤숫자 = " + rand); for (int i = 1; i <= 100; i++) { if (i % rand == 0) { System.out.println("배수 출력 = " + i); } } } }
3e0eccdb48a204209b8870a730ec6a4211d714a1
2,409
java
Java
jme3-bullet/src/common/java/com/jme3/bullet/animation/RagdollCollisionListener.java
Markil3/jmonkeyengine
49383a5c0c80557b99275bbe0d9af42e7527bd03
[ "BSD-3-Clause" ]
3,139
2015-01-01T10:18:09.000Z
2022-03-31T12:51:24.000Z
jme3-bullet/src/common/java/com/jme3/bullet/animation/RagdollCollisionListener.java
Markil3/jmonkeyengine
49383a5c0c80557b99275bbe0d9af42e7527bd03
[ "BSD-3-Clause" ]
1,385
2015-01-01T00:21:56.000Z
2022-03-31T18:36:04.000Z
jme3-bullet/src/common/java/com/jme3/bullet/animation/RagdollCollisionListener.java
Markil3/jmonkeyengine
49383a5c0c80557b99275bbe0d9af42e7527bd03
[ "BSD-3-Clause" ]
1,306
2015-01-01T10:18:11.000Z
2022-03-27T06:38:48.000Z
42.263158
80
0.756746
6,288
/* * Copyright (c) 2009-2018 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.bullet.animation; import com.jme3.bullet.collision.PhysicsCollisionEvent; import com.jme3.bullet.collision.PhysicsCollisionObject; /** * Interface to receive notifications whenever a linked rigid body in a * DynamicAnimControl collides with another physics object. * <p> * This class is shared between JBullet and Native Bullet. * * @author Nehon */ public interface RagdollCollisionListener { /** * Invoked when a collision involving a linked rigid body occurs. * * @param physicsLink the physics link that collided (not null) * @param object the collision object that collided with the bone (not null) * @param event other event details (not null) */ void collide(PhysicsLink physicsLink, PhysicsCollisionObject object, PhysicsCollisionEvent event); }
3e0ecd0b3d61c884f79185a58c3146450b782e0a
2,687
java
Java
message-builder-hl7v3-release-pcs_mr2009_r02_04_03/src/main/java/ca/infoway/messagebuilder/model/pcs_mr2009_r02_04_03/claims/ficr_mt510201ca/AdjudicationResultReasonBean.java
CanadaHealthInfoway/message-builder
a24b368b6ad7330ce8e1319e6bae130cea981818
[ "Apache-2.0" ]
1
2022-03-09T12:17:41.000Z
2022-03-09T12:17:41.000Z
message-builder-hl7v3-release-pcs_mr2009_r02_04_03/src/main/java/ca/infoway/messagebuilder/model/pcs_mr2009_r02_04_03/claims/ficr_mt510201ca/AdjudicationResultReasonBean.java
CanadaHealthInfoway/message-builder
a24b368b6ad7330ce8e1319e6bae130cea981818
[ "Apache-2.0" ]
null
null
null
message-builder-hl7v3-release-pcs_mr2009_r02_04_03/src/main/java/ca/infoway/messagebuilder/model/pcs_mr2009_r02_04_03/claims/ficr_mt510201ca/AdjudicationResultReasonBean.java
CanadaHealthInfoway/message-builder
a24b368b6ad7330ce8e1319e6bae130cea981818
[ "Apache-2.0" ]
null
null
null
33.17284
101
0.720506
6,289
/** * Copyright 2013 Canada Health Infoway, 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. * * Author: $LastChangedBy$ * Last modified: $LastChangedDate$ * Revision: $LastChangedRevision$ */ /* This class was auto-generated by the message builder generator tools. */ package ca.infoway.messagebuilder.model.pcs_mr2009_r02_04_03.claims.ficr_mt510201ca; import ca.infoway.messagebuilder.annotation.Hl7PartTypeMapping; import ca.infoway.messagebuilder.annotation.Hl7XmlMapping; import ca.infoway.messagebuilder.datatype.ED; import ca.infoway.messagebuilder.datatype.impl.EDImpl; import ca.infoway.messagebuilder.datatype.lang.EncapsulatedData; import ca.infoway.messagebuilder.model.MessagePartBean; import ca.infoway.messagebuilder.model.pcs_mr2009_r02_04_03.claims.merged.Trigger2Bean; import java.util.ArrayList; import java.util.List; @Hl7PartTypeMapping({"FICR_MT510201CA.AdjudicationResultReason"}) public class AdjudicationResultReasonBean extends MessagePartBean implements AdjudicationCodeChoice { private static final long serialVersionUID = 20190731L; private ED<EncapsulatedData> value = new EDImpl<EncapsulatedData>(); private List<Trigger2Bean> trigger = new ArrayList<Trigger2Bean>(); /** * <p>Business Name: Adjudicated Result Reason</p> * * <p>Relationship: * FICR_MT510201CA.AdjudicationResultReason.value</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ @Hl7XmlMapping({"value"}) public EncapsulatedData getValue() { return this.value.getValue(); } /** * <p>Business Name: Adjudicated Result Reason</p> * * <p>Relationship: * FICR_MT510201CA.AdjudicationResultReason.value</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ public void setValue(EncapsulatedData value) { this.value.setValue(value); } /** * <p>Relationship: * FICR_MT510201CA.AdjudicationCodeChoice.trigger</p> * * <p>Conformance/Cardinality: REQUIRED (0-10)</p> */ @Hl7XmlMapping({"trigger"}) public List<Trigger2Bean> getTrigger() { return this.trigger; } }
3e0ece2abb7ef7cfbde335d2ce4bd7f67157109c
225
java
Java
spring/spring_demo/src/main/java/com/sunbc/beans/generic/di/UserService.java
shaniaoyizu/review
cc6e7f3c457acc68c4f38b81862dd847d957c67f
[ "Apache-2.0" ]
null
null
null
spring/spring_demo/src/main/java/com/sunbc/beans/generic/di/UserService.java
shaniaoyizu/review
cc6e7f3c457acc68c4f38b81862dd847d957c67f
[ "Apache-2.0" ]
1
2020-07-14T14:30:05.000Z
2020-07-14T14:30:05.000Z
spring/spring_demo/src/main/java/com/sunbc/beans/generic/di/UserService.java
shaniaoyizu/review
cc6e7f3c457acc68c4f38b81862dd847d957c67f
[ "Apache-2.0" ]
null
null
null
15
52
0.72
6,290
package com.sunbc.beans.generic.di; import org.springframework.stereotype.Service; /** * Created on 2020-06-26 * * @author sunbc * @Describe * @since */ @Service public class UserService extends BaseService<User> { }
3e0ece74e2bd7a60911caa7a53c3501c1cf71451
990
java
Java
src/main/java/com/ntc/rabbit/MainApp.java
congnghia0609/ntc-jrabb
875e1dbcb2c858bb69f455d9ec47863989f5a498
[ "Apache-2.0" ]
1
2020-05-25T16:02:07.000Z
2020-05-25T16:02:07.000Z
src/main/java/com/ntc/rabbit/MainApp.java
congnghia0609/ntc-jrabb
875e1dbcb2c858bb69f455d9ec47863989f5a498
[ "Apache-2.0" ]
2
2020-10-15T05:26:01.000Z
2021-02-23T17:03:39.000Z
src/main/java/com/ntc/rabbit/MainApp.java
congnghia0609/ntc-jrabbit
875e1dbcb2c858bb69f455d9ec47863989f5a498
[ "Apache-2.0" ]
null
null
null
17.368421
75
0.628283
6,291
/* * Copyright 2017 nghiatc. * * 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.ntc.rabbit; /** * * @author nghiatc * @since May 3, 2017 */ public class MainApp { /** * @param args the command line arguments */ public static void main(String[] args) { try { System.out.println("Run test done!!!..."); } catch (Exception e) { e.printStackTrace(); } } }
3e0eceaab6b0c1318c2b54b4341ce4b621123435
3,711
java
Java
scouter2-collector/src/test/java/scouter2/collector/infrastructure/repository/local/LocalProfileRepoTest.java
scouter-project/scouter2-prototyping
6cdc604da2e033ed2e4371101accdd4990ffb8b5
[ "Apache-2.0" ]
1
2022-03-26T15:20:04.000Z
2022-03-26T15:20:04.000Z
scouter2-collector/src/test/java/scouter2/collector/infrastructure/repository/local/LocalProfileRepoTest.java
scouter-project/scouter2-prototyping
6cdc604da2e033ed2e4371101accdd4990ffb8b5
[ "Apache-2.0" ]
2
2020-06-18T16:34:32.000Z
2021-01-21T00:10:17.000Z
scouter2-collector/src/test/java/scouter2/collector/infrastructure/repository/local/LocalProfileRepoTest.java
scouter-project/scouter2-prototyping
6cdc604da2e033ed2e4371101accdd4990ffb8b5
[ "Apache-2.0" ]
null
null
null
38.666667
113
0.719289
6,292
/* * Copyright 2019. The Scouter2 Authors. * * @https://github.com/scouter-project/scouter2 * * 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 scouter2.collector.infrastructure.repository.local; import com.google.protobuf.ByteString; import org.eclipse.collections.api.list.MutableList; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import scouter2.collector.LocalRepoTest; import scouter2.collector.domain.profile.Profile; import scouter2.common.util.ThreadUtil; import scouter2.fixture.ProfileFixture; import scouter2.proto.ProfileP; import scouter2.proto.StepTypeP; import scouter2.testsupport.T; import static org.assertj.core.api.Assertions.assertThat; /** * @author Gun Lee (lyhxr@example.com) on 07/09/2019 */ public class LocalProfileRepoTest extends LocalRepoTest { String applicationId = "testapp"; @Autowired LocalProfileRepo repo; @Test public void add_and_get_profiles() { Profile profile = ProfileFixture.getOne(); repo.add(profile); MutableList<ProfileP> found = repo.findProfiles(profile.getProto().getTxid().toByteArray(), Integer.MAX_VALUE).getProfiles(); assertThat(found.size()).isEqualTo(1); assertThat(found.get(0).getSteps()).isEqualTo(profile.getProto().getSteps()); assertThat(found.get(0).getStepTypes(0)).isEqualTo(profile.getProto().getStepTypes(0)); } @Test public void add_and_get_multi_profiles() { ByteString sameTxid = T.xlogIdAsBs(); Profile profile0 = ProfileFixture.getOne(); Profile profile11 = ProfileFixture.getOne(sameTxid, StepTypeP.DUMP); Profile profile12 = ProfileFixture.getOne(sameTxid, StepTypeP.APICALL); repo.add(profile0); repo.add(profile11); repo.add(profile12); MutableList<ProfileP> found = repo.findProfiles(sameTxid.toByteArray(), Integer.MAX_VALUE).getProfiles(); assertThat(found.size()).isEqualTo(2); assertThat(found.get(0).getSteps()).isEqualTo(profile11.getProto().getSteps()); assertThat(found.get(0).getStepTypes(0)).isEqualTo(profile11.getProto().getStepTypes(0)); assertThat(found.get(1).getStepTypes(0)).isEqualTo(profile12.getProto().getStepTypes(0)); } @Test public void add_and_get_multi_profiles_after_offset_index_buffer_flush() { ByteString sameTxid = T.xlogIdAsBs(); Profile profile0 = ProfileFixture.getOne(); Profile profile11 = ProfileFixture.getOne(sameTxid, StepTypeP.DUMP); Profile profile12 = ProfileFixture.getOne(sameTxid, StepTypeP.APICALL); repo.add(profile0); repo.add(profile11); repo.add(profile12); ThreadUtil.sleep(550); MutableList<ProfileP> found = repo.findProfiles(sameTxid.toByteArray(), Integer.MAX_VALUE).getProfiles(); assertThat(found.size()).isEqualTo(2); assertThat(found.get(0).getSteps()).isEqualTo(profile11.getProto().getSteps()); assertThat(found.get(0).getStepTypes(0)).isEqualTo(profile11.getProto().getStepTypes(0)); assertThat(found.get(1).getStepTypes(0)).isEqualTo(profile12.getProto().getStepTypes(0)); } }
3e0ecebba42ced9e2ce780ebd8a8c27df0af650d
8,560
java
Java
core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CoordinateOperationContext.java
aplocon/sis
6717af92dcf8ffec8aab7c2ba8809a60c4bc50fd
[ "Apache-2.0" ]
null
null
null
core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CoordinateOperationContext.java
aplocon/sis
6717af92dcf8ffec8aab7c2ba8809a60c4bc50fd
[ "Apache-2.0" ]
null
null
null
core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CoordinateOperationContext.java
aplocon/sis
6717af92dcf8ffec8aab7c2ba8809a60c4bc50fd
[ "Apache-2.0" ]
1
2019-02-25T14:09:55.000Z
2019-02-25T14:09:55.000Z
41.352657
134
0.699766
6,293
/* * 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.sis.referencing.operation; import java.io.Serializable; import java.util.function.Predicate; import org.opengis.metadata.extent.Extent; import org.opengis.metadata.extent.GeographicBoundingBox; import org.opengis.referencing.operation.CoordinateOperation; import org.apache.sis.metadata.iso.extent.DefaultGeographicBoundingBox; import org.apache.sis.metadata.iso.extent.DefaultExtent; import org.apache.sis.metadata.iso.extent.Extents; import org.apache.sis.internal.util.CollectionsExt; import org.apache.sis.util.ArgumentChecks; import org.apache.sis.util.resources.Errors; /** * Optional information about the context in which a requested coordinate operation will be used. * The context can provide information such as: * * <ul> * <li>The geographic area where the transformation will be used.</li> * <li>The desired accuracy. A coarser accuracy may allow SIS to choose a faster transformation method.</li> * </ul> * * While optional, those information can help {@link DefaultCoordinateOperationFactory} * to choose the most suitable coordinate transformation between two CRS. * * <div class="note"><b>Example:</b> * if a transformation from NAD27 to WGS84 is requested without providing context, then Apache SIS will return the * transformation applicable to the widest North American surface. But if the user provides a context saying that * he wants to transform coordinates in Texas, then Apache SIS may return another coordinate transformation with * different {@linkplain org.apache.sis.referencing.datum.BursaWolfParameters Bursa-Wolf parameters} more suitable * to Texas, but not suitable to the rest of North-America. * </div> * * {@code CoordinateOperationContext} is part of the API used by SIS for implementing the <cite>late binding</cite> * model. See {@linkplain org.apache.sis.referencing.operation package javadoc} for a note on early binding versus * late binding implementations. * * @author Martin Desruisseaux (Geomatys) * @version 1.0 * @since 0.7 * @module * * @todo Should also take the country of a {@link java.util.Locale}. The EPSG database contains ISO2 and ISO3 * identifiers that we can use. */ public class CoordinateOperationContext implements Serializable { /** * For cross-version compatibility. */ private static final long serialVersionUID = -6944460471653277973L; /** * The spatio-temporal area of interest, or {@code null} if none. */ private Extent areaOfInterest; /** * The desired accuracy in metres, or 0 for the best accuracy available. * See {@link #getDesiredAccuracy()} for more details about what we mean by <cite>"best accuracy"</cite>. */ private double desiredAccuracy; /** * Creates a new context with no area of interest and the best accuracy available. */ public CoordinateOperationContext() { } /** * Creates a new context with the given area of interest and desired accuracy. * * @param area the area of interest, or {@code null} if none. * @param accuracy the desired accuracy in metres, or 0 for the best accuracy available. * See {@link #getDesiredAccuracy()} for more details about what we mean by <cite>"best accuracy"</cite>. */ public CoordinateOperationContext(final Extent area, final double accuracy) { ArgumentChecks.ensurePositive("accuracy", accuracy); areaOfInterest = area; desiredAccuracy = accuracy; } /** * Creates an operation context for the given area of interest, which may be null. * This is a convenience method for a frequently-used operation. * * @param areaOfInterest the area of interest, or {@code null} if none. * @return the operation context, or {@code null} if the given bounding box was null. * * @since 1.0 */ public static CoordinateOperationContext fromBoundingBox(final GeographicBoundingBox areaOfInterest) { if (areaOfInterest != null) { if (areaOfInterest instanceof DefaultGeographicBoundingBox && ((DefaultGeographicBoundingBox) areaOfInterest).isEmpty()) { throw new IllegalArgumentException(Errors.format(Errors.Keys.EmptyArgument_1, "areaOfInterest")); } final CoordinateOperationContext context = new CoordinateOperationContext(); context.setAreaOfInterest(areaOfInterest); return context; } return null; } /** * Returns the spatio-temporal area of interest, or {@code null} if none. * * @return the spatio-temporal area of interest, or {@code null} if none. * * @see Extents#getGeographicBoundingBox(Extent) */ public Extent getAreaOfInterest() { return areaOfInterest; } /** * Sets the spatio-temporal area of interest, or {@code null} if none. * * @param area the spatio-temporal area of interest, or {@code null} if none. */ public void setAreaOfInterest(Extent area) { if (area != null) { area = new DefaultExtent(area); } areaOfInterest = area; } /** * Sets the geographic component of the area of interest, or {@code null} if none. * This convenience method set the bounding box into the spatio-temporal {@link Extent}. * * <p>The reverse operation can be done with <code>{@linkplain Extents#getGeographicBoundingBox(Extent) * Extents.getGeographicBoundingBox}({@linkplain #getAreaOfInterest()})</code>.</p> * * @param area the geographic area of interest, or {@code null} if none. */ public void setAreaOfInterest(final GeographicBoundingBox area) { areaOfInterest = setGeographicBoundingBox(areaOfInterest, area); } /** * Sets the given geographic bounding box in the given extent. */ static Extent setGeographicBoundingBox(Extent areaOfInterest, final GeographicBoundingBox bbox) { if (areaOfInterest != null) { final DefaultExtent ex = DefaultExtent.castOrCopy(areaOfInterest); ex.setGeographicElements(CollectionsExt.singletonOrEmpty(bbox)); areaOfInterest = ex; } else if (bbox != null) { areaOfInterest = new DefaultExtent(null, bbox, null, null); } return areaOfInterest; } /** * Returns the desired accuracy in metres. * A value of 0 means to search for the most accurate operation. * * <p>When searching for the most accurate operation, SIS considers only the operations specified by the authority. * For example the <cite>Molodensky</cite> method is a better datum shift approximation than <cite>Abridged Molodensky</cite>. * But if all coordinate operations defined by the authority use the Abridged Molodensky method, then SIS will ignore * the Molodensky one.</p> * * @return the desired accuracy in metres. */ public double getDesiredAccuracy() { return desiredAccuracy; } /** * Sets the desired accuracy in metres. * A value of 0 means to search for the most accurate operation. * See {@link #getDesiredAccuracy()} for more details about what we mean by <cite>"most accurate"</cite>. * * @param accuracy the desired accuracy in metres. */ public void setDesiredAccuracy(final double accuracy) { ArgumentChecks.ensurePositive("accuracy", accuracy); desiredAccuracy = accuracy; } /** * Returns a filter that can be used for applying additional restrictions on the coordinate operation. * * @todo Not yet implemented. */ Predicate<CoordinateOperation> getOperationFilter() { return null; } }
3e0ecf3d84ca32483a59301c8f82db5878eb830b
491
java
Java
cloud-seckill/src/main/java/com/fairy/cloud/seckill/domain/OmsOrderDetail.java
ITLULU/fairy-cloud
64c156c96cfbdff91c5483010d3cea12a1bbe2ef
[ "Apache-2.0" ]
null
null
null
cloud-seckill/src/main/java/com/fairy/cloud/seckill/domain/OmsOrderDetail.java
ITLULU/fairy-cloud
64c156c96cfbdff91c5483010d3cea12a1bbe2ef
[ "Apache-2.0" ]
null
null
null
cloud-seckill/src/main/java/com/fairy/cloud/seckill/domain/OmsOrderDetail.java
ITLULU/fairy-cloud
64c156c96cfbdff91c5483010d3cea12a1bbe2ef
[ "Apache-2.0" ]
null
null
null
21.347826
68
0.733198
6,294
package com.fairy.cloud.seckill.domain; import com.fairy.cloud.mbg.model.po.OmsOrder; import com.fairy.cloud.mbg.model.po.OmsOrderItem; import java.util.List; /** * 包含订单商品信息的订单详情 */ public class OmsOrderDetail extends OmsOrder { private List<OmsOrderItem> orderItemList; public List<OmsOrderItem> getOrderItemList() { return orderItemList; } public void setOrderItemList(List<OmsOrderItem> orderItemList) { this.orderItemList = orderItemList; } }
3e0ecfa591309c745b2ad44942d9a45ce2587d99
3,413
java
Java
org.bridgedb.uri.sql/test/org/bridgedb/uri/UriMapperBySysCodeIdTest.java
fehrhart/BridgeDb
bfbecc042b205a604bddf27aa16db154afba2143
[ "Apache-2.0" ]
22
2015-02-05T11:12:51.000Z
2022-02-04T01:09:13.000Z
org.bridgedb.uri.sql/test/org/bridgedb/uri/UriMapperBySysCodeIdTest.java
fehrhart/BridgeDb
bfbecc042b205a604bddf27aa16db154afba2143
[ "Apache-2.0" ]
154
2015-04-07T11:04:27.000Z
2022-03-29T12:02:00.000Z
org.bridgedb.uri.sql/test/org/bridgedb/uri/UriMapperBySysCodeIdTest.java
fehrhart/BridgeDb
bfbecc042b205a604bddf27aa16db154afba2143
[ "Apache-2.0" ]
25
2015-01-05T18:31:18.000Z
2022-02-25T10:13:52.000Z
36.698925
115
0.679754
6,295
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.bridgedb.uri; import java.util.HashSet; import java.util.Set; import org.bridgedb.uri.api.MappingsBySysCodeId; import org.hamcrest.Matcher; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.*; import static org.hamcrest.Matchers.*; /** * * @author Christian */ @Tag("mysql") public abstract class UriMapperBySysCodeIdTest extends UriListenerTest{ private static final String EMPTY_GRAPH = ""; /** * Test of mapUri method, of class UriMapper. */ @Test public void testMapUri_sourceUri_lensId_tgtUriPatterns() throws Exception { report("MapUri_sourceUri_lensId_tgtUriPatterns"); String sourceUri = map3Uri3; String lensId = null; Set<String> tgtUriPatterns = new HashSet<String>(); tgtUriPatterns.add(stringPattern2); tgtUriPatterns.add(stringPattern3); MappingsBySysCodeId results = uriMapper.mapUriBySysCodeId(sourceUri, lensId, EMPTY_GRAPH, tgtUriPatterns); Set<String> sysCodes = results.getSysCodes(); assertThat(sysCodes, not(hasItem(DataSource1.getSystemCode()))); assertThat(sysCodes, hasItem(DataSource2.getSystemCode())); assertThat(sysCodes, hasItem(DataSource3.getSystemCode())); Set<String> ids = results.getIds(DataSource2.getSystemCode()); assertThat(ids, hasItem(ds2Id3)); Set<String> uris = results.getUris(DataSource2.getSystemCode(), ds2Id3); assertThat(uris, hasItem(map3Uri2)); //assertFalse(results.contains(map3Uri1)); //assertTrue(results.contains(map3Uri2)); //assertFalse(results.contains(map3Uri2a)); //assertTrue(results.contains(map3Uri3)); //assertFalse(results.contains(map2Uri2)); //assertFalse(results.contains(map1Uri3)); } /** * Test of mapUri method, of class UriMapper. */ @Test public void testMapUri_sourceUris_lensId_tgtUriPatterns() throws Exception { report("MapUri_sourceUri_lensId_tgtUriPatterns"); Set<String> sourceUris = new HashSet<String>(); sourceUris.add(map3Uri3); sourceUris.add(map1Uri3); String lensId = null; Set<String> tgtUriPatterns = new HashSet<String>(); tgtUriPatterns.add(stringPattern2); MappingsBySysCodeId results = uriMapper.mapUriBySysCodeId(sourceUris, lensId, EMPTY_GRAPH, tgtUriPatterns); Set<String> sysCodes = results.getSysCodes(); assertThat(sysCodes, not(hasItem(DataSource1.getSystemCode()))); assertThat(sysCodes, hasItem(DataSource2.getSystemCode())); assertThat(sysCodes, not(hasItem(DataSource3.getSystemCode()))); Set<String> ids = results.getIds(DataSource2.getSystemCode()); assertThat(ids, (Matcher) hasItem(ds2Id3)); Set<String> uris = results.getUris(DataSource2.getSystemCode(), ds2Id3); assertThat(uris, (Matcher) hasItem(map3Uri2)); //assertFalse(results.contains(map3Uri1)); //assertTrue(results.contains(map3Uri2)); //assertFalse(results.contains(map3Uri2a)); //assertTrue(results.contains(map3Uri3)); //assertFalse(results.contains(map2Uri2)); //assertFalse(results.contains(map1Uri3)); } }
3e0ed0810aef4f18305ccef11ef026f6e1f10dc9
193
java
Java
app/src/main/java/com/loicortola/chat/android/listener/AsyncTaskController.java
loicortola/training-chat-android
20688d660ef3bffe55ab4d1c67754e598fba4437
[ "MIT" ]
null
null
null
app/src/main/java/com/loicortola/chat/android/listener/AsyncTaskController.java
loicortola/training-chat-android
20688d660ef3bffe55ab4d1c67754e598fba4437
[ "MIT" ]
null
null
null
app/src/main/java/com/loicortola/chat/android/listener/AsyncTaskController.java
loicortola/training-chat-android
20688d660ef3bffe55ab4d1c67754e598fba4437
[ "MIT" ]
null
null
null
19.3
45
0.715026
6,296
package com.loicortola.chat.android.listener; /** * Created by loic on 29/04/2016. */ public interface AsyncTaskController<T> { void onPreExecute(); void onPostExecute(T success); }
3e0ed3a27487ab6c71e3719a8ef3e2e60fd6e8bb
513
java
Java
sharding-table/src/main/java/com/liuawei/sharding/trade/service/UserOrderServiceImpl.java
liu-a-wei/sharding-jdbc
05957f47f6eb3b7156433c3b212f620c142703f6
[ "Apache-2.0" ]
null
null
null
sharding-table/src/main/java/com/liuawei/sharding/trade/service/UserOrderServiceImpl.java
liu-a-wei/sharding-jdbc
05957f47f6eb3b7156433c3b212f620c142703f6
[ "Apache-2.0" ]
null
null
null
sharding-table/src/main/java/com/liuawei/sharding/trade/service/UserOrderServiceImpl.java
liu-a-wei/sharding-jdbc
05957f47f6eb3b7156433c3b212f620c142703f6
[ "Apache-2.0" ]
null
null
null
24.428571
63
0.795322
6,297
package com.liuawei.sharding.trade.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.liuawei.sharding.trade.dao.UserOrderDao; import com.liuawei.sharding.trade.model.UserOrder; @Service public class UserOrderServiceImpl implements UserOrderService{ @Autowired private UserOrderDao userOrderDao; @Override public int insertOrder(UserOrder userOrder) { return userOrderDao.insertOrder(userOrder); } }
3e0ed3f059fa916f5d34fb93ef89a9177387aa99
10,471
java
Java
impl/src/main/java/com/force/formula/commands/FunctionDateValue.java
ksosine/formula-engine
6180693dbe2a0e80c20413febeeb0280d9438974
[ "BSD-3-Clause" ]
9
2021-10-14T17:14:26.000Z
2022-03-28T23:45:33.000Z
impl/src/main/java/com/force/formula/commands/FunctionDateValue.java
ksosine/formula-engine
6180693dbe2a0e80c20413febeeb0280d9438974
[ "BSD-3-Clause" ]
5
2021-11-01T21:15:37.000Z
2022-01-16T16:55:00.000Z
impl/src/main/java/com/force/formula/commands/FunctionDateValue.java
ksosine/formula-engine
6180693dbe2a0e80c20413febeeb0280d9438974
[ "BSD-3-Clause" ]
7
2021-10-19T16:37:01.000Z
2022-03-28T23:45:36.000Z
44.939914
179
0.644924
6,298
package com.force.formula.commands; import java.lang.reflect.Type; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Deque; import java.util.regex.Pattern; import com.force.formula.BindingObserver; import com.force.formula.FormulaCommand; import com.force.formula.FormulaCommandType.AllowedContext; import com.force.formula.FormulaCommandType.SelectorSection; import com.force.formula.FormulaContext; import com.force.formula.FormulaDateException; import com.force.formula.FormulaDateTime; import com.force.formula.FormulaEngine; import com.force.formula.FormulaException; import com.force.formula.FormulaProperties; import com.force.formula.FormulaRuntimeContext; import com.force.formula.impl.FormulaAST; import com.force.formula.impl.IllegalArgumentTypeException; import com.force.formula.impl.JsValue; import com.force.formula.impl.TableAliasRegistry; import com.force.formula.impl.WrongNumberOfArgumentsException; import com.force.formula.sql.SQLPair; import com.force.formula.util.FormulaDateUtil; import com.force.formula.util.FormulaI18nUtils; import com.force.formula.util.FormulaTextUtil; import com.force.i18n.BaseLocalizer; /** * Describe your class here. * * @author dchasman * @since 144 */ @AllowedContext(section = SelectorSection.DATE_TIME, isOffline=true) public class FunctionDateValue extends FormulaCommandInfoImpl implements FormulaCommandValidator { public static final String FUNCTION_NAME = "DATEVALUE"; protected static final String JS_FORMAT_TEMPLATE = "new Date(new Date(%s).setUTCHours(0,0,0,0))"; public FunctionDateValue() { super(FUNCTION_NAME); FormulaCommandInfoRegistry.addBindingObserver(timeZoneIdBindingObserver); FormulaCommandInfoRegistry.addBindingObserver(timeZoneOffsetBindingObserver); } @Override public FormulaCommand getCommand(FormulaAST node, FormulaContext context) { Type inputDataType = ((FormulaAST)node.getFirstChild()).getDataType(); boolean isDateTime = inputDataType == FormulaDateTime.class; return new OperatorDateValueFormulaCommand(this, isDateTime); } @Override public SQLPair getSQL(FormulaAST node, FormulaContext context, String[] args, String[] guards, TableAliasRegistry registry) { Type inputDataType = ((FormulaAST)node.getFirstChild()).getDataType(); String sql; String guard; if (inputDataType == FormulaDateTime.class) { sql = getSqlHooks(context).sqlConvertDateTimeToDate(args[0], USERS_TIMEZONE_ID_MARKER, USERS_TIMEZONE_OFFSET_MARKER); guard = SQLPair.generateGuard(guards, null); } else { sql = String.format(getSqlHooks(context).sqlToDateIso(), args[0]); FormulaAST child = (FormulaAST)node.getFirstChild(); if (child != null && child.isLiteral() && child.getDataType() == String.class) { if (OperatorDateValueFormulaCommand.isDateValid(ConstantString.getStringValue(child, true))) { // no guard needed guard = SQLPair.generateGuard(guards, null); } else { // we know it's false guard = SQLPair.generateGuard(guards, "0=0"); sql = String.format(getSqlHooks(context).sqlToDate(), "NULL"); } } else { // Guard protects against malformed dates as strings. It assumes all months have 31 days. Validates invalid months. Accepts years from 0000-9999. guard = SQLPair .generateGuard( guards, String.format( getSqlHooks(context).sqlDateValueGuard(), args[0])); /*Other 2 options of guards, probably when we get versioning we can switch to either one of these: Option1: guards against invalid months not in 1-12 and invalid days in a month (>31). Assumes all months have 31 days. So Apr 31 and Feb 30 are not guarded. Year 0000 is guarded. " NOT REGEXP_LIKE (%s, '^(000[1-9]|00[1-9]\\d|0[[1-9]\\d\\d|[1-9]\\d{3})-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$')", Option 2: most robust guard, this will guard invalid dates like april 31 or february 30. The only problem with this one is that it assumes february always has 29 days, so will not catch as invalid date feb 29 in a non leap year. " NOT REGEXP_LIKE (%s, '^(000[1-9]|00[1-9]\\d|0[[1-9]\\d\\d|[1-9]\\d{3})-(((0?[1-9]|1[012])-(0?[1-9]|[12][0-9]))|((0?[13578]|1[02])-3[01])|((0?[469]|11)-30))$')", */ } } return new SQLPair(sql, guard); } @Override public Type validate(FormulaAST node, FormulaContext context, FormulaProperties properties) throws FormulaException { if (node.getNumberOfChildren() != 1) { throw new WrongNumberOfArgumentsException(node.getText(), 1, node); } Type inputDataType = ((FormulaAST)node.getFirstChild()).getDataType(); if (inputDataType != FormulaDateTime.class && inputDataType != String.class && inputDataType != RuntimeType.class) { throw new IllegalArgumentTypeException(node.getText()); } return inputDataType == RuntimeType.class ? inputDataType : Date.class; } // sets timezone IDs during the late binding stage ("__TZ_ID__" -> "America/Los_Angeles") private static final BindingObserver timeZoneIdBindingObserver = new BindingObserver() { @Override public String bind(String value) { Calendar cal = FormulaI18nUtils.getLocalizer().getCalendar(BaseLocalizer.LOCAL); String timezone = FormulaEngine.getHooks().getDbTimeZoneID(cal.getTimeZone()); return FormulaTextUtil.replaceSimple(value, FunctionDateValue.USERS_TIMEZONE_ID_MARKER, timezone); } }; private static final BindingObserver timeZoneOffsetBindingObserver = new BindingObserver() { @Override public String bind(String value) { int offsetInHours = FunctionDateValue.getUserTimezoneOffsetHours(); return FormulaTextUtil.replaceSimple(value, FunctionDateValue.USERS_TIMEZONE_OFFSET_MARKER, String.valueOf(offsetInHours)); } }; public static int getUserTimezoneOffsetHours() { Calendar c = FormulaI18nUtils.getLocalizer().getCalendar(BaseLocalizer.LOCAL); return c.getTimeZone().getRawOffset() / (1000 * 60 * 60); } @Override public JsValue getJavascript(FormulaAST node, FormulaContext context, JsValue[] args) throws FormulaException { Type inputDataType = ((FormulaAST)node.getFirstChild()).getDataType(); if (inputDataType == FormulaDateTime.class) { return JsValue.forNonNullResult("new Date("+args[0] + ".setUTCHours(0,0,0,0))", args); } else if (inputDataType == BigDecimal.class) { return JsValue.forNonNullResult(String.format(JS_FORMAT_TEMPLATE, jsToNum(context,args[0].js)), args); } else { return JsValue.forNonNullResult(String.format(JS_FORMAT_TEMPLATE, args[0].js),args); } } private static final String USERS_TIMEZONE_ID_MARKER = "__TZ_ID__"; private static final String USERS_TIMEZONE_OFFSET_MARKER = "__TZ_OFFSET__"; public static class OperatorDateValueFormulaCommand extends AbstractFormulaCommand { private static final long serialVersionUID = 1L; private final boolean isDateTime; public OperatorDateValueFormulaCommand(FormulaCommandInfo formulaCommandInfo, boolean isDateTime) { super(formulaCommandInfo); this.isDateTime = isDateTime; } @Override public boolean isDeterministic(FormulaContext context) { // When we convert from dateTime to date, we use User's TZ, so not deterministic. return !isDateTime; } @Override public void execute(FormulaRuntimeContext context, Deque<Object> stack) throws FormulaException { Object input = stack.pop(); Date value = null; if (input != null && input != ConstantString.NullString) { if (input instanceof FormulaDateTime) { // Convert from FormulaDateTime to Date FormulaDateTime dateTimeInput = (FormulaDateTime)input; if (dateTimeInput != null) { Date date = dateTimeInput.getDate(); if (date != null) { Calendar c = FormulaI18nUtils.getLocalizer().getCalendar(BaseLocalizer.LOCAL); value = FormulaDateUtil.truncateDateToOwnersGmtMidnight(c.getTimeZone(), date); } } } else { try { value = parseDate(checkStringType(input)); } catch (FormulaDateException x) { FormulaEngine.getHooks().handleFormulaDateException(x); } } } stack.push(value); } protected static boolean isDateValid(String date) { try { parseDate(date); return true; } catch (FormulaDateException x) { return false; } } private static Pattern DATE_PATTERN = Pattern.compile("\\d{4}-.*"); // Convert from string of the form "YYYY-MM-DD" to Date protected static Date parseDate(String input) throws FormulaDateException { if (FormulaEngine.getHooks().isFormulaContainerCompiling()) { return null; // dummy values during compile won't work } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); try { // Do a pre-check for 4-digit year (setLenient does not require this) if (!DATE_PATTERN.matcher(input).matches()) { throw new FormulaDateException( "Invalid year for DATEVALUE function"); } return dateFormat.parse(input); } catch (ParseException x) { throw new FormulaDateException(x); } } } }
3e0ed4ee1190a2b46eff271c3d530b9f6f730fcb
1,329
java
Java
src/java/dbDriver/OracleDriver.java
MixRedo/Cesfam
21455b3f92afb8995f828d8ff5fb6b5e25c8b86a
[ "MIT" ]
null
null
null
src/java/dbDriver/OracleDriver.java
MixRedo/Cesfam
21455b3f92afb8995f828d8ff5fb6b5e25c8b86a
[ "MIT" ]
null
null
null
src/java/dbDriver/OracleDriver.java
MixRedo/Cesfam
21455b3f92afb8995f828d8ff5fb6b5e25c8b86a
[ "MIT" ]
null
null
null
34.973684
106
0.6614
6,299
/* * 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 dbDriver; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import util.PropertyReader; /** * * @author Daniel */ public final class OracleDriver { public static Connection getConnection() throws SQLException, IOException{ Connection connection = null; PropertyReader reader = new PropertyReader(); String host = reader.getPropValuesByName("host"); String port = reader.getPropValuesByName("port"); String sid = reader.getPropValuesByName("sid"); String username = reader.getPropValuesByName("username"); String password = reader.getPropValuesByName("password"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); String connectionString = String.format("jdbc:oracle:thin:@%1$s:%2$s:%3$s", host, port, sid); connection = DriverManager.getConnection(connectionString,username,password); } catch (ClassNotFoundException | SQLException e) { } return connection; } }
3e0ed54b14adc106c96710cedf6509249fdd8567
332
java
Java
src/slogo/compiler/math/ArcTangentCommand.java
puzzler7/parser_CS308
963273515ed3ecc632288032d2b7a7a0fa4bddac
[ "MIT" ]
null
null
null
src/slogo/compiler/math/ArcTangentCommand.java
puzzler7/parser_CS308
963273515ed3ecc632288032d2b7a7a0fa4bddac
[ "MIT" ]
null
null
null
src/slogo/compiler/math/ArcTangentCommand.java
puzzler7/parser_CS308
963273515ed3ecc632288032d2b7a7a0fa4bddac
[ "MIT" ]
null
null
null
19.529412
60
0.728916
6,300
package slogo.compiler.math; import slogo.compiler.parser.Command; public class ArcTangentCommand extends Command { public ArcTangentCommand(String declaration) { super(declaration); desiredArgs = 1; } @Override public double executeCommand() { return Math.toDegrees(Math.atan(args.get(0).execute())); } }
3e0ed55075c055196aa74ed9801c5c522e22e4e0
969
java
Java
app/src/main/java/com/github/kaism/watchlist/utils/ListItemTouchHelper.java
kaism/watchlist
5c9f8cf96578bd7279ba529e266edd4e50a51423
[ "BSL-1.0" ]
2
2020-11-08T17:03:23.000Z
2020-11-16T08:07:32.000Z
app/src/main/java/com/github/kaism/watchlist/utils/ListItemTouchHelper.java
kaism/watchlist
5c9f8cf96578bd7279ba529e266edd4e50a51423
[ "BSL-1.0" ]
null
null
null
app/src/main/java/com/github/kaism/watchlist/utils/ListItemTouchHelper.java
kaism/watchlist
5c9f8cf96578bd7279ba529e266edd4e50a51423
[ "BSL-1.0" ]
1
2020-11-08T17:03:24.000Z
2020-11-08T17:03:24.000Z
26.189189
147
0.775026
6,301
package com.github.kaism.watchlist.utils; import androidx.annotation.NonNull; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.RecyclerView; public class ListItemTouchHelper extends ItemTouchHelper { public ListItemTouchHelper(@NonNull ListItemTouchHelper.Callback callback) { super(callback); } public static class Callback extends ItemTouchHelper.SimpleCallback { /** * Callback method to be invoked when item has been swiped left. */ public void onSwipedLeft(int position) {} public Callback() { super(0, ItemTouchHelper.LEFT); } @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { int position = viewHolder.getAdapterPosition(); onSwipedLeft(position); } } }
3e0ed55a2359b1aae127a75b543917f960bd45f0
2,599
java
Java
mie creazioni/Informatica/Ingegneria/MyCalendar/src/fondt2/lab03/mycal/tests/AppointmentTest.java
andre-bisa/Archive
9599342d684172391d8919714e5494082615efb8
[ "MIT" ]
null
null
null
mie creazioni/Informatica/Ingegneria/MyCalendar/src/fondt2/lab03/mycal/tests/AppointmentTest.java
andre-bisa/Archive
9599342d684172391d8919714e5494082615efb8
[ "MIT" ]
null
null
null
mie creazioni/Informatica/Ingegneria/MyCalendar/src/fondt2/lab03/mycal/tests/AppointmentTest.java
andre-bisa/Archive
9599342d684172391d8919714e5494082615efb8
[ "MIT" ]
null
null
null
36.605634
113
0.740285
6,302
package fondt2.lab03.mycal.tests; import static org.junit.Assert.*; import java.time.Duration; import java.time.LocalDateTime; import java.time.Month; import java.time.temporal.ChronoUnit; import org.junit.Test; import fondt2.lab03.mycal.Appointment; public class AppointmentTest { @Test public void testSetGetFrom() { LocalDateTime dateTime = LocalDateTime.of(1980, Month.JUNE, 16, 12, 45, 0); Appointment app = new Appointment("test", dateTime, Duration.of(10, ChronoUnit.MINUTES));; assertEquals(dateTime, app.getFrom()); LocalDateTime newFrom = LocalDateTime.of(1980, Month.JULY, 16, 12, 45, 0); app.setFrom(newFrom); assertEquals(newFrom, app.getFrom()); } @Test public void testSetGetTo() { LocalDateTime dateTime = LocalDateTime.of(2011, Month.JUNE, 16, 12, 45, 0); Appointment app = new Appointment("test", dateTime, Duration.of(0, ChronoUnit.MINUTES));; assertEquals(dateTime, app.getTo()); LocalDateTime newTo = LocalDateTime.of(2011, Month.JULY, 16, 12, 45, 0); app.setTo(newTo); assertEquals(newTo, app.getTo()); } @Test public void testSetGetDescription() { Appointment app = new Appointment("Compleanno", LocalDateTime.now(), Duration.of(10, ChronoUnit.MINUTES)); assertEquals("Compleanno", app.getDescription()); app.setDescription("Anniversario"); assertEquals("Anniversario", app.getDescription()); } @Test public void testSetGetDuration() { LocalDateTime dateTime = LocalDateTime.of(2011, Month.JUNE, 16, 12, 45, 0); Appointment app = new Appointment("test", dateTime, Duration.of(10, ChronoUnit.MINUTES)); assertEquals(Duration.ofMinutes(10), app.getDuration()); LocalDateTime toDateTime = app.getTo(); LocalDateTime expected = LocalDateTime.of(2011, Month.JUNE, 16, 12, 55, 0); assertEquals(expected, toDateTime); app.setDuration(Duration.of(20, ChronoUnit.MINUTES)); LocalDateTime newExpected = LocalDateTime.of(2011, Month.JUNE, 16, 13, 05, 0); assertEquals(newExpected, app.getTo()); } @Test public void testEqualsAppointment() { Appointment app1 = new Appointment("Compleanno", LocalDateTime.now(), Duration.of(10, ChronoUnit.MINUTES)); Appointment app2 = new Appointment("Compleanno", LocalDateTime.now(), Duration.of(10, ChronoUnit.MINUTES)); assertTrue(app1.equals(app2)); } @Test public void testNotEqualsAppointment() { Appointment app1 = new Appointment("Compleanno", LocalDateTime.now(), Duration.of(10, ChronoUnit.MINUTES)); Appointment app2 = new Appointment("Non Compleanno", LocalDateTime.now(), Duration.of(10, ChronoUnit.MINUTES)); assertFalse(app1.equals(app2)); } }
3e0ed6014918327b8f24aa9b04ba68edd8424e23
619
java
Java
rc-api/src/main/java/com/ruoyi/user/service/IUserMoneyService.java
jkl123456/rongchuang
0c040b59873344af9c5da18e8c496327688cf008
[ "MIT" ]
1
2020-10-15T03:33:06.000Z
2020-10-15T03:33:06.000Z
rc-api/src/main/java/com/ruoyi/user/service/IUserMoneyService.java
LiangShaoHong/rongchuang2
0c040b59873344af9c5da18e8c496327688cf008
[ "MIT" ]
null
null
null
rc-api/src/main/java/com/ruoyi/user/service/IUserMoneyService.java
LiangShaoHong/rongchuang2
0c040b59873344af9c5da18e8c496327688cf008
[ "MIT" ]
1
2020-10-15T02:18:28.000Z
2020-10-15T02:18:28.000Z
24.76
150
0.636511
6,303
package com.ruoyi.user.service; import java.math.BigDecimal; /** * 平台加减币接口 * @author xiaoxia */ public interface IUserMoneyService { /** * 加减币接口 * @param userId 交易会员id * @param account 交易会员名称 * @param fromUserId 交易对象id(订单ID) * @param money 金额变化值 * @param cashHandFee 手续费(平台佣金) * @param recordType 资金变化类型 0转账 1提现 2充值 3后台人员操作 4法币交易 5币币交易 * @param mark 备注说明 * @return */ boolean moneyDoCenter(String userId, String account, String fromUserId, BigDecimal money, BigDecimal cashHandFee, String recordType, String mark); }
3e0ed6368ef95b04a3620f6957eefcf7073bf24e
3,988
java
Java
oracles/filters/reuse/src/test/java/de/learnlib/filter/reuse/test/QuiescenceTest.java
tiferrei/learnlib
7e3386940ba89b75115b6c25ba03e1f1fe5be410
[ "Apache-2.0" ]
158
2015-01-22T08:51:52.000Z
2022-03-21T11:39:52.000Z
oracles/filters/reuse/src/test/java/de/learnlib/filter/reuse/test/QuiescenceTest.java
tiferrei/learnlib
7e3386940ba89b75115b6c25ba03e1f1fe5be410
[ "Apache-2.0" ]
47
2015-04-14T11:45:52.000Z
2021-07-14T11:08:41.000Z
oracles/filters/reuse/src/test/java/de/learnlib/filter/reuse/test/QuiescenceTest.java
tiferrei/learnlib
7e3386940ba89b75115b6c25ba03e1f1fe5be410
[ "Apache-2.0" ]
55
2015-01-11T13:55:28.000Z
2022-02-25T08:14:13.000Z
33.512605
120
0.620863
6,304
/* Copyright (C) 2013-2021 TU Dortmund * This file is part of LearnLib, http://www.learnlib.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.learnlib.filter.reuse.test; import java.util.function.Supplier; import de.learnlib.algorithms.lstar.mealy.ExtensibleLStarMealyBuilder; import de.learnlib.api.algorithm.LearningAlgorithm.MealyLearner; import de.learnlib.filter.reuse.ReuseCapableOracle; import de.learnlib.filter.reuse.ReuseOracle; import net.automatalib.words.Alphabet; import net.automatalib.words.Word; import net.automatalib.words.WordBuilder; import net.automatalib.words.impl.Alphabets; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Similar to the {@link LearningTest} but this time with quiescence in outputs. The purpose of this test is just to * check that the reuse filter is able to work with {@code null} outputs. * * @author Oliver Bauer */ public class QuiescenceTest { private ReuseOracle<Integer, Integer, String> reuseOracle; private Alphabet<Integer> sigma; /** * {@inheritDoc}. */ @BeforeClass protected void setUp() { sigma = Alphabets.integers(0, 3); reuseOracle = new ReuseOracle.ReuseOracleBuilder<>(sigma, new TestOracleFactory()).build(); } @Test public void simpleTest() { MealyLearner<Integer, String> learner = new ExtensibleLStarMealyBuilder<Integer, String>().withAlphabet(sigma).withOracle(reuseOracle).create(); learner.startLearning(); } private static class TestOracleFactory implements Supplier<ReuseCapableOracle<Integer, Integer, String>> { @Override public ReuseCapableOracle<Integer, Integer, String> get() { return new TestOracle(); } } static class TestOracle implements ReuseCapableOracle<Integer, Integer, String> { private final int threshold = 3; @Override public QueryResult<Integer, String> continueQuery(Word<Integer> trace, Integer s) { Integer integer = s; WordBuilder<String> output = new WordBuilder<>(); for (Integer symbol : trace) { if (integer + symbol < threshold) { integer += symbol; output.add("ok"); } else if (integer + symbol == threshold) { integer += symbol; output.add("done"); } else { output.add(null); // quiescence } } QueryResult<Integer, String> result; result = new QueryResult<>(output.toWord(), integer); return result; } @Override public QueryResult<Integer, String> processQuery(Word<Integer> trace) { int integer = 0; WordBuilder<String> output = new WordBuilder<>(); for (Integer symbol : trace) { if (integer + symbol < threshold) { integer += symbol; output.add("ok"); } else if (integer + symbol == threshold) { integer += symbol; output.add("done"); } else { output.add(null); // quiescence } } QueryResult<Integer, String> result; result = new QueryResult<>(output.toWord(), integer); return result; } } }
3e0ed64f19ec6bb27daf450f884721dfa7871aae
3,346
java
Java
Controller/test/action/TranslateToCActionTest.java
engaugusto/compilador-faculdade-2011
4f44d7319962bc14ba893707780acfe83db85724
[ "MIT" ]
null
null
null
Controller/test/action/TranslateToCActionTest.java
engaugusto/compilador-faculdade-2011
4f44d7319962bc14ba893707780acfe83db85724
[ "MIT" ]
null
null
null
Controller/test/action/TranslateToCActionTest.java
engaugusto/compilador-faculdade-2011
4f44d7319962bc14ba893707780acfe83db85724
[ "MIT" ]
null
null
null
29.610619
78
0.50538
6,305
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package action; import java.util.ArrayList; import model.TokenValue; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Admin */ public class TranslateToCActionTest { public TranslateToCActionTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of Translate method, of class TranslateToCAction. */ @Test public void testTranslate() { System.out.println("Translate"); ArrayList<String> tokens = new ArrayList<String>(); ArrayList<TokenValue> tokenV = new ArrayList<TokenValue>(); tokens.add("tkMain"); tokens.add("tkOpenFunc"); tokens.add("tkI"); tokens.add("tkId"); tokenV.add(new TokenValue("i", TokenValue.Tipo.INTEGER, null, true)); tokens.add("tkEndLine"); tokens.add("tkFor"); tokens.add("tkId"); tokenV.add(new TokenValue("i", TokenValue.Tipo.INTEGER, null, false)); tokens.add("tkAtrib"); tokens.add("tkInt"); tokenV.add(new TokenValue("0", TokenValue.Tipo.INTEGER, 0, true)); tokens.add("tkEndLine"); tokens.add("tkId"); tokenV.add(new TokenValue("i", TokenValue.Tipo.INTEGER, null, true)); tokens.add("tkGreater"); tokens.add("tkInt"); tokenV.add(new TokenValue("10", TokenValue.Tipo.INTEGER, 10, true)); tokens.add("tkEndLine"); tokens.add("tkId"); tokenV.add(new TokenValue("i", TokenValue.Tipo.INTEGER, null, true)); tokens.add("tkAtrib"); tokens.add("tkId"); tokenV.add(new TokenValue("i", TokenValue.Tipo.INTEGER, null, true)); tokens.add("tkSoma"); tokens.add("tkInt"); tokenV.add(new TokenValue("1", TokenValue.Tipo.INTEGER, 1, true)); tokens.add("tkOpenFunc"); tokens.add("tkCloseFunc"); tokens.add("tkCloseFunc"); TranslateToCAction instance = new TranslateToCAction(); String expResult = "#include<stdio.h>\r\n"+ "#include<stdlib.h>\r\n"+ "\r\n"+ "int main()\r\n"+ "{\r\n"+ "int\r\n"+ "i;\r\n"+ "for (\r\n"+ "i=\r\n"+ "0;\r\n"+ "i>\r\n"+ "10;\r\n"+ "i=\r\n"+ "i+\r\n"+ "1){\r\n"+ "}\r\n"+ "}\r\n"+ "\r\n"; String result = instance.Translate(tokens,tokenV); System.out.println(result); System.out.println("Expected:\r\n"+expResult); assertEquals(expResult, result); } }
3e0ed6f2fef39ea4c0132958109177d2436277cc
6,999
java
Java
sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/sharding/statement/dml/ShardingSelectOptimizedStatement.java
contextshuffling/incubator-shardingsphere
da2ce6f6c34b01b4a18fa8ace68c173969532df5
[ "Apache-2.0" ]
null
null
null
sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/sharding/statement/dml/ShardingSelectOptimizedStatement.java
contextshuffling/incubator-shardingsphere
da2ce6f6c34b01b4a18fa8ace68c173969532df5
[ "Apache-2.0" ]
null
null
null
sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/sharding/statement/dml/ShardingSelectOptimizedStatement.java
contextshuffling/incubator-shardingsphere
da2ce6f6c34b01b4a18fa8ace68c173969532df5
[ "Apache-2.0" ]
null
null
null
47.290541
184
0.718388
6,306
/* * 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.shardingsphere.core.optimize.sharding.statement.dml; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.apache.shardingsphere.core.optimize.api.segment.Tables; import org.apache.shardingsphere.core.optimize.sharding.segment.select.groupby.GroupBy; import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.AggregationSelectItem; import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.SelectItem; import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.SelectItems; import org.apache.shardingsphere.core.optimize.sharding.segment.select.orderby.OrderBy; import org.apache.shardingsphere.core.optimize.sharding.segment.select.orderby.OrderByItem; import org.apache.shardingsphere.core.optimize.sharding.segment.select.pagination.Pagination; import org.apache.shardingsphere.core.parse.sql.segment.dml.order.item.ColumnOrderByItemSegment; import org.apache.shardingsphere.core.parse.sql.segment.dml.order.item.ExpressionOrderByItemSegment; import org.apache.shardingsphere.core.parse.sql.segment.dml.order.item.IndexOrderByItemSegment; import org.apache.shardingsphere.core.parse.sql.segment.dml.order.item.TextOrderByItemSegment; import org.apache.shardingsphere.core.parse.sql.statement.SQLStatement; import org.apache.shardingsphere.core.parse.util.SQLUtil; import java.util.Collection; import java.util.Map; /** * Select optimized statement for sharding. * * @author zhangliang */ @Getter @Setter @ToString public final class ShardingSelectOptimizedStatement extends ShardingConditionOptimizedStatement { private final Tables tables; private final GroupBy groupBy; private final OrderBy orderBy; private final SelectItems selectItems; private final Pagination pagination; private boolean containsSubquery; public ShardingSelectOptimizedStatement(final SQLStatement sqlStatement, final GroupBy groupBy, final OrderBy orderBy, final SelectItems selectItems, final Pagination pagination) { super(sqlStatement); this.tables = new Tables(sqlStatement); this.groupBy = groupBy; this.orderBy = orderBy; this.selectItems = selectItems; this.pagination = pagination; } /** * Set index for select items. * * @param columnLabelIndexMap map for column label and index */ public void setIndexForItems(final Map<String, Integer> columnLabelIndexMap) { setIndexForAggregationItem(columnLabelIndexMap); setIndexForOrderItem(columnLabelIndexMap, orderBy.getItems()); setIndexForOrderItem(columnLabelIndexMap, groupBy.getItems()); } private void setIndexForAggregationItem(final Map<String, Integer> columnLabelIndexMap) { for (AggregationSelectItem each : selectItems.getAggregationSelectItems()) { Preconditions.checkState(columnLabelIndexMap.containsKey(each.getColumnLabel()), "Can't find index: %s, please add alias for aggregate selections", each); each.setIndex(columnLabelIndexMap.get(each.getColumnLabel())); for (AggregationSelectItem derived : each.getDerivedAggregationItems()) { Preconditions.checkState(columnLabelIndexMap.containsKey(derived.getColumnLabel()), "Can't find index: %s", derived); derived.setIndex(columnLabelIndexMap.get(derived.getColumnLabel())); } } } private void setIndexForOrderItem(final Map<String, Integer> columnLabelIndexMap, final Collection<OrderByItem> orderByItems) { for (OrderByItem each : orderByItems) { if (each.getSegment() instanceof IndexOrderByItemSegment) { each.setIndex(((IndexOrderByItemSegment) each.getSegment()).getColumnIndex()); continue; } if (each.getSegment() instanceof ColumnOrderByItemSegment && ((ColumnOrderByItemSegment) each.getSegment()).getColumn().getOwner().isPresent()) { Optional<Integer> itemIndex = selectItems.findItemIndex(((ColumnOrderByItemSegment) each.getSegment()).getText()); if (itemIndex.isPresent()) { each.setIndex(itemIndex.get()); continue; } } Optional<String> alias = getAlias(((TextOrderByItemSegment) each.getSegment()).getText()); String columnLabel = alias.isPresent() ? alias.get() : getOrderItemText((TextOrderByItemSegment) each.getSegment()); Preconditions.checkState(columnLabelIndexMap.containsKey(columnLabel), "Can't find index: %s", each); if (columnLabelIndexMap.containsKey(columnLabel)) { each.setIndex(columnLabelIndexMap.get(columnLabel)); } } } private Optional<String> getAlias(final String name) { if (selectItems.isUnqualifiedShorthandItem()) { return Optional.absent(); } String rawName = SQLUtil.getExactlyValue(name); for (SelectItem each : selectItems.getItems()) { if (SQLUtil.getExactlyExpression(rawName).equalsIgnoreCase(SQLUtil.getExactlyExpression(SQLUtil.getExactlyValue(each.getExpression())))) { return each.getAlias(); } if (rawName.equalsIgnoreCase(each.getAlias().orNull())) { return Optional.of(rawName); } } return Optional.absent(); } private String getOrderItemText(final TextOrderByItemSegment orderByItemSegment) { return orderByItemSegment instanceof ColumnOrderByItemSegment ? ((ColumnOrderByItemSegment) orderByItemSegment).getColumn().getName() : ((ExpressionOrderByItemSegment) orderByItemSegment).getExpression(); } /** * Judge group by and order by sequence is same or not. * * @return group by and order by sequence is same or not */ public boolean isSameGroupByAndOrderByItems() { return !groupBy.getItems().isEmpty() && groupBy.getItems().equals(orderBy.getItems()); } }
3e0ed8b5f61ca3bd2c20c05d206648858f096d12
7,650
java
Java
modules/analysis/common/src/test/org/apache/lucene/analysis/payloads/DelimitedPayloadTokenFilterTest.java
chrismattmann/solrcene
501a7df450df18d98146c83143ec17530a732aef
[ "Apache-2.0" ]
3
2016-04-27T12:10:00.000Z
2019-06-12T23:28:18.000Z
modules/analysis/common/src/test/org/apache/lucene/analysis/payloads/DelimitedPayloadTokenFilterTest.java
chrismattmann/solrcene
501a7df450df18d98146c83143ec17530a732aef
[ "Apache-2.0" ]
null
null
null
modules/analysis/common/src/test/org/apache/lucene/analysis/payloads/DelimitedPayloadTokenFilterTest.java
chrismattmann/solrcene
501a7df450df18d98146c83143ec17530a732aef
[ "Apache-2.0" ]
5
2015-12-29T13:55:22.000Z
2020-05-10T23:49:45.000Z
55.035971
171
0.731373
6,307
package org.apache.lucene.analysis.payloads; /** * 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. */ import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.core.WhitespaceTokenizer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.PayloadAttribute; import org.apache.lucene.index.Payload; import org.apache.lucene.util.LuceneTestCase; import java.io.StringReader; public class DelimitedPayloadTokenFilterTest extends LuceneTestCase { public void testPayloads() throws Exception { String test = "The quick|JJ red|JJ fox|NN jumped|VB over the lazy|JJ brown|JJ dogs|NN"; DelimitedPayloadTokenFilter filter = new DelimitedPayloadTokenFilter (new WhitespaceTokenizer(TEST_VERSION_CURRENT, new StringReader(test)), DelimitedPayloadTokenFilter.DEFAULT_DELIMITER, new IdentityEncoder()); CharTermAttribute termAtt = filter.getAttribute(CharTermAttribute.class); PayloadAttribute payAtt = filter.getAttribute(PayloadAttribute.class); assertTermEquals("The", filter, termAtt, payAtt, null); assertTermEquals("quick", filter, termAtt, payAtt, "JJ".getBytes("UTF-8")); assertTermEquals("red", filter, termAtt, payAtt, "JJ".getBytes("UTF-8")); assertTermEquals("fox", filter, termAtt, payAtt, "NN".getBytes("UTF-8")); assertTermEquals("jumped", filter, termAtt, payAtt, "VB".getBytes("UTF-8")); assertTermEquals("over", filter, termAtt, payAtt, null); assertTermEquals("the", filter, termAtt, payAtt, null); assertTermEquals("lazy", filter, termAtt, payAtt, "JJ".getBytes("UTF-8")); assertTermEquals("brown", filter, termAtt, payAtt, "JJ".getBytes("UTF-8")); assertTermEquals("dogs", filter, termAtt, payAtt, "NN".getBytes("UTF-8")); assertFalse(filter.incrementToken()); } public void testNext() throws Exception { String test = "The quick|JJ red|JJ fox|NN jumped|VB over the lazy|JJ brown|JJ dogs|NN"; DelimitedPayloadTokenFilter filter = new DelimitedPayloadTokenFilter (new WhitespaceTokenizer(TEST_VERSION_CURRENT, new StringReader(test)), DelimitedPayloadTokenFilter.DEFAULT_DELIMITER, new IdentityEncoder()); assertTermEquals("The", filter, null); assertTermEquals("quick", filter, "JJ".getBytes("UTF-8")); assertTermEquals("red", filter, "JJ".getBytes("UTF-8")); assertTermEquals("fox", filter, "NN".getBytes("UTF-8")); assertTermEquals("jumped", filter, "VB".getBytes("UTF-8")); assertTermEquals("over", filter, null); assertTermEquals("the", filter, null); assertTermEquals("lazy", filter, "JJ".getBytes("UTF-8")); assertTermEquals("brown", filter, "JJ".getBytes("UTF-8")); assertTermEquals("dogs", filter, "NN".getBytes("UTF-8")); assertFalse(filter.incrementToken()); } public void testFloatEncoding() throws Exception { String test = "The quick|1.0 red|2.0 fox|3.5 jumped|0.5 over the lazy|5 brown|99.3 dogs|83.7"; DelimitedPayloadTokenFilter filter = new DelimitedPayloadTokenFilter(new WhitespaceTokenizer(TEST_VERSION_CURRENT, new StringReader(test)), '|', new FloatEncoder()); CharTermAttribute termAtt = filter.getAttribute(CharTermAttribute.class); PayloadAttribute payAtt = filter.getAttribute(PayloadAttribute.class); assertTermEquals("The", filter, termAtt, payAtt, null); assertTermEquals("quick", filter, termAtt, payAtt, PayloadHelper.encodeFloat(1.0f)); assertTermEquals("red", filter, termAtt, payAtt, PayloadHelper.encodeFloat(2.0f)); assertTermEquals("fox", filter, termAtt, payAtt, PayloadHelper.encodeFloat(3.5f)); assertTermEquals("jumped", filter, termAtt, payAtt, PayloadHelper.encodeFloat(0.5f)); assertTermEquals("over", filter, termAtt, payAtt, null); assertTermEquals("the", filter, termAtt, payAtt, null); assertTermEquals("lazy", filter, termAtt, payAtt, PayloadHelper.encodeFloat(5.0f)); assertTermEquals("brown", filter, termAtt, payAtt, PayloadHelper.encodeFloat(99.3f)); assertTermEquals("dogs", filter, termAtt, payAtt, PayloadHelper.encodeFloat(83.7f)); assertFalse(filter.incrementToken()); } public void testIntEncoding() throws Exception { String test = "The quick|1 red|2 fox|3 jumped over the lazy|5 brown|99 dogs|83"; DelimitedPayloadTokenFilter filter = new DelimitedPayloadTokenFilter(new WhitespaceTokenizer(TEST_VERSION_CURRENT, new StringReader(test)), '|', new IntegerEncoder()); CharTermAttribute termAtt = filter.getAttribute(CharTermAttribute.class); PayloadAttribute payAtt = filter.getAttribute(PayloadAttribute.class); assertTermEquals("The", filter, termAtt, payAtt, null); assertTermEquals("quick", filter, termAtt, payAtt, PayloadHelper.encodeInt(1)); assertTermEquals("red", filter, termAtt, payAtt, PayloadHelper.encodeInt(2)); assertTermEquals("fox", filter, termAtt, payAtt, PayloadHelper.encodeInt(3)); assertTermEquals("jumped", filter, termAtt, payAtt, null); assertTermEquals("over", filter, termAtt, payAtt, null); assertTermEquals("the", filter, termAtt, payAtt, null); assertTermEquals("lazy", filter, termAtt, payAtt, PayloadHelper.encodeInt(5)); assertTermEquals("brown", filter, termAtt, payAtt, PayloadHelper.encodeInt(99)); assertTermEquals("dogs", filter, termAtt, payAtt, PayloadHelper.encodeInt(83)); assertFalse(filter.incrementToken()); } void assertTermEquals(String expected, TokenStream stream, byte[] expectPay) throws Exception { CharTermAttribute termAtt = stream.getAttribute(CharTermAttribute.class); PayloadAttribute payloadAtt = stream.getAttribute(PayloadAttribute.class); assertTrue(stream.incrementToken()); assertEquals(expected, termAtt.toString()); Payload payload = payloadAtt.getPayload(); if (payload != null) { assertTrue(payload.length() + " does not equal: " + expectPay.length, payload.length() == expectPay.length); for (int i = 0; i < expectPay.length; i++) { assertTrue(expectPay[i] + " does not equal: " + payload.byteAt(i), expectPay[i] == payload.byteAt(i)); } } else { assertTrue("expectPay is not null and it should be", expectPay == null); } } void assertTermEquals(String expected, TokenStream stream, CharTermAttribute termAtt, PayloadAttribute payAtt, byte[] expectPay) throws Exception { assertTrue(stream.incrementToken()); assertEquals(expected, termAtt.toString()); Payload payload = payAtt.getPayload(); if (payload != null) { assertTrue(payload.length() + " does not equal: " + expectPay.length, payload.length() == expectPay.length); for (int i = 0; i < expectPay.length; i++) { assertTrue(expectPay[i] + " does not equal: " + payload.byteAt(i), expectPay[i] == payload.byteAt(i)); } } else { assertTrue("expectPay is not null and it should be", expectPay == null); } } }
3e0ed8ee0d93bc66fa8353bc8bfba862f17a038b
248
java
Java
file_ext/src/com/lara/Manager12.java
mkp1104/localEclipseWorkspaceJava
3523a0400ac95c0495c2714b8fb17c05f03d8dba
[ "MIT" ]
null
null
null
file_ext/src/com/lara/Manager12.java
mkp1104/localEclipseWorkspaceJava
3523a0400ac95c0495c2714b8fb17c05f03d8dba
[ "MIT" ]
null
null
null
file_ext/src/com/lara/Manager12.java
mkp1104/localEclipseWorkspaceJava
3523a0400ac95c0495c2714b8fb17c05f03d8dba
[ "MIT" ]
null
null
null
17.714286
40
0.669355
6,308
package com.lara; import java.io.PrintStream; public class Manager12 { public static void main(String[] args) { PrintStream ps=System.out; ps.println("Hello to All!!"); ps.println("Hello to All!!"); ps.println("Hello to All!!"); } }
3e0ed91f76bc9e23f4ebd6f43d8a44f40ad65622
332
java
Java
src/main/java/com/swnote/blog/dao/ArticleTagDao.java
lzj09/sw-blog
3b2df46be9c67e2bcb6fb1edfe580dd341d2c3f2
[ "Apache-2.0" ]
5
2019-04-26T01:29:25.000Z
2020-06-14T14:31:31.000Z
src/main/java/com/swnote/blog/dao/ArticleTagDao.java
lzj09/sw-blog
3b2df46be9c67e2bcb6fb1edfe580dd341d2c3f2
[ "Apache-2.0" ]
null
null
null
src/main/java/com/swnote/blog/dao/ArticleTagDao.java
lzj09/sw-blog
3b2df46be9c67e2bcb6fb1edfe580dd341d2c3f2
[ "Apache-2.0" ]
null
null
null
19.529412
63
0.759036
6,309
package com.swnote.blog.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.swnote.blog.domain.ArticleTag; import org.springframework.stereotype.Repository; /** * 文章标签关系Dao * * @author lzj * @since 1.0 * @date [2019-07-31] */ @Repository public interface ArticleTagDao extends BaseMapper<ArticleTag> { }
3e0eda94b9cf4039992633d005955fdcf1f91ddb
615
java
Java
client/standardmotion/app/src/main/java/com/example/standardmotion/ui/sportnews/Title.java
gorgeousdays/AiYunDong
04aaca79647bb4bdfbcc988ef9c6790163b0a72b
[ "MIT" ]
null
null
null
client/standardmotion/app/src/main/java/com/example/standardmotion/ui/sportnews/Title.java
gorgeousdays/AiYunDong
04aaca79647bb4bdfbcc988ef9c6790163b0a72b
[ "MIT" ]
null
null
null
client/standardmotion/app/src/main/java/com/example/standardmotion/ui/sportnews/Title.java
gorgeousdays/AiYunDong
04aaca79647bb4bdfbcc988ef9c6790163b0a72b
[ "MIT" ]
null
null
null
19.21875
73
0.603252
6,310
package com.example.standardmotion.ui.sportnews; public class Title { private String title; private String descr; private String imageUrl; private String uri; public Title(String title,String descr, String imageUrl, String uri){ this.title = title; this.imageUrl = imageUrl; this.descr = descr; this.uri = uri; } public String getTitle() { return title; } public String getImageUrl() { return imageUrl; } public String getDescr() { return descr; } public String getUri() { return uri; } }
3e0edb2416af43fe1f4379774cf9583f84a00ca2
252
java
Java
JavaFundamentals/JavaOOPAdvanced/04.EnumsAndAnnotationsExercise/src/_03CardsWithPower/CardSuit.java
yangra/SoftUni
2fe8ac059fe398f8bf229200c5406840f026fb88
[ "MIT" ]
null
null
null
JavaFundamentals/JavaOOPAdvanced/04.EnumsAndAnnotationsExercise/src/_03CardsWithPower/CardSuit.java
yangra/SoftUni
2fe8ac059fe398f8bf229200c5406840f026fb88
[ "MIT" ]
null
null
null
JavaFundamentals/JavaOOPAdvanced/04.EnumsAndAnnotationsExercise/src/_03CardsWithPower/CardSuit.java
yangra/SoftUni
2fe8ac059fe398f8bf229200c5406840f026fb88
[ "MIT" ]
null
null
null
15.75
51
0.599206
6,311
package _03CardsWithPower; public enum CardSuit { CLUBS(0), DIAMONDS(13), HEARTS(26), SPADES(39); private int power; CardSuit(int power) { this.power = power; } public int getPower() { return this.power; } }
3e0edbd16ac94b65d31386afe7d27a640bb01da6
2,384
java
Java
landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_GAME_STARTING.java
wwrssg/ratel
6e15281f74eb1f777853a16c89f73e640ef1f4bf
[ "Apache-2.0" ]
1
2020-07-29T03:07:09.000Z
2020-07-29T03:07:09.000Z
landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_GAME_STARTING.java
wwrssg/ratel
6e15281f74eb1f777853a16c89f73e640ef1f4bf
[ "Apache-2.0" ]
null
null
null
landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_GAME_STARTING.java
wwrssg/ratel
6e15281f74eb1f777853a16c89f73e640ef1f4bf
[ "Apache-2.0" ]
1
2020-06-10T10:51:34.000Z
2020-06-10T10:51:34.000Z
32.657534
95
0.760487
6,312
package org.nico.ratel.landlords.server.event; import java.util.LinkedList; import java.util.List; import org.nico.ratel.landlords.channel.ChannelUtils; import org.nico.ratel.landlords.entity.ClientSide; import org.nico.ratel.landlords.entity.Poker; import org.nico.ratel.landlords.entity.Room; import org.nico.ratel.landlords.enums.ClientEventCode; import org.nico.ratel.landlords.enums.ClientRole; import org.nico.ratel.landlords.enums.ClientType; import org.nico.ratel.landlords.enums.RoomStatus; import org.nico.ratel.landlords.helper.MapHelper; import org.nico.ratel.landlords.helper.PokerHelper; import org.nico.ratel.landlords.server.ServerContains; import org.nico.ratel.landlords.server.robot.RobotEventListener; public class ServerEventListener_CODE_GAME_STARTING implements ServerEventListener{ @Override public void call(ClientSide clientSide, String data) { Room room = ServerContains.getRoom(clientSide.getRoomId()); LinkedList<ClientSide> roomClientList = room.getClientSideList(); // Send the points of poker List<List<Poker>> pokersList = PokerHelper.distributePoker(); int cursor = 0; for(ClientSide client: roomClientList){ client.setPokers(pokersList.get(cursor ++)); } room.setLandlordPokers(pokersList.get(3)); // Push information about the robber int startGrabIndex = (int)(Math.random() * 3); ClientSide startGrabClient = roomClientList.get(startGrabIndex); room.setCurrentSellClient(startGrabClient.getId()); // Push start game messages room.setStatus(RoomStatus.STARTING); // Record the first speaker room.setFirstSellClient(startGrabClient.getId()); for(ClientSide client: roomClientList) { client.setType(ClientType.PEASANT); String result = MapHelper.newInstance() .put("roomId", room.getId()) .put("roomOwner", room.getRoomOwner()) .put("roomClientCount", room.getClientSideList().size()) .put("nextClientNickname", startGrabClient.getNickname()) .put("nextClientId", startGrabClient.getId()) .put("pokers", client.getPokers()) .json(); if(client.getRole() == ClientRole.PLAYER) { ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_GAME_STARTING, result); }else { if(startGrabClient.getId() == client.getId()) { RobotEventListener.get(ClientEventCode.CODE_GAME_LANDLORD_ELECT).call(client, result); } } } } }
3e0edc419f6067290ece559d5a08389df7c69398
2,141
java
Java
app/src/main/java/com/guardiansofgalakddy/lvlmonitor/junhwa/Aes.java
superb1019/LVL-Monitor
edb28914cc99b0a1aceabc18350c4541a4785944
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/guardiansofgalakddy/lvlmonitor/junhwa/Aes.java
superb1019/LVL-Monitor
edb28914cc99b0a1aceabc18350c4541a4785944
[ "Apache-2.0" ]
3
2019-12-23T06:59:20.000Z
2020-05-18T06:32:30.000Z
app/src/main/java/com/guardiansofgalakddy/lvlmonitor/junhwa/Aes.java
superb1019/LVL-Monitor
edb28914cc99b0a1aceabc18350c4541a4785944
[ "Apache-2.0" ]
8
2019-12-16T07:15:58.000Z
2020-02-05T08:02:28.000Z
35.683333
133
0.621672
6,313
package com.guardiansofgalakddy.lvlmonitor.junhwa; import java.security.AlgorithmParameters; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Aes { public static byte[] aesKey = { 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f }; public static byte[] aesIv = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; public static byte[] hexStringToByteArray(String hex) { if (hex == null || hex.length() == 0) { return null; } byte[] ba = new byte[hex.length() / 2]; for (int i = 0; i < ba.length; i++) { ba[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); } return ba; } public static String byteArrayToHexString(byte[] ba) { if (ba == null || ba.length == 0) { return null; } StringBuffer sb = new StringBuffer(ba.length * 2); String hexNumber; for (int x = 0; x < ba.length; x++) { hexNumber = "0" + Integer.toHexString(0xff & ba[x]); sb.append(hexNumber.substring(hexNumber.length() - 2)); } return sb.toString(); } public static byte[] encrypt(byte[] bytes) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(aesIv); Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec); byte[] encrypted = cipher.doFinal(bytes); return encrypted; } public static byte[] decrypt(byte[] bytes) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(aesIv); Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec); byte[] original = cipher.doFinal(bytes); return original; } }
3e0edce7a4a9dab08bfcb890719adb06e0c690fd
2,140
java
Java
jena-tdb/src/test/java/org/apache/jena/tdb/transaction/TestTransactionTDB.java
costas80/jena
7d146c5c265196c9c2740948fd1cd22b21aca033
[ "Apache-2.0" ]
null
null
null
jena-tdb/src/test/java/org/apache/jena/tdb/transaction/TestTransactionTDB.java
costas80/jena
7d146c5c265196c9c2740948fd1cd22b21aca033
[ "Apache-2.0" ]
1
2022-02-05T16:08:39.000Z
2022-02-05T16:08:41.000Z
jena-tdb/src/test/java/org/apache/jena/tdb/transaction/TestTransactionTDB.java
costas80/jena
7d146c5c265196c9c2740948fd1cd22b21aca033
[ "Apache-2.0" ]
null
null
null
31.470588
76
0.722897
6,314
/** * 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.jena.tdb.transaction; import org.apache.jena.atlas.lib.FileOps ; import org.apache.jena.atlas.logging.LogCtl ; import org.apache.jena.query.Dataset ; import org.apache.jena.sparql.transaction.AbstractTestTransactionLifecycle ; import org.apache.jena.tdb.ConfigTest ; import org.apache.jena.tdb.TDBFactory ; import org.apache.jena.tdb.sys.SystemTDB ; import org.apache.jena.tdb.sys.TDBInternal; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; public class TestTransactionTDB extends AbstractTestTransactionLifecycle { private String DIR = null ; private static String level = null ; @BeforeClass public static void beforeClassLoggingOff() { level = LogCtl.getLevel(SystemTDB.errlog.getName()); LogCtl.setLevel(SystemTDB.errlog.getName(), "OFF"); } @AfterClass public static void afterClassLoggingOn() { LogCtl.setLevel(SystemTDB.errlog.getName(), level); } @Before public void before() { TDBInternal.reset(); DIR = ConfigTest.getCleanDir(); } @After public void after() { TDBInternal.reset(); FileOps.clearDirectory(DIR); } @Override protected Dataset create() { return TDBFactory.createDataset(DIR); } }
3e0eddd21fd76662c74fdd3e708d26ad1f44a85b
684
java
Java
app/src/main/java/bravin/shi/com/multinested/constant/TimeConstants.java
bravinshi/MultiNested
ac04811d03c4b5d3c71e17eb46a7791822737aed
[ "Apache-2.0" ]
null
null
null
app/src/main/java/bravin/shi/com/multinested/constant/TimeConstants.java
bravinshi/MultiNested
ac04811d03c4b5d3c71e17eb46a7791822737aed
[ "Apache-2.0" ]
null
null
null
app/src/main/java/bravin/shi/com/multinested/constant/TimeConstants.java
bravinshi/MultiNested
ac04811d03c4b5d3c71e17eb46a7791822737aed
[ "Apache-2.0" ]
null
null
null
23.586207
44
0.669591
6,315
package bravin.shi.com.multinested.constant; import android.support.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2017/03/13 * desc : The constants of time. * </pre> */ public final class TimeConstants { public static final int MSEC = 1; public static final int SEC = 1000; public static final int MIN = 60000; public static final int HOUR = 3600000; public static final int DAY = 86400000; @IntDef({MSEC, SEC, MIN, HOUR, DAY}) @Retention(RetentionPolicy.SOURCE) public @interface Unit { } }
3e0ede72db51b83f8d26f8132fb73a88b07e5bb6
1,629
java
Java
dcf_service_producer/src/main/java/com/nimble/dcfs/custom/producer/demo/DemoAdvData.java
nimble-platform/dcf_service
f9b7954abe4a506b8c74fda321014b2ba61632e6
[ "Apache-2.0" ]
2
2019-01-02T12:46:17.000Z
2019-02-13T15:04:32.000Z
dcf_service_producer/src/main/java/com/nimble/dcfs/custom/producer/demo/DemoAdvData.java
nimble-platform/dcf_service
f9b7954abe4a506b8c74fda321014b2ba61632e6
[ "Apache-2.0" ]
2
2021-03-31T20:50:47.000Z
2021-03-31T20:54:47.000Z
dcf_service_producer/src/main/java/com/nimble/dcfs/custom/producer/demo/DemoAdvData.java
nimble-platform/dcf_service
f9b7954abe4a506b8c74fda321014b2ba61632e6
[ "Apache-2.0" ]
2
2019-02-13T11:22:56.000Z
2020-07-01T21:09:12.000Z
24.313433
147
0.650092
6,316
/* * Copyright 2018 a.musumeci. * * 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.nimble.dcfs.custom.producer.demo; /** * * @author a.musumeci */ public class DemoAdvData { String url; long totalPaid, revenue; private DemoAdvNested nestedInfo = new DemoAdvNested(); public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public double getTotalPaid() { return totalPaid; } public void setTotalPaid(long totalPaid) { this.totalPaid = totalPaid; } public double getRevenue() { return revenue; } public void setRevenue(long revenue) { this.revenue = revenue; } @Override public String toString() { return "DemoAdvData{" + "url=" + url + ", totalPaid=" + totalPaid + ", revenue=" + revenue + "', nestedInfo=" + nestedInfo.toString() +"}"; } public DemoAdvNested getNestedInfo() { return nestedInfo; } public void setNestedInfo(DemoAdvNested nestedInfo) { this.nestedInfo = nestedInfo; } }
3e0ede9b62ff80c8f3f6deabfc097e8c852d494e
26,659
java
Java
bundles/uclid.xtext/src-gen/uclid/xtext/uclid/impl/UclidFactoryImpl.java
sderrien/Uclid-editor
f34b7409da8fc2a11bc744e3612f96c2d00d631b
[ "MIT" ]
null
null
null
bundles/uclid.xtext/src-gen/uclid/xtext/uclid/impl/UclidFactoryImpl.java
sderrien/Uclid-editor
f34b7409da8fc2a11bc744e3612f96c2d00d631b
[ "MIT" ]
null
null
null
bundles/uclid.xtext/src-gen/uclid/xtext/uclid/impl/UclidFactoryImpl.java
sderrien/Uclid-editor
f34b7409da8fc2a11bc744e3612f96c2d00d631b
[ "MIT" ]
null
null
null
23.242371
112
0.65115
6,317
/** * generated by Xtext 2.24.0 */ package uclid.xtext.uclid.impl; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; import uclid.xtext.uclid.ArgList; import uclid.xtext.uclid.ArgMapListRule; import uclid.xtext.uclid.ArgMapRule; import uclid.xtext.uclid.ArrayTypeRule; import uclid.xtext.uclid.Assignment; import uclid.xtext.uclid.AssignmentRule; import uclid.xtext.uclid.AxiomDeclRule; import uclid.xtext.uclid.CallStatement; import uclid.xtext.uclid.CaseBlockRule; import uclid.xtext.uclid.CaseStmtRule; import uclid.xtext.uclid.CmdRule; import uclid.xtext.uclid.CompoundStatement; import uclid.xtext.uclid.ConstDecl; import uclid.xtext.uclid.ConstRule; import uclid.xtext.uclid.ConstsDeclRule; import uclid.xtext.uclid.ControlBlockRule; import uclid.xtext.uclid.DeclRule; import uclid.xtext.uclid.DefaultCaseBlockRule; import uclid.xtext.uclid.E10Rule; import uclid.xtext.uclid.E11Rule; import uclid.xtext.uclid.E12Rule; import uclid.xtext.uclid.E13Rule; import uclid.xtext.uclid.E1Rule; import uclid.xtext.uclid.E2Rule; import uclid.xtext.uclid.E3Rule; import uclid.xtext.uclid.E4Rule; import uclid.xtext.uclid.E5Rule; import uclid.xtext.uclid.E6Rule; import uclid.xtext.uclid.E7Rule; import uclid.xtext.uclid.E8Rule; import uclid.xtext.uclid.E9Rule; import uclid.xtext.uclid.EnsureExprsRule; import uclid.xtext.uclid.EnumRef; import uclid.xtext.uclid.EnumTypeRule; import uclid.xtext.uclid.EnumValue; import uclid.xtext.uclid.ExprListRule; import uclid.xtext.uclid.ExprRule; import uclid.xtext.uclid.ForLoopRule; import uclid.xtext.uclid.FuncDecl; import uclid.xtext.uclid.FunctionDecl; import uclid.xtext.uclid.IdListRule; import uclid.xtext.uclid.IfPrimaryExpr; import uclid.xtext.uclid.IfStmtRule; import uclid.xtext.uclid.InitDeclRule; import uclid.xtext.uclid.InputDecl; import uclid.xtext.uclid.InputsDeclRule; import uclid.xtext.uclid.InstanceDecl; import uclid.xtext.uclid.InvariantRule; import uclid.xtext.uclid.ModelRule; import uclid.xtext.uclid.ModifiesExprsRule; import uclid.xtext.uclid.ModuleRule; import uclid.xtext.uclid.NextDeclRule; import uclid.xtext.uclid.OutputDecl; import uclid.xtext.uclid.OutputsDeclRule; import uclid.xtext.uclid.ParenthesisExpr; import uclid.xtext.uclid.ProcReturnArgRule; import uclid.xtext.uclid.ProcedureDecl; import uclid.xtext.uclid.PropertyRule; import uclid.xtext.uclid.RecordTypeRule; import uclid.xtext.uclid.RequireExprsRule; import uclid.xtext.uclid.SharedVarsDeclRule; import uclid.xtext.uclid.SpecDeclRule; import uclid.xtext.uclid.Statement; import uclid.xtext.uclid.StatementRule; import uclid.xtext.uclid.TopLevel; import uclid.xtext.uclid.TupleExpr; import uclid.xtext.uclid.TupleTypeRule; import uclid.xtext.uclid.Type; import uclid.xtext.uclid.TypeDecl; import uclid.xtext.uclid.TypedObjectDecl; import uclid.xtext.uclid.UclidFactory; import uclid.xtext.uclid.UclidPackage; import uclid.xtext.uclid.VarDecl; import uclid.xtext.uclid.VarReference; import uclid.xtext.uclid.VarsDeclRule; import uclid.xtext.uclid.WhileLoopRule; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class UclidFactoryImpl extends EFactoryImpl implements UclidFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static UclidFactory init() { try { UclidFactory theUclidFactory = (UclidFactory)EPackage.Registry.INSTANCE.getEFactory(UclidPackage.eNS_URI); if (theUclidFactory != null) { return theUclidFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new UclidFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public UclidFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case UclidPackage.MODEL_RULE: return createModelRule(); case UclidPackage.MODULE_RULE: return createModuleRule(); case UclidPackage.DECL_RULE: return createDeclRule(); case UclidPackage.TYPE_DECL: return createTypeDecl(); case UclidPackage.INPUTS_DECL_RULE: return createInputsDeclRule(); case UclidPackage.OUTPUTS_DECL_RULE: return createOutputsDeclRule(); case UclidPackage.TYPED_OBJECT_DECL: return createTypedObjectDecl(); case UclidPackage.INPUT_DECL: return createInputDecl(); case UclidPackage.OUTPUT_DECL: return createOutputDecl(); case UclidPackage.VAR_DECL: return createVarDecl(); case UclidPackage.FUNC_DECL: return createFuncDecl(); case UclidPackage.VARS_DECL_RULE: return createVarsDeclRule(); case UclidPackage.CONSTS_DECL_RULE: return createConstsDeclRule(); case UclidPackage.CONST_DECL: return createConstDecl(); case UclidPackage.SHARED_VARS_DECL_RULE: return createSharedVarsDeclRule(); case UclidPackage.ARG_LIST: return createArgList(); case UclidPackage.PROC_RETURN_ARG_RULE: return createProcReturnArgRule(); case UclidPackage.REQUIRE_EXPRS_RULE: return createRequireExprsRule(); case UclidPackage.ENSURE_EXPRS_RULE: return createEnsureExprsRule(); case UclidPackage.MODIFIES_EXPRS_RULE: return createModifiesExprsRule(); case UclidPackage.INSTANCE_DECL: return createInstanceDecl(); case UclidPackage.ARG_MAP_LIST_RULE: return createArgMapListRule(); case UclidPackage.ARG_MAP_RULE: return createArgMapRule(); case UclidPackage.AXIOM_DECL_RULE: return createAxiomDeclRule(); case UclidPackage.SPEC_DECL_RULE: return createSpecDeclRule(); case UclidPackage.PROPERTY_RULE: return createPropertyRule(); case UclidPackage.INVARIANT_RULE: return createInvariantRule(); case UclidPackage.INIT_DECL_RULE: return createInitDeclRule(); case UclidPackage.NEXT_DECL_RULE: return createNextDeclRule(); case UclidPackage.STATEMENT: return createStatement(); case UclidPackage.CALL_STATEMENT: return createCallStatement(); case UclidPackage.ASSIGNMENT_RULE: return createAssignmentRule(); case UclidPackage.COMPOUND_STATEMENT: return createCompoundStatement(); case UclidPackage.IF_STMT_RULE: return createIfStmtRule(); case UclidPackage.CASE_STMT_RULE: return createCaseStmtRule(); case UclidPackage.DEFAULT_CASE_BLOCK_RULE: return createDefaultCaseBlockRule(); case UclidPackage.CASE_BLOCK_RULE: return createCaseBlockRule(); case UclidPackage.FOR_LOOP_RULE: return createForLoopRule(); case UclidPackage.WHILE_LOOP_RULE: return createWhileLoopRule(); case UclidPackage.EXPR_RULE: return createExprRule(); case UclidPackage.E1_RULE: return createE1Rule(); case UclidPackage.E2_RULE: return createE2Rule(); case UclidPackage.E3_RULE: return createE3Rule(); case UclidPackage.E4_RULE: return createE4Rule(); case UclidPackage.E5_RULE: return createE5Rule(); case UclidPackage.E6_RULE: return createE6Rule(); case UclidPackage.E7_RULE: return createE7Rule(); case UclidPackage.E8_RULE: return createE8Rule(); case UclidPackage.E9_RULE: return createE9Rule(); case UclidPackage.E10_RULE: return createE10Rule(); case UclidPackage.E11_RULE: return createE11Rule(); case UclidPackage.E12_RULE: return createE12Rule(); case UclidPackage.VAR_REFERENCE: return createVarReference(); case UclidPackage.TYPE: return createType(); case UclidPackage.E13_RULE: return createE13Rule(); case UclidPackage.ENUM_REF: return createEnumRef(); case UclidPackage.TUPLE_EXPR: return createTupleExpr(); case UclidPackage.IF_PRIMARY_EXPR: return createIfPrimaryExpr(); case UclidPackage.PARENTHESIS_EXPR: return createParenthesisExpr(); case UclidPackage.CONST_RULE: return createConstRule(); case UclidPackage.CONTROL_BLOCK_RULE: return createControlBlockRule(); case UclidPackage.CMD_RULE: return createCmdRule(); case UclidPackage.ID_LIST_RULE: return createIdListRule(); case UclidPackage.EXPR_LIST_RULE: return createExprListRule(); case UclidPackage.TOP_LEVEL: return createTopLevel(); case UclidPackage.MODULE: return createModule(); case UclidPackage.FUNCTION_DECL: return createFunctionDecl(); case UclidPackage.PROCEDURE_DECL: return createProcedureDecl(); case UclidPackage.STATEMENT_RULE: return createStatementRule(); case UclidPackage.ASSIGNMENT: return createAssignment(); case UclidPackage.ENUM_TYPE_RULE: return createEnumTypeRule(); case UclidPackage.ENUM_VALUE: return createEnumValue(); case UclidPackage.TUPLE_TYPE_RULE: return createTupleTypeRule(); case UclidPackage.RECORD_TYPE_RULE: return createRecordTypeRule(); case UclidPackage.ARRAY_TYPE_RULE: return createArrayTypeRule(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ModelRule createModelRule() { ModelRuleImpl modelRule = new ModelRuleImpl(); return modelRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ModuleRule createModuleRule() { ModuleRuleImpl moduleRule = new ModuleRuleImpl(); return moduleRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public DeclRule createDeclRule() { DeclRuleImpl declRule = new DeclRuleImpl(); return declRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public TypeDecl createTypeDecl() { TypeDeclImpl typeDecl = new TypeDeclImpl(); return typeDecl; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public InputsDeclRule createInputsDeclRule() { InputsDeclRuleImpl inputsDeclRule = new InputsDeclRuleImpl(); return inputsDeclRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public OutputsDeclRule createOutputsDeclRule() { OutputsDeclRuleImpl outputsDeclRule = new OutputsDeclRuleImpl(); return outputsDeclRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public TypedObjectDecl createTypedObjectDecl() { TypedObjectDeclImpl typedObjectDecl = new TypedObjectDeclImpl(); return typedObjectDecl; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public InputDecl createInputDecl() { InputDeclImpl inputDecl = new InputDeclImpl(); return inputDecl; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public OutputDecl createOutputDecl() { OutputDeclImpl outputDecl = new OutputDeclImpl(); return outputDecl; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public VarDecl createVarDecl() { VarDeclImpl varDecl = new VarDeclImpl(); return varDecl; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public FuncDecl createFuncDecl() { FuncDeclImpl funcDecl = new FuncDeclImpl(); return funcDecl; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public VarsDeclRule createVarsDeclRule() { VarsDeclRuleImpl varsDeclRule = new VarsDeclRuleImpl(); return varsDeclRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ConstsDeclRule createConstsDeclRule() { ConstsDeclRuleImpl constsDeclRule = new ConstsDeclRuleImpl(); return constsDeclRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ConstDecl createConstDecl() { ConstDeclImpl constDecl = new ConstDeclImpl(); return constDecl; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public SharedVarsDeclRule createSharedVarsDeclRule() { SharedVarsDeclRuleImpl sharedVarsDeclRule = new SharedVarsDeclRuleImpl(); return sharedVarsDeclRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ArgList createArgList() { ArgListImpl argList = new ArgListImpl(); return argList; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ProcReturnArgRule createProcReturnArgRule() { ProcReturnArgRuleImpl procReturnArgRule = new ProcReturnArgRuleImpl(); return procReturnArgRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public RequireExprsRule createRequireExprsRule() { RequireExprsRuleImpl requireExprsRule = new RequireExprsRuleImpl(); return requireExprsRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EnsureExprsRule createEnsureExprsRule() { EnsureExprsRuleImpl ensureExprsRule = new EnsureExprsRuleImpl(); return ensureExprsRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ModifiesExprsRule createModifiesExprsRule() { ModifiesExprsRuleImpl modifiesExprsRule = new ModifiesExprsRuleImpl(); return modifiesExprsRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public InstanceDecl createInstanceDecl() { InstanceDeclImpl instanceDecl = new InstanceDeclImpl(); return instanceDecl; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ArgMapListRule createArgMapListRule() { ArgMapListRuleImpl argMapListRule = new ArgMapListRuleImpl(); return argMapListRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ArgMapRule createArgMapRule() { ArgMapRuleImpl argMapRule = new ArgMapRuleImpl(); return argMapRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public AxiomDeclRule createAxiomDeclRule() { AxiomDeclRuleImpl axiomDeclRule = new AxiomDeclRuleImpl(); return axiomDeclRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public SpecDeclRule createSpecDeclRule() { SpecDeclRuleImpl specDeclRule = new SpecDeclRuleImpl(); return specDeclRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public PropertyRule createPropertyRule() { PropertyRuleImpl propertyRule = new PropertyRuleImpl(); return propertyRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public InvariantRule createInvariantRule() { InvariantRuleImpl invariantRule = new InvariantRuleImpl(); return invariantRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public InitDeclRule createInitDeclRule() { InitDeclRuleImpl initDeclRule = new InitDeclRuleImpl(); return initDeclRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NextDeclRule createNextDeclRule() { NextDeclRuleImpl nextDeclRule = new NextDeclRuleImpl(); return nextDeclRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Statement createStatement() { StatementImpl statement = new StatementImpl(); return statement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public CallStatement createCallStatement() { CallStatementImpl callStatement = new CallStatementImpl(); return callStatement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public AssignmentRule createAssignmentRule() { AssignmentRuleImpl assignmentRule = new AssignmentRuleImpl(); return assignmentRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public CompoundStatement createCompoundStatement() { CompoundStatementImpl compoundStatement = new CompoundStatementImpl(); return compoundStatement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public IfStmtRule createIfStmtRule() { IfStmtRuleImpl ifStmtRule = new IfStmtRuleImpl(); return ifStmtRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public CaseStmtRule createCaseStmtRule() { CaseStmtRuleImpl caseStmtRule = new CaseStmtRuleImpl(); return caseStmtRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public DefaultCaseBlockRule createDefaultCaseBlockRule() { DefaultCaseBlockRuleImpl defaultCaseBlockRule = new DefaultCaseBlockRuleImpl(); return defaultCaseBlockRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public CaseBlockRule createCaseBlockRule() { CaseBlockRuleImpl caseBlockRule = new CaseBlockRuleImpl(); return caseBlockRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ForLoopRule createForLoopRule() { ForLoopRuleImpl forLoopRule = new ForLoopRuleImpl(); return forLoopRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public WhileLoopRule createWhileLoopRule() { WhileLoopRuleImpl whileLoopRule = new WhileLoopRuleImpl(); return whileLoopRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ExprRule createExprRule() { ExprRuleImpl exprRule = new ExprRuleImpl(); return exprRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E1Rule createE1Rule() { E1RuleImpl e1Rule = new E1RuleImpl(); return e1Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E2Rule createE2Rule() { E2RuleImpl e2Rule = new E2RuleImpl(); return e2Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E3Rule createE3Rule() { E3RuleImpl e3Rule = new E3RuleImpl(); return e3Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E4Rule createE4Rule() { E4RuleImpl e4Rule = new E4RuleImpl(); return e4Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E5Rule createE5Rule() { E5RuleImpl e5Rule = new E5RuleImpl(); return e5Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E6Rule createE6Rule() { E6RuleImpl e6Rule = new E6RuleImpl(); return e6Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E7Rule createE7Rule() { E7RuleImpl e7Rule = new E7RuleImpl(); return e7Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E8Rule createE8Rule() { E8RuleImpl e8Rule = new E8RuleImpl(); return e8Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E9Rule createE9Rule() { E9RuleImpl e9Rule = new E9RuleImpl(); return e9Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E10Rule createE10Rule() { E10RuleImpl e10Rule = new E10RuleImpl(); return e10Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E11Rule createE11Rule() { E11RuleImpl e11Rule = new E11RuleImpl(); return e11Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E12Rule createE12Rule() { E12RuleImpl e12Rule = new E12RuleImpl(); return e12Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public VarReference createVarReference() { VarReferenceImpl varReference = new VarReferenceImpl(); return varReference; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Type createType() { TypeImpl type = new TypeImpl(); return type; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public E13Rule createE13Rule() { E13RuleImpl e13Rule = new E13RuleImpl(); return e13Rule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EnumRef createEnumRef() { EnumRefImpl enumRef = new EnumRefImpl(); return enumRef; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public TupleExpr createTupleExpr() { TupleExprImpl tupleExpr = new TupleExprImpl(); return tupleExpr; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public IfPrimaryExpr createIfPrimaryExpr() { IfPrimaryExprImpl ifPrimaryExpr = new IfPrimaryExprImpl(); return ifPrimaryExpr; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ParenthesisExpr createParenthesisExpr() { ParenthesisExprImpl parenthesisExpr = new ParenthesisExprImpl(); return parenthesisExpr; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ConstRule createConstRule() { ConstRuleImpl constRule = new ConstRuleImpl(); return constRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ControlBlockRule createControlBlockRule() { ControlBlockRuleImpl controlBlockRule = new ControlBlockRuleImpl(); return controlBlockRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public CmdRule createCmdRule() { CmdRuleImpl cmdRule = new CmdRuleImpl(); return cmdRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public IdListRule createIdListRule() { IdListRuleImpl idListRule = new IdListRuleImpl(); return idListRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ExprListRule createExprListRule() { ExprListRuleImpl exprListRule = new ExprListRuleImpl(); return exprListRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public TopLevel createTopLevel() { TopLevelImpl topLevel = new TopLevelImpl(); return topLevel; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public uclid.xtext.uclid.Module createModule() { ModuleImpl module = new ModuleImpl(); return module; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public FunctionDecl createFunctionDecl() { FunctionDeclImpl functionDecl = new FunctionDeclImpl(); return functionDecl; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ProcedureDecl createProcedureDecl() { ProcedureDeclImpl procedureDecl = new ProcedureDeclImpl(); return procedureDecl; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public StatementRule createStatementRule() { StatementRuleImpl statementRule = new StatementRuleImpl(); return statementRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Assignment createAssignment() { AssignmentImpl assignment = new AssignmentImpl(); return assignment; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EnumTypeRule createEnumTypeRule() { EnumTypeRuleImpl enumTypeRule = new EnumTypeRuleImpl(); return enumTypeRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EnumValue createEnumValue() { EnumValueImpl enumValue = new EnumValueImpl(); return enumValue; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public TupleTypeRule createTupleTypeRule() { TupleTypeRuleImpl tupleTypeRule = new TupleTypeRuleImpl(); return tupleTypeRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public RecordTypeRule createRecordTypeRule() { RecordTypeRuleImpl recordTypeRule = new RecordTypeRuleImpl(); return recordTypeRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ArrayTypeRule createArrayTypeRule() { ArrayTypeRuleImpl arrayTypeRule = new ArrayTypeRuleImpl(); return arrayTypeRule; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public UclidPackage getUclidPackage() { return (UclidPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static UclidPackage getPackage() { return UclidPackage.eINSTANCE; } } //UclidFactoryImpl
3e0edeea38b8918d9fddf92933634136f7ffc64b
2,696
java
Java
OpaAPI/src/main/java/gov/nara/opa/api/services/impl/user/lists/AddToUserListServiceImpl.java
usnationalarchives/catalog-source
74187b9096a388c033ff1f5ca4ec6634b5bba69e
[ "CC0-1.0" ]
4
2019-06-26T22:43:09.000Z
2021-08-19T04:07:19.000Z
OpaAPI/src/main/java/gov/nara/opa/api/services/impl/user/lists/AddToUserListServiceImpl.java
usnationalarchives/catalog-source
74187b9096a388c033ff1f5ca4ec6634b5bba69e
[ "CC0-1.0" ]
1
2019-07-05T14:03:46.000Z
2019-09-17T13:21:11.000Z
OpaAPI/src/main/java/gov/nara/opa/api/services/impl/user/lists/AddToUserListServiceImpl.java
usnationalarchives/catalog-source
74187b9096a388c033ff1f5ca4ec6634b5bba69e
[ "CC0-1.0" ]
null
null
null
27.510204
79
0.728487
6,318
package gov.nara.opa.api.services.impl.user.lists; import gov.nara.opa.api.dataaccess.user.lists.UserListDao; import gov.nara.opa.api.services.system.ConfigurationService; import gov.nara.opa.api.services.user.lists.AddToUserListService; import gov.nara.opa.api.services.user.lists.ViewUserListService; import gov.nara.opa.api.user.lists.UserListItem; import gov.nara.opa.architecture.logging.OpaLogger; import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @Component @Transactional public class AddToUserListServiceImpl implements AddToUserListService { private static OpaLogger logger = OpaLogger .getLogger(AddToUserListServiceImpl.class); SecureRandom random; @Autowired private UserListDao userListDao; @Autowired private ViewUserListService viewUserListService; @Autowired private ConfigurationService configurationService; public UserListItem getListItem(int listId, String opaId) { try { // Check for duplicate list List<UserListItem> dupList; dupList = userListDao.selectListItem(listId, opaId); if (dupList.size() > 0) { return dupList.get(0); } } catch (Exception e) { logger.error(e.getMessage(), e); //throw new OpaRuntimeException(e); } return null; } @Override public List<String> getOpaIdsToAddToList(int listId, String[] opaIds) { List<String> opaIdsToAddToList = new ArrayList<String>(); try { opaIdsToAddToList = userListDao.checkListForOpaIds(listId, opaIds); } catch (Exception e) { logger.error(e.getMessage(), e); //throw new OpaRuntimeException(e); } return opaIdsToAddToList; } @Override public List<UserListItem> getNonDuplicateListOpaIds(int listId, String[] opaIds) { List<UserListItem> nonDuplicateListOpaIds = new ArrayList<UserListItem>(); try { nonDuplicateListOpaIds = userListDao.checkListForDuplicateOpaIds(listId, opaIds); } catch (Exception e) { logger.error(e.getMessage(), e); //throw new OpaRuntimeException(e); } return nonDuplicateListOpaIds; } @Override public int batchAddOpaIdsToList(int listId, List<String> opaIdsToAddToList) { int toalIdsAddedToList = 0; try { toalIdsAddedToList = userListDao.batchAddToUserList(listId, opaIdsToAddToList); } catch (Exception e) { logger.error(e.getMessage(), e); //throw new OpaRuntimeException(e); } return toalIdsAddedToList; } }
3e0edfcda6d939d75450bd448e0169903220393b
2,319
java
Java
src/main/java/cn/roothub/bbs/module/visit/service/impl/VisitServiceImpl.java
wangxingwei/Roothub
14edcc01f17e6d0b3c56f6eeaa00dfacfa7131f2
[ "MIT" ]
1
2019-11-18T16:19:44.000Z
2019-11-18T16:19:44.000Z
src/main/java/cn/roothub/bbs/module/visit/service/impl/VisitServiceImpl.java
wangxingwei/Roothub
14edcc01f17e6d0b3c56f6eeaa00dfacfa7131f2
[ "MIT" ]
null
null
null
src/main/java/cn/roothub/bbs/module/visit/service/impl/VisitServiceImpl.java
wangxingwei/Roothub
14edcc01f17e6d0b3c56f6eeaa00dfacfa7131f2
[ "MIT" ]
null
null
null
28.9875
93
0.728331
6,319
package cn.roothub.bbs.module.visit.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.roothub.bbs.module.visit.dao.VisitDao; import cn.roothub.bbs.common.dto.DMLExecution; import cn.roothub.bbs.core.base.PageDataBody; import cn.roothub.bbs.module.user.model.User; import cn.roothub.bbs.module.visit.model.Visit; import cn.roothub.bbs.common.enums.InsertEnum; import cn.roothub.bbs.common.enums.UpdateEnum; import cn.roothub.bbs.core.exception.OperationFailedException; import cn.roothub.bbs.core.exception.OperationRepeaException; import cn.roothub.bbs.core.exception.OperationSystemException; import cn.roothub.bbs.module.visit.service.VisitService; /** * * @author sen 2018年8月4日 下午3:34:37 TODO */ @Service public class VisitServiceImpl implements VisitService { @Autowired private VisitDao visitDao; /** * 分页查询访问记录 */ @Override public PageDataBody<User> page(Integer vid, Integer pageNumber, Integer pageSize) { int totalRow = visitDao.count(vid); List<User> list = visitDao.select(vid, (pageNumber - 1) * pageSize, pageSize); return new PageDataBody<>(list, pageNumber, pageSize, totalRow); } /** * 添加访问记录 */ @Override @Transactional public DMLExecution save(Visit visit) { try { if (visit.getUid() == visit.getVid()) { throw new OperationRepeaException("访问者与被访问者为同一用户!"); } int isVisit = visitDao.isVisit(visit.getUid(), visit.getVid()); if (isVisit == 0) { int insert = visitDao.insert(visit); if (insert <= 0) { throw new OperationFailedException("添加失败!"); } else { return new DMLExecution("添加访问记录", InsertEnum.SUCCESS, visit); } } else { int update = visitDao.update(visit); if (update <= 0) { throw new OperationFailedException("更新失败!"); } else { return new DMLExecution("更新访问记录", UpdateEnum.SUCCESS, visit); } } } catch (OperationRepeaException e2) { throw e2; } catch (OperationFailedException e1) { throw e1; } catch (Exception e) { throw new OperationSystemException("insert into or update visit error " + e.getMessage()); } } @Override public int count(Integer vid) { return visitDao.count(vid); } }
3e0ee08dc3d8a60a74cd216cff22e322ad1240c7
1,554
java
Java
debop4k-data-orm/src/main/java/debop4k/data/orm/jpa/config/AbstractJpaH2Configuration.java
debop/debop4k
5a621998b88b4d416f510971536abf3bf82fb2f0
[ "Apache-2.0" ]
30
2016-07-21T23:06:21.000Z
2022-01-29T12:36:36.000Z
debop4k-data-orm/src/main/java/debop4k/data/orm/jpa/config/AbstractJpaH2Configuration.java
debop/debop4k
5a621998b88b4d416f510971536abf3bf82fb2f0
[ "Apache-2.0" ]
null
null
null
debop4k-data-orm/src/main/java/debop4k/data/orm/jpa/config/AbstractJpaH2Configuration.java
debop/debop4k
5a621998b88b4d416f510971536abf3bf82fb2f0
[ "Apache-2.0" ]
10
2016-10-07T02:29:38.000Z
2022-01-29T12:36:48.000Z
31.959184
109
0.685185
6,320
/* * Copyright (c) 2016. Sunghyouk Bae <ychag@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 debop4k.data.orm.jpa.config; import debop4k.config.database.DatabaseSetting; import debop4k.data.JdbcDrivers; import org.hibernate.cfg.Environment; import java.util.Properties; /** * H2 Database 용 JPA Configuration * * @author ychag@example.com */ public abstract class AbstractJpaH2Configuration extends AbstractJpaConfiguration { @Override protected DatabaseSetting getDatabaseSetting() { return DatabaseSetting.builder() .driverClass(JdbcDrivers.DRIVER_CLASS_H2) .jdbcUrl("jdbc:h2:mem:" + getDatabaseName() + ";DB_CLOSE_ON_EXIT=FALSE;MVCC=TRUE;") .username("sa") .password("") .build(); } @Override public Properties jpaProperties() { Properties props = super.jpaProperties(); props.put(Environment.DIALECT, JdbcDrivers.DIALECT_H2); return props; } }
3e0ee0b5007cf099273865b4e444ecf3d20fe86c
1,313
java
Java
src/main/java/isaac/bastion/CommonSettings.java
Diet-Cola/Bastion
e0a247d01b56fc1a74748f8e331aaa4237390cd4
[ "BSD-3-Clause" ]
3
2017-03-26T02:29:37.000Z
2017-06-22T13:37:44.000Z
src/main/java/isaac/bastion/CommonSettings.java
Diet-Cola/Bastion
e0a247d01b56fc1a74748f8e331aaa4237390cd4
[ "BSD-3-Clause" ]
47
2016-04-10T22:38:40.000Z
2021-11-12T03:37:46.000Z
src/main/java/isaac/bastion/CommonSettings.java
Diet-Cola/Bastion
e0a247d01b56fc1a74748f8e331aaa4237390cd4
[ "BSD-3-Clause" ]
20
2016-02-19T23:44:19.000Z
2021-11-18T23:10:59.000Z
28.543478
117
0.789033
6,321
/** * Created by Aleksey on 16.07.2017. */ package isaac.bastion; import java.util.HashSet; import java.util.List; import java.util.Set; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; public class CommonSettings { private boolean cancelReinforcementModeInBastionField; private int listBastionTimeout; private Set<Material> cancelPlacementAndDamage; public boolean isCancelReinforcementModeInBastionField() { return this.cancelReinforcementModeInBastionField; } public int getListBastionTimeout() { return this.listBastionTimeout; } public Set<Material> getCancelPlacementAndDamage() { return this.cancelPlacementAndDamage; } public static CommonSettings load(ConfigurationSection config) { CommonSettings settings = new CommonSettings(); settings.cancelReinforcementModeInBastionField = config.getBoolean("cancelReinforcementModeInBastionField", false); settings.listBastionTimeout = config.getInt("listBastionTimeout", 2000); List<String> materialNames = config.getStringList("cancelPlacementAndDamage"); settings.cancelPlacementAndDamage = new HashSet<>(); for (String name : materialNames) { Material m = Material.matchMaterial(name); if (m != null) { settings.cancelPlacementAndDamage.add(m); } } return settings; } }
3e0ee16c8f1f769d3bb2ef96939c6869cef70b18
1,672
java
Java
google-ads/src/main/java/com/google/ads/googleads/v8/common/ImageDimensionOrBuilder.java
AndrewMBurke/google-ads-java
207849be2dc1d731ebf1910e3363181b4ff99666
[ "Apache-2.0" ]
109
2018-04-26T19:43:28.000Z
2022-03-24T06:18:50.000Z
google-ads/src/main/java/com/google/ads/googleads/v8/common/ImageDimensionOrBuilder.java
AndrewMBurke/google-ads-java
207849be2dc1d731ebf1910e3363181b4ff99666
[ "Apache-2.0" ]
292
2018-06-07T13:37:37.000Z
2022-03-31T16:28:00.000Z
google-ads/src/main/java/com/google/ads/googleads/v8/common/ImageDimensionOrBuilder.java
AndrewMBurke/google-ads-java
207849be2dc1d731ebf1910e3363181b4ff99666
[ "Apache-2.0" ]
134
2018-05-07T22:01:07.000Z
2022-03-28T13:52:52.000Z
21.714286
96
0.605861
6,322
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v8/common/asset_types.proto package com.google.ads.googleads.v8.common; public interface ImageDimensionOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v8.common.ImageDimension) com.google.protobuf.MessageOrBuilder { /** * <pre> * Height of the image. * </pre> * * <code>int64 height_pixels = 4;</code> * @return Whether the heightPixels field is set. */ boolean hasHeightPixels(); /** * <pre> * Height of the image. * </pre> * * <code>int64 height_pixels = 4;</code> * @return The heightPixels. */ long getHeightPixels(); /** * <pre> * Width of the image. * </pre> * * <code>int64 width_pixels = 5;</code> * @return Whether the widthPixels field is set. */ boolean hasWidthPixels(); /** * <pre> * Width of the image. * </pre> * * <code>int64 width_pixels = 5;</code> * @return The widthPixels. */ long getWidthPixels(); /** * <pre> * A URL that returns the image with this height and width. * </pre> * * <code>string url = 6;</code> * @return Whether the url field is set. */ boolean hasUrl(); /** * <pre> * A URL that returns the image with this height and width. * </pre> * * <code>string url = 6;</code> * @return The url. */ java.lang.String getUrl(); /** * <pre> * A URL that returns the image with this height and width. * </pre> * * <code>string url = 6;</code> * @return The bytes for url. */ com.google.protobuf.ByteString getUrlBytes(); }
3e0ee1dc46ac83a30765a12eb7d732ccb4743a3c
5,494
java
Java
src/main/groovy/time/Duration.java
chanwit/groovy
9cbd75c4ffd69f08333db079e0535446140403b4
[ "Apache-2.0" ]
6
2015-08-26T18:05:01.000Z
2019-01-18T01:10:31.000Z
src/main/groovy/time/Duration.java
chanwit/groovy
9cbd75c4ffd69f08333db079e0535446140403b4
[ "Apache-2.0" ]
8
2020-06-30T23:18:12.000Z
2022-02-01T00:58:05.000Z
src/main/groovy/time/Duration.java
chanwit/groovy
9cbd75c4ffd69f08333db079e0535446140403b4
[ "Apache-2.0" ]
2
2015-11-05T00:53:54.000Z
2019-05-02T22:10:46.000Z
42.914063
148
0.592572
6,323
/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.time; import java.util.Calendar; import java.util.Date; /** * Duration represents time periods which have values independant of the context. * So, whilst we can't say how long a month is without knowing the year and the name of the month, * we know how long a day is independant of the date. * * This is not 100% true for days. * Days can actually be 23, 24 or 25 hours long (due to daylight saving adjustments) * * If you ask Duration to convert itself to milliseconds then it will work on the basis of 24 hours * in a day. If you add or subtract it from a date it will take daylight saving into account. * * @author John Wilson upchh@example.com */ public class Duration extends BaseDuration { public Duration(final int days, final int hours, final int minutes, final int seconds, final int millis) { super(days, hours, minutes, seconds, millis); } public Duration plus(final Duration rhs) { return new Duration(this.getDays() + rhs.getDays(), this.getHours() + rhs.getHours(), this.getMinutes() + rhs.getMinutes(), this.getSeconds() + rhs.getSeconds(), this.getMillis() + rhs.getMillis()); } public Duration plus(final TimeDuration rhs) { return rhs.plus(this); } public DatumDependentDuration plus(final DatumDependentDuration rhs) { return rhs.plus(this); } public Duration minus(final Duration rhs) { return new Duration(this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public TimeDuration minus(final TimeDuration rhs) { return new TimeDuration(this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public DatumDependentDuration minus(final DatumDependentDuration rhs) { return new DatumDependentDuration(-rhs.getYears(), -rhs.getMonths(), this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public TimeDatumDependentDuration minus(final TimeDatumDependentDuration rhs) { return new TimeDatumDependentDuration(-rhs.getYears(), -rhs.getMonths(), this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public long toMilliseconds() { return ((((((long)(this.getDays() * 24 ) + this.getHours()) * 60 + this.getMinutes()) * 60) + this.getSeconds()) * 1000) + this.getMillis(); } public Date getAgo() { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, -this.getDays()); cal.add(Calendar.HOUR_OF_DAY, -this.getHours()); cal.add(Calendar.MINUTE, -this.getMinutes()); cal.add(Calendar.SECOND, -this.getSeconds()); cal.add(Calendar.MILLISECOND, -this.getMillis()); // // SqlDate should not really care about these values but it seems to "remember" them // so we clear them. // We do the adds first incase we get carry into the day field // cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new java.sql.Date(cal.getTimeInMillis()); } public From getFrom() { return new From() { public Date getNow() { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, Duration.this.getDays()); // // SqlDate should not really care about these values but it seems to "remember" them // so we clear them. // We do the adds first incase we get carry into the day field // cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new java.sql.Date(cal.getTimeInMillis()); } }; } }
3e0ee260b9048e02e75f95001461a6cc432c6394
7,672
java
Java
xchange-bitstamp/src/main/java/com/xeiam/xchange/bitstamp/service/streaming/BitstampPusherService.java
sutra/XChange
bdc03577100d7c2c41757c6d50b2262112c96b50
[ "MIT" ]
2
2016-02-10T17:46:57.000Z
2017-06-01T07:41:35.000Z
xchange-bitstamp/src/main/java/com/xeiam/xchange/bitstamp/service/streaming/BitstampPusherService.java
joansmith/XChange
ed8c3a7c24bde836d3ee524327025389a4c9e3f1
[ "MIT" ]
null
null
null
xchange-bitstamp/src/main/java/com/xeiam/xchange/bitstamp/service/streaming/BitstampPusherService.java
joansmith/XChange
ed8c3a7c24bde836d3ee524327025389a4c9e3f1
[ "MIT" ]
null
null
null
29.736434
142
0.712722
6,324
package com.xeiam.xchange.bitstamp.service.streaming; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.java_websocket.WebSocket.READYSTATE; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.pusher.client.Pusher; import com.pusher.client.channel.Channel; import com.pusher.client.channel.SubscriptionEventListener; import com.xeiam.xchange.Exchange; import com.xeiam.xchange.bitstamp.BitstampAdapters; import com.xeiam.xchange.bitstamp.dto.marketdata.BitstampStreamingOrderBook; import com.xeiam.xchange.bitstamp.dto.marketdata.BitstampStreamingTransaction; import com.xeiam.xchange.bitstamp.dto.marketdata.BitstampTransaction; import com.xeiam.xchange.bitstamp.service.polling.BitstampBasePollingService; import com.xeiam.xchange.currency.CurrencyPair; import com.xeiam.xchange.dto.Order; import com.xeiam.xchange.dto.marketdata.OrderBook; import com.xeiam.xchange.dto.marketdata.Trade; import com.xeiam.xchange.dto.trade.LimitOrder; import com.xeiam.xchange.service.streaming.DefaultExchangeEvent; import com.xeiam.xchange.service.streaming.ExchangeEvent; import com.xeiam.xchange.service.streaming.ExchangeEventType; import com.xeiam.xchange.service.streaming.StreamingExchangeService; /** * <p> * Streaming trade service for the Bitstamp exchange * </p> */ public class BitstampPusherService extends BitstampBasePollingService implements StreamingExchangeService { private final Logger logger = LoggerFactory.getLogger(BitstampPusherService.class); // private final ExchangeEventListener exchangeEventListener; private final BlockingQueue<ExchangeEvent> consumerEventQueue = new LinkedBlockingQueue<ExchangeEvent>(); private final ObjectMapper streamObjectMapper; /** * Ensures that exchange-specific configuration is available */ private final BitstampStreamingConfiguration configuration; private Pusher client; private Map<String, Channel> channels; // private ReconnectService reconnectService; /** * Constructor * * @param exchange * @param configuration */ public BitstampPusherService(Exchange exchange, BitstampStreamingConfiguration configuration) { super(exchange); this.configuration = configuration; client = new Pusher(configuration.getPusherKey(), configuration.pusherOptions()); // reconnectService = new ReconnectService(this, configuration); channels = new HashMap<String, Channel>(); streamObjectMapper = new ObjectMapper(); streamObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } @Override public void connect() { // Re-connect is handled by the base ReconnectService when it reads a closed // conn. state client.connect(); channels.clear(); for (String name : configuration.getChannels()) { Channel instance = client.subscribe(name); if (name.equals("order_book")) { bindOrderData(instance); } else if (name.equals("diff_order_book")) { bindDiffOrderData(instance); } else if (name.equals("live_trades")) { bindTradeData(instance); } else { throw new IllegalArgumentException(name); } channels.put(name, instance); } } @Override public void disconnect() { client.disconnect(); channels.clear(); } /** * <p> * Returns next event in consumer event queue, then removes it. * </p> * * @return An ExchangeEvent */ @Override public ExchangeEvent getNextEvent() throws InterruptedException { return consumerEventQueue.take(); } /** * {@inheritDoc} */ @Override public int countEventsAvailable() { return consumerEventQueue.size(); } /** * <p> * Sends a msg over the socket. * </p> */ @Override public void send(String msg) { // There's nothing to send for the current API! } /** * <p> * Query the current state of the socket. * </p> */ @Override public READYSTATE getWebSocketStatus() { // ConnectionState: CONNECTING, CONNECTED, DISCONNECTING, DISCONNECTED, ALL // mapped to: // READYSTATE: NOT_YET_CONNECTED, CONNECTING, OPEN, CLOSING, CLOSED; switch (client.getConnection().getState()) { case CONNECTING: return READYSTATE.CONNECTING; case CONNECTED: return READYSTATE.OPEN; case DISCONNECTING: return READYSTATE.CLOSING; case DISCONNECTED: return READYSTATE.CLOSED; default: return READYSTATE.NOT_YET_CONNECTED; } } private void bindOrderData(Channel chan) { SubscriptionEventListener listener = new SubscriptionEventListener() { @Override public void onEvent(String channelName, String eventName, String data) { ExchangeEvent xevt = null; try { OrderBook snapshot = parseOrderBook(data); xevt = new DefaultExchangeEvent(ExchangeEventType.SUBSCRIBE_ORDERS, data, snapshot); } catch (IOException e) { logger.error("JSON stream error", e); } if (xevt != null) { addToEventQueue(xevt); } } }; chan.bind("data", listener); } private void bindDiffOrderData(Channel chan) { SubscriptionEventListener listener = new SubscriptionEventListener() { @Override public void onEvent(String channelName, String eventName, String data) { ExchangeEvent xevt = null; try { OrderBook delta = parseOrderBook(data); xevt = new DefaultExchangeEvent(ExchangeEventType.DEPTH, data, delta); } catch (IOException e) { logger.error("JSON stream error", e); } if (xevt != null) { addToEventQueue(xevt); } } }; chan.bind("data", listener); } private OrderBook parseOrderBook(String rawJson) throws IOException { BitstampStreamingOrderBook bitstampOrderBook = streamObjectMapper.readValue(rawJson, BitstampStreamingOrderBook.class); List<LimitOrder> asks = BitstampAdapters.createOrders(CurrencyPair.BTC_USD, Order.OrderType.ASK, bitstampOrderBook.getAsks()); List<LimitOrder> bids = BitstampAdapters.createOrders(CurrencyPair.BTC_USD, Order.OrderType.BID, bitstampOrderBook.getBids()); return new OrderBook(null, asks, bids); } private void bindTradeData(Channel chan) { SubscriptionEventListener listener = new SubscriptionEventListener() { @Override public void onEvent(String channelName, String eventName, String data) { ExchangeEvent exchangeEvent = null; try { Trade trade = parseTrade(data); exchangeEvent = new DefaultExchangeEvent(ExchangeEventType.TRADE, data, trade); } catch (IOException e) { logger.error("JSON stream error", e); } if (exchangeEvent != null) { addToEventQueue(exchangeEvent); } } }; chan.bind("trade", listener); } private Trade parseTrade(String rawJson) throws IOException { BitstampTransaction transaction = streamObjectMapper.readValue(rawJson, BitstampStreamingTransaction.class); return new Trade(null, transaction.getAmount(), CurrencyPair.BTC_USD, transaction.getPrice(), null, String.valueOf(transaction.getTid())); } private void addToEventQueue(ExchangeEvent event) { try { consumerEventQueue.put(event); } catch (InterruptedException e) { logger.debug("Event queue interrupted", e); } } }
3e0ee3151fd73046dd28ad797edb20796a11677f
290
java
Java
split-example/android/app/src/main/java/com/example/SampleBActivity.java
desmond1121/react-native-split
982fc0edd6daed41cd1687023235394438f80712
[ "Apache-2.0" ]
154
2017-04-23T12:45:42.000Z
2022-03-13T09:29:14.000Z
split-example/android/app/src/main/java/com/example/SampleBActivity.java
desmond1121/react-native-split
982fc0edd6daed41cd1687023235394438f80712
[ "Apache-2.0" ]
9
2017-06-01T03:02:28.000Z
2018-10-30T07:14:56.000Z
react-native-0.50.4/split-example/android/app/src/main/java/com/example/SampleBActivity.java
vilvil/react-native-demo-split
adb706c3003c3ef6e4b346241cbd64fb9ed5e6e0
[ "Apache-2.0" ]
28
2017-04-24T10:13:06.000Z
2019-03-13T09:36:04.000Z
19.333333
60
0.686207
6,325
package com.example; public class SampleBActivity extends BaseSubBundleActivity { @Override protected String getScriptAssetPath() { return "bundle/sample_b/index.bundle"; } @Override protected String getMainComponentName() { return "SampleB"; } }
3e0ee322ec5703df4322ec4f8dd180f0badbf609
901
java
Java
bookmarks-plus/bookmarks-plus-android-hybrid/src/org/openntf/bookmarksplus/app/SplashScreenActivity.java
OpenNTF/Hackathon2017-P1
982f65626b641b8cc1255f5bb19f171d8b32c6ae
[ "Apache-2.0" ]
null
null
null
bookmarks-plus/bookmarks-plus-android-hybrid/src/org/openntf/bookmarksplus/app/SplashScreenActivity.java
OpenNTF/Hackathon2017-P1
982f65626b641b8cc1255f5bb19f171d8b32c6ae
[ "Apache-2.0" ]
null
null
null
bookmarks-plus/bookmarks-plus-android-hybrid/src/org/openntf/bookmarksplus/app/SplashScreenActivity.java
OpenNTF/Hackathon2017-P1
982f65626b641b8cc1255f5bb19f171d8b32c6ae
[ "Apache-2.0" ]
null
null
null
27.30303
85
0.631521
6,326
/*!COPYRIGHT HEADER! * */ package org.openntf.bookmarksplus.app; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; public class SplashScreenActivity extends Activity { // Splash screen timer private static int SPLASH_TIME_OUT = 3000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splashscreen); new Handler().postDelayed(new Runnable() { @Override public void run() { // This method will be executed once the timer is over Intent i = new Intent(SplashScreenActivity.this, MainActivity.class); startActivity(i); // close this activity finish(); } }, SPLASH_TIME_OUT); } }
3e0ee4a164f6b85a1514bff3a4e73e87180f2eab
5,626
java
Java
ExtractedJars/Shopkick_com.shopkick.app/javafiles/android/support/transition/ViewUtilsApi22.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/Shopkick_com.shopkick.app/javafiles/android/support/transition/ViewUtilsApi22.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/Shopkick_com.shopkick.app/javafiles/android/support/transition/ViewUtilsApi22.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
36.532468
121
0.570565
6,327
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.transition; import android.util.Log; import android.view.View; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; // Referenced classes of package android.support.transition: // ViewUtilsApi21 class ViewUtilsApi22 extends ViewUtilsApi21 { ViewUtilsApi22() { // 0 0:aload_0 // 1 1:invokespecial #19 <Method void ViewUtilsApi21()> // 2 4:return } private void fetchSetLeftTopRightBottomMethod() { if(!sSetLeftTopRightBottomMethodFetched) //* 0 0:getstatic #27 <Field boolean sSetLeftTopRightBottomMethodFetched> //* 1 3:ifne 68 { try { sSetLeftTopRightBottomMethod = ((Class) (android/view/View)).getDeclaredMethod("setLeftTopRightBottom", new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE }); // 2 6:ldc1 #29 <Class View> // 3 8:ldc1 #31 <String "setLeftTopRightBottom"> // 4 10:iconst_4 // 5 11:anewarray Class[] // 6 14:dup // 7 15:iconst_0 // 8 16:getstatic #39 <Field Class Integer.TYPE> // 9 19:aastore // 10 20:dup // 11 21:iconst_1 // 12 22:getstatic #39 <Field Class Integer.TYPE> // 13 25:aastore // 14 26:dup // 15 27:iconst_2 // 16 28:getstatic #39 <Field Class Integer.TYPE> // 17 31:aastore // 18 32:dup // 19 33:iconst_3 // 20 34:getstatic #39 <Field Class Integer.TYPE> // 21 37:aastore // 22 38:invokevirtual #43 <Method Method Class.getDeclaredMethod(String, Class[])> // 23 41:putstatic #45 <Field Method sSetLeftTopRightBottomMethod> sSetLeftTopRightBottomMethod.setAccessible(true); // 24 44:getstatic #45 <Field Method sSetLeftTopRightBottomMethod> // 25 47:iconst_1 // 26 48:invokevirtual #51 <Method void Method.setAccessible(boolean)> } //* 27 51:goto 64 catch(NoSuchMethodException nosuchmethodexception) //* 28 54:astore_1 { Log.i("ViewUtilsApi22", "Failed to retrieve setLeftTopRightBottom method", ((Throwable) (nosuchmethodexception))); // 29 55:ldc1 #11 <String "ViewUtilsApi22"> // 30 57:ldc1 #53 <String "Failed to retrieve setLeftTopRightBottom method"> // 31 59:aload_1 // 32 60:invokestatic #59 <Method int Log.i(String, String, Throwable)> // 33 63:pop } sSetLeftTopRightBottomMethodFetched = true; // 34 64:iconst_1 // 35 65:putstatic #27 <Field boolean sSetLeftTopRightBottomMethodFetched> } // 36 68:return } public void setLeftTopRightBottom(View view, int i, int j, int k, int l) { fetchSetLeftTopRightBottomMethod(); // 0 0:aload_0 // 1 1:invokespecial #67 <Method void fetchSetLeftTopRightBottomMethod()> Method method = sSetLeftTopRightBottomMethod; // 2 4:getstatic #45 <Field Method sSetLeftTopRightBottomMethod> // 3 7:astore 6 if(method != null) //* 4 9:aload 6 //* 5 11:ifnull 69 try { method.invoke(((Object) (view)), new Object[] { Integer.valueOf(i), Integer.valueOf(j), Integer.valueOf(k), Integer.valueOf(l) }); // 6 14:aload 6 // 7 16:aload_1 // 8 17:iconst_4 // 9 18:anewarray Object[] // 10 21:dup // 11 22:iconst_0 // 12 23:iload_2 // 13 24:invokestatic #73 <Method Integer Integer.valueOf(int)> // 14 27:aastore // 15 28:dup // 16 29:iconst_1 // 17 30:iload_3 // 18 31:invokestatic #73 <Method Integer Integer.valueOf(int)> // 19 34:aastore // 20 35:dup // 21 36:iconst_2 // 22 37:iload 4 // 23 39:invokestatic #73 <Method Integer Integer.valueOf(int)> // 24 42:aastore // 25 43:dup // 26 44:iconst_3 // 27 45:iload 5 // 28 47:invokestatic #73 <Method Integer Integer.valueOf(int)> // 29 50:aastore // 30 51:invokevirtual #77 <Method Object Method.invoke(Object, Object[])> // 31 54:pop return; // 32 55:return } //* 33 56:astore_1 //* 34 57:new #79 <Class RuntimeException> //* 35 60:dup //* 36 61:aload_1 //* 37 62:invokevirtual #83 <Method Throwable InvocationTargetException.getCause()> //* 38 65:invokespecial #86 <Method void RuntimeException(Throwable)> //* 39 68:athrow //* 40 69:return // Misplaced declaration of an exception variable catch(View view) //* 41 70:astore_1 { return; // 42 71:return } // Misplaced declaration of an exception variable catch(View view) { throw new RuntimeException(((InvocationTargetException) (view)).getCause()); } else return; } private static final String TAG = "ViewUtilsApi22"; private static Method sSetLeftTopRightBottomMethod; private static boolean sSetLeftTopRightBottomMethodFetched; }