id
int64 | file_name
string | file_path
string | content
string | size
int64 | language
string | extension
string | total_lines
int64 | avg_line_length
float64 | max_line_length
int64 | alphanum_fraction
float64 | repo_name
string | repo_stars
int64 | repo_forks
int64 | repo_open_issues
int64 | repo_license
string | repo_extraction_date
string | exact_duplicates_redpajama
bool | near_duplicates_redpajama
bool | exact_duplicates_githubcode
bool | exact_duplicates_stackv2
bool | exact_duplicates_stackv1
bool | near_duplicates_githubcode
bool | near_duplicates_stackv1
bool | near_duplicates_stackv2
bool | length
int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,315,538
|
A_testFail15.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameParameters/cannotRename/A_testFail15.java
|
//cannot rename to: j
package p;
class A{
void m(int i){
for (int j= 0; j < 10; j++){
}
};
}
| 98
|
Java
|
.java
| 8
| 10.625
| 30
| 0.549451
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 98
|
1,312,872
|
CommonLayoutActionGroup.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/navigator/CommonLayoutActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.navigator;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.navigator.IExtensionStateModel;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.MultiActionGroup;
import org.eclipse.jdt.internal.ui.navigator.IExtensionStateConstants.Values;
import org.eclipse.jdt.internal.ui.packageview.PackagesMessages;
/**
* Adds view menus to switch between flat and hierarchical layout.
*
* @since 3.2
*/
public class CommonLayoutActionGroup extends MultiActionGroup {
public static final String LAYOUT_GROUP_NAME = "layout"; //$NON-NLS-1$
private IExtensionStateModel fStateModel;
private StructuredViewer fStructuredViewer;
private boolean fHasContributedToViewMenu = false;
private IAction fHierarchicalLayout = null;
private IAction fFlatLayoutAction = null;
private IAction[] fActions;
private IMenuManager fLayoutSubMenu;
private class CommonLayoutAction extends Action {
private final boolean fIsFlatLayout;
public CommonLayoutAction(boolean flat) {
super("", AS_RADIO_BUTTON); //$NON-NLS-1$
fIsFlatLayout = flat;
if (fIsFlatLayout) {
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LAYOUT_FLAT_ACTION);
} else {
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LAYOUT_HIERARCHICAL_ACTION);
}
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
@Override
public void run() {
if (fStateModel.getBooleanProperty(Values.IS_LAYOUT_FLAT) != fIsFlatLayout) {
fStateModel.setBooleanProperty(Values.IS_LAYOUT_FLAT, fIsFlatLayout);
fStructuredViewer.getControl().setRedraw(false);
try {
fStructuredViewer.refresh();
} finally {
fStructuredViewer.getControl().setRedraw(true);
}
}
}
}
public CommonLayoutActionGroup(StructuredViewer structuredViewer,
IExtensionStateModel stateModel) {
super();
fStateModel = stateModel;
fStructuredViewer = structuredViewer;
}
@Override
public void fillActionBars(IActionBars actionBars) {
if (!fHasContributedToViewMenu) {
IMenuManager viewMenu = actionBars.getMenuManager();
// Create layout sub menu
if (fLayoutSubMenu == null) {
fLayoutSubMenu = new MenuManager(PackagesMessages.LayoutActionGroup_label);
addActions(fLayoutSubMenu);
viewMenu.insertAfter(IWorkbenchActionConstants.MB_ADDITIONS, new Separator(LAYOUT_GROUP_NAME));
}
viewMenu.appendToGroup(LAYOUT_GROUP_NAME, fLayoutSubMenu);
fHasContributedToViewMenu = true;
}
}
public void unfillActionBars(IActionBars actionBars) {
if (fHasContributedToViewMenu) {
// Create layout sub menu
if (fLayoutSubMenu != null) {
actionBars.getMenuManager().remove(fLayoutSubMenu);
fLayoutSubMenu.dispose();
fLayoutSubMenu= null;
}
fHasContributedToViewMenu = false;
}
}
private IAction[] createActions() {
fFlatLayoutAction = new CommonLayoutAction(true);
fFlatLayoutAction.setText(PackagesMessages.LayoutActionGroup_flatLayoutAction_label);
JavaPluginImages.setLocalImageDescriptors(fFlatLayoutAction, "flatLayout.png"); //$NON-NLS-1$
fHierarchicalLayout = new CommonLayoutAction(false);
fHierarchicalLayout.setText(PackagesMessages.LayoutActionGroup_hierarchicalLayoutAction_label);
JavaPluginImages.setLocalImageDescriptors(fHierarchicalLayout, "hierarchicalLayout.png"); //$NON-NLS-1$
return new IAction[] { fFlatLayoutAction, fHierarchicalLayout };
}
public void setFlatLayout(boolean flatLayout) {
if (fActions == null) {
fActions = createActions();
// indicates check the flat action
setActions(fActions, flatLayout ? 0 : 1);
}
fHierarchicalLayout.setChecked(!flatLayout);
fFlatLayoutAction.setChecked(flatLayout);
}
}
| 4,734
|
Java
|
.java
| 120
| 36.4
| 108
| 0.766027
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 4,734
|
4,582,729
|
Template.java
|
exohood_exohoodcity-discord-server/jarvis/src/main/java/net/dv8tion/jda/api/entities/templates/Template.java
|
/*
* Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.api.entities.templates;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.exceptions.InsufficientPermissionException;
import net.dv8tion.jda.api.managers.TemplateManager;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.internal.JDAImpl;
import net.dv8tion.jda.internal.managers.TemplateManagerImpl;
import net.dv8tion.jda.internal.requests.RestActionImpl;
import net.dv8tion.jda.internal.requests.Route;
import net.dv8tion.jda.internal.utils.Checks;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.time.OffsetDateTime;
/**
* Representation of a Discord Guild Template
* <br>This class is immutable.
*
* @since 4.3.0
*
* @see #resolve(JDA, String)
* @see net.dv8tion.jda.api.entities.Guild#retrieveTemplates() Guild.retrieveTemplates()
*/
public class Template
{
private final JDAImpl api;
private final String code;
private final String name;
private final String description;
private final int uses;
private final User creator;
private final OffsetDateTime createdAt;
private final OffsetDateTime updatedAt;
private final TemplateGuild guild;
private final boolean synced;
protected TemplateManager manager;
public Template(final JDAImpl api, final String code, final String name, final String description,
final int uses, final User creator, final OffsetDateTime createdAt, final OffsetDateTime updatedAt,
final TemplateGuild guild, final boolean synced)
{
this.api = api;
this.code = code;
this.name = name;
this.description = description;
this.uses = uses;
this.creator = creator;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.guild = guild;
this.synced = synced;
}
/**
* Retrieves a new {@link net.dv8tion.jda.api.entities.templates.Template Template} instance for the given template code.
*
* <p>Possible {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} include:
* <ul>
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_GUILD_TEMPLATE Unknown Guild Template}
* <br>The template doesn't exist.</li>
* </ul>
*
* @param api
* The JDA instance
* @param code
* A valid template code
*
* @throws java.lang.IllegalArgumentException
* <ul>
* <li>If the provided code is null or empty</li>
* <li>If the provided code contains a whitespace</li>
* <li>If the provided JDA object is null</li>
* </ul>
*
* @return {@link net.dv8tion.jda.api.requests.RestAction RestAction} - Type: {@link net.dv8tion.jda.api.entities.templates.Template Template}
* <br>The Template object
*/
@Nonnull
public static RestAction<Template> resolve(final JDA api, final String code)
{
Checks.notEmpty(code, "code");
Checks.noWhitespace(code, "code");
Checks.notNull(api, "api");
Route.CompiledRoute route = Route.Templates.GET_TEMPLATE.compile(code);
JDAImpl jda = (JDAImpl) api;
return new RestActionImpl<>(api, route, (response, request) ->
jda.getEntityBuilder().createTemplate(response.getObject()));
}
/**
* Syncs this template.
* <br>Requires {@link net.dv8tion.jda.api.Permission#MANAGE_SERVER MANAGE_SERVER} in the template's guild.
* Will throw an {@link net.dv8tion.jda.api.exceptions.InsufficientPermissionException InsufficientPermissionException} otherwise.
*
* @throws IllegalStateException
* If the account is not in the template's guild
* @throws net.dv8tion.jda.api.exceptions.InsufficientPermissionException
* If the account does not have {@link net.dv8tion.jda.api.Permission#MANAGE_SERVER MANAGE_SERVER} in the template's guild
*
* @return {@link net.dv8tion.jda.api.requests.RestAction RestAction} - Type: {@link net.dv8tion.jda.api.entities.templates.Template Template}
* <br>The synced Template object
*/
@Nonnull
@CheckReturnValue
public RestAction<Template> sync()
{
checkInteraction();
final Route.CompiledRoute route = Route.Templates.SYNC_TEMPLATE.compile(guild.getId(), this.code);
return new RestActionImpl<>(api, route, (response, request) ->
api.getEntityBuilder().createTemplate(response.getObject()));
}
/**
* Deletes this template.
* <br>Requires {@link net.dv8tion.jda.api.Permission#MANAGE_SERVER MANAGE_SERVER} in the template's guild.
* Will throw an {@link net.dv8tion.jda.api.exceptions.InsufficientPermissionException InsufficientPermissionException} otherwise.
*
* @throws IllegalStateException
* If the account is not in the template's guild
* @throws net.dv8tion.jda.api.exceptions.InsufficientPermissionException
* If the account does not have {@link net.dv8tion.jda.api.Permission#MANAGE_SERVER MANAGE_SERVER} in the template's guild
*
* @return {@link net.dv8tion.jda.api.requests.RestAction RestAction}
*/
@Nonnull
@CheckReturnValue
public RestAction<Void> delete()
{
checkInteraction();
final Route.CompiledRoute route = Route.Templates.DELETE_TEMPLATE.compile(guild.getId(), this.code);
return new RestActionImpl<>(api, route);
}
/**
* The template code.
*
* @return The template code
*/
@Nonnull
public String getCode()
{
return this.code;
}
/**
* The template name.
*
* @return The template name
*/
@Nonnull
public String getName()
{
return this.name;
}
/**
* The template description.
*
* @return The template description
*/
@Nullable
public String getDescription()
{
return this.description;
}
/**
* How often this template has been used.
*
* @return The uses of this template
*/
public int getUses()
{
return this.uses;
}
/**
* The user who created this template.
*
* @return The user who created this template
*/
@Nonnull
public User getCreator()
{
return this.creator;
}
/**
* Returns creation date of this template.
*
* @return The creation date of this template
*/
@Nonnull
public OffsetDateTime getTimeCreated()
{
return this.createdAt;
}
/**
* Returns the last update date of this template.
* <br>If this template has never been updated, this returns the date of creation.
*
* @return The last update date of this template
*
* @see #getTimeCreated()
*/
@Nonnull
public OffsetDateTime getTimeUpdated()
{
return this.updatedAt;
}
/**
* A {@link TemplateGuild Template.Guild} object
* containing information about this template's origin guild.
*
* @return Information about this template's origin guild
*
* @see TemplateGuild
*/
@Nonnull
public TemplateGuild getGuild()
{
return this.guild;
}
/**
* Whether or not this template is synced.
*
* @return True, if this template matches the current guild structure
*/
public boolean isSynced()
{
return this.synced;
}
/**
* Returns the {@link net.dv8tion.jda.api.managers.TemplateManager TemplateManager} for this Template.
* <br>In the TemplateManager, you can modify the name or description of the template.
* You modify multiple fields in one request by chaining setters before calling {@link net.dv8tion.jda.api.requests.RestAction#queue() RestAction.queue()}.
*
* <p>This is a lazy idempotent getter. The manager is retained after the first call.
* This getter is not thread-safe and would require guards by the user.
*
* @throws IllegalStateException
* If the account is not in the template's guild
* @throws net.dv8tion.jda.api.exceptions.InsufficientPermissionException
* If the currently logged in account does not have {@link net.dv8tion.jda.api.Permission#MANAGE_SERVER MANAGE_SERVER}
*
* @return The TemplateManager of this Template
*/
@Nonnull
public TemplateManager getManager()
{
checkInteraction();
if (manager == null)
return manager = new TemplateManagerImpl(this);
return manager;
}
private void checkInteraction()
{
final net.dv8tion.jda.api.entities.Guild guild = this.api.getGuildById(this.guild.getIdLong());
if (guild == null)
throw new IllegalStateException("Cannot interact with a template without shared guild");
if (!guild.getSelfMember().hasPermission(Permission.MANAGE_SERVER))
throw new InsufficientPermissionException(guild, Permission.MANAGE_SERVER);
}
/**
* The {@link net.dv8tion.jda.api.JDA JDA} instance used to create this Template instance.
*
* @return The corresponding JDA instance
*/
@Nonnull
public JDA getJDA()
{
return this.api;
}
@Override
public int hashCode()
{
return code.hashCode();
}
@Override
public boolean equals(Object obj)
{
if (obj == this)
return true;
if (!(obj instanceof Template))
return false;
Template impl = (Template) obj;
return impl.code.equals(this.code);
}
@Override
public String toString()
{
return "Template(" + this.code + ")";
}
}
| 10,920
|
Java
|
.java
| 301
| 29.342193
| 160
| 0.653857
|
exohood/exohoodcity-discord-server
| 2
| 1
| 0
|
GPL-3.0
|
9/5/2024, 12:18:21 AM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 10,920
|
4,345,579
|
SimLoaderTest.java
|
eMoflon_cobolt/simonstrator-simrunner/src/de/tudarmstadt/maki/simonstrator/peerfact/multirunner/SimLoaderTest.java
|
package de.tudarmstadt.maki.simonstrator.peerfact.multirunner;
/**
* A basic Simulation Loader Test.
*
* @author bjoern
*
*/
public class SimLoaderTest implements SimulationLoader {
@Override
public void initialize(String[] args) {
// not interested.
}
@Override
public boolean loadSimulations(Callback callback) {
callback.addSimulation(new SimulationDescription("Test 1",
"config/pubsub/batch/minimal/pubsub_mini.xml"));
callback.addSimulation(new SimulationDescription("Test 2",
"config/pubsub/batch/minimal/pubsub_mini.xml"));
callback.addSimulation(new SimulationDescription("Test 3",
"config/pubsub/batch/minimal/pubsub_mini.xml"));
callback.addSimulation(new SimulationDescription("Test 4",
"config/pubsub/batch/minimal/pubsub_mini.xml"));
System.out.println("Loaded four test configs...");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
@Override
public int getNumberOfParallelInstances() {
return 2;
}
}
| 1,031
|
Java
|
.java
| 35
| 26.571429
| 62
| 0.760606
|
eMoflon/cobolt
| 2
| 1
| 0
|
GPL-3.0
|
9/5/2024, 12:10:02 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 1,031
|
2,956,338
|
Parameter.java
|
ahmetaa_lium-diarization/src/fr/lium/spkDiarization/parameter/Parameter.java
|
/**
*
* <p>
* Param
* </p>
*
* @author <a href="mailto:[email protected]">Sylvain Meignier</a>
* @author <a href="mailto:[email protected]">Gael Salaun</a>
* @author <a href="mailto:[email protected]">Teva Merlin</a>
* @version v2.0
*
* Copyright (c) 2007-2009 Universite du Maine. All Rights Reserved. Use is subject to license terms.
*
* THIS SOFTWARE IS PROVIDED BY THE "UNIVERSITE DU MAINE" 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 REGENTS AND 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 fr.lium.spkDiarization.parameter;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.cmu.sphinx.util.Utilities;
import fr.lium.spkDiarization.lib.SpkDiarizationLogger;
import gnu.getopt.Getopt;
/**
* The Class Parameter.
*/
public class Parameter implements Cloneable {
/** The Constant logger. */
private final static Logger logger = Logger.getLogger(Parameter.class.getName());
/** The Default charset. */
public static Charset DefaultCharset = Charset.forName("ISO-8859-1");
/** The show. */
public String show; // Current show name.
/** The help. */
public Boolean help;
/**
* The Class ActionHelp.
*/
private class ActionHelp extends LongOptAction {
/*
* (non-Javadoc)
* @see fr.lium.spkDiarization.parameter.LongOptAction#execute(java.lang.String)
*/
@Override
public void execute(String arg) {
help = true;
}
/*
* (non-Javadoc)
* @see fr.lium.spkDiarization.parameter.LongOptAction#getValue()
*/
@Override
public String getValue() {
return help.toString();
}
}
/** The logger level. */
public Level loggerLevel = Level.INFO;
/**
* The Class ActionLoggerLevel.
*/
private class ActionLoggerLevel extends LongOptAction {
/*
* (non-Javadoc)
* @see fr.lium.spkDiarization.parameter.LongOptAction#execute(java.lang.String)
*/
@Override
public void execute(String optarg) {
SpkDiarizationLogger.setLevel(optarg);
}
/*
* (non-Javadoc)
* @see fr.lium.spkDiarization.parameter.LongOptAction#getValue()
*/
@Override
public String getValue() {
return loggerLevel.toString();
}
}
// Video Parameters
/** The parameter video input feature. */
private ParameterVideoInputFeature parameterVideoInputFeature;
// Audio Parameters
/** The parameter input feature. */
private ParameterAudioInputFeature parameterInputFeature;
/** The parameter input feature2. */
private ParameterInputFeature2 parameterInputFeature2;
/** The parameter output feature. */
private ParameterAudioOutputFeature parameterOutputFeature;
/** The parameter segmentation. */
private ParameterSegmentation parameterSegmentation;
/** The parameter clustering. */
private ParameterClustering parameterClustering;
/** The parameter em. */
private ParameterEM parameterEM;
/** The parameter ehmm. */
private ParameterEHMM parameterEHMM;
/** The parameter map. */
private ParameterMAP parameterMAP;
/** The parameter variance control. */
private ParameterVarianceControl parameterVarianceControl;
/** The parameter score. */
private ParameterScore parameterScore;
/** The parameter decoder. */
private ParameterDecoder parameterDecoder;
/** The parameter filter. */
private ParameterFilter parameterFilter;
/** The parameter adjust segmentation. */
private ParameterAdjustSegmentation parameterAdjustSegmentation;
/** The parameter top gaussian. */
private ParameterTopGaussian parameterTopGaussian;
/** The parameter named speaker. */
private ParameterNamedSpeaker parameterNamedSpeaker;
/** The parameter segmentation split. */
private ParameterSegmentationSplit parameterSegmentationSplit;
/** The parameter model. */
private ParameterModel parameterModel;
/** The parameter initialization em. */
private ParameterInitializationEM parameterInitializationEM;
/** The parameter segmentation input file. */
private ParameterSegmentationInputFile parameterSegmentationInputFile;
/** The parameter segmentation input file2. */
private ParameterSegmentationInputFile2 parameterSegmentationInputFile2;
/** The parameter segmentation input file3. */
private ParameterSegmentationInputFile3 parameterSegmentationInputFile3;
/** The parameter segmentation output file. */
private ParameterSegmentationOutputFile parameterSegmentationOutputFile;
/** The parameter segmentation filter file. */
private ParameterSegmentationFilterFile parameterSegmentationFilterFile;
/** The parameter model set output file. */
private ParameterModelSetOutputFile parameterModelSetOutputFile;
/** The parameter model set input file. */
private ParameterModelSetInputFile parameterModelSetInputFile;
/** The parameter model set input file2. */
private ParameterModelSetInputFile2 parameterModelSetInputFile2;
/** The parameter diarization. */
private ParameterBNDiarization parameterDiarization;
/** The parameter normlization. */
private ParameterIVectorNormalization parameterNormlization;
/** The parameter ilp. */
private ParameterILP parameterILP;
/** The parameter total variability. */
private ParameterTotalVariability parameterTotalVariability;
// GetOption
/** The option list. */
private ArrayList<LongOptWithAction> optionList = new ArrayList<LongOptWithAction>();
/** The local option list. */
private ArrayList<LongOptWithAction> localOptionList = new ArrayList<LongOptWithAction>();
/** The nb options. */
private static int nbOptions = 100;
/** The list of parameter object. */
private ArrayList<ParameterBase> listOfParameterObject = new ArrayList<ParameterBase>();
/**
* Gets the next option index.
*
* @return the next option index
*/
public static int getNextOptionIndex() {
return nbOptions++;
}
/**
* Instantiates a new parameter.
*/
public Parameter() {
parameterSegmentationInputFile = new ParameterSegmentationInputFile(this);
parameterSegmentationInputFile2 = new ParameterSegmentationInputFile2(this);
parameterSegmentationInputFile3 = new ParameterSegmentationInputFile3(this);
parameterSegmentationOutputFile = new ParameterSegmentationOutputFile(this);
parameterSegmentationFilterFile = new ParameterSegmentationFilterFile(this);
parameterEM = new ParameterEM(this);
parameterEHMM = new ParameterEHMM(this);
parameterVarianceControl = new ParameterVarianceControl(this);
parameterMAP = new ParameterMAP(this);
parameterClustering = new ParameterClustering(this);
parameterSegmentation = new ParameterSegmentation(this);
// parameterSpeechDetector = new ParameterSpeechDetector(this);
parameterScore = new ParameterScore(this);
parameterDecoder = new ParameterDecoder(this);
parameterFilter = new ParameterFilter(this);
parameterAdjustSegmentation = new ParameterAdjustSegmentation(this);
parameterTopGaussian = new ParameterTopGaussian(this);
parameterNamedSpeaker = new ParameterNamedSpeaker(this);
parameterSegmentationSplit = new ParameterSegmentationSplit(this);
parameterModel = new ParameterModel(this);
parameterInitializationEM = new ParameterInitializationEM(this);
parameterInputFeature = new ParameterAudioInputFeature(this);
parameterInputFeature2 = new ParameterInputFeature2(this);
parameterOutputFeature = new ParameterAudioOutputFeature(this);
parameterModelSetOutputFile = new ParameterModelSetOutputFile(this);
parameterModelSetInputFile = new ParameterModelSetInputFile(this);
parameterModelSetInputFile2 = new ParameterModelSetInputFile2(this);
parameterDiarization = new ParameterBNDiarization(this);
parameterVideoInputFeature = new ParameterVideoInputFeature(this);
parameterNormlization = new ParameterIVectorNormalization(this);
parameterTotalVariability = new ParameterTotalVariability(this);
parameterILP = new ParameterILP(this);
for (Field field : Parameter.class.getDeclaredFields()) {
// field.setAccessible(true);
if (field.getName().startsWith("parameter") == true) {
ParameterBase p;
try {
p = (ParameterBase) field.get(this);
listOfParameterObject.add(p);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
addOptions(new LongOptWithAction("logger", new ActionLoggerLevel(), "logger level"));
addOptions(new LongOptWithAction("help", 0, new ActionHelp(), "help wanted"));
show = "";
help = false;
}
/**
* Adds the sub parameter.
*
* @param parameterBase the parameter base
* @return the parameter base
*/
protected ParameterBase addSubParameter(ParameterBase parameterBase) {
listOfParameterObject.add(parameterBase);
return parameterBase;
}
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public Parameter clone() throws CloneNotSupportedException {
Parameter parameter = (Parameter) super.clone();
parameter.parameterInputFeature = parameterInputFeature.clone();
parameter.parameterInputFeature2 = parameterInputFeature2.clone();
parameter.parameterOutputFeature = parameterOutputFeature.clone();
parameter.parameterSegmentation = parameterSegmentation.clone();
parameter.parameterClustering = parameterClustering.clone();
parameter.parameterEM = parameterEM.clone();
parameter.parameterEHMM = parameterEHMM.clone();
parameter.parameterMAP = parameterMAP.clone();
parameter.parameterVarianceControl = parameterVarianceControl.clone();
parameter.parameterScore = parameterScore.clone();
parameter.parameterDecoder = parameterDecoder.clone();
parameter.parameterFilter = parameterFilter.clone();
parameter.parameterAdjustSegmentation = parameterAdjustSegmentation.clone();
parameter.parameterTopGaussian = parameterTopGaussian.clone();
parameter.parameterNamedSpeaker = parameterNamedSpeaker.clone();
parameter.parameterSegmentationSplit = parameterSegmentationSplit.clone();
parameter.parameterModel = parameterModel.clone();
parameter.parameterInitializationEM = parameterInitializationEM.clone();
parameter.parameterSegmentationInputFile = parameterSegmentationInputFile.clone();
parameter.parameterSegmentationInputFile2 = parameterSegmentationInputFile2.clone();
parameter.parameterSegmentationInputFile3 = parameterSegmentationInputFile3.clone();
parameter.parameterSegmentationOutputFile = parameterSegmentationOutputFile.clone();
parameter.parameterSegmentationFilterFile = parameterSegmentationFilterFile.clone();
parameter.parameterModelSetOutputFile = parameterModelSetOutputFile.clone();
parameter.parameterModelSetInputFile = parameterModelSetInputFile.clone();
parameter.parameterModelSetInputFile2 = parameterModelSetInputFile2.clone();
parameter.parameterDiarization = parameterDiarization.clone();
parameter.parameterVideoInputFeature = parameterVideoInputFeature.clone();
parameter.parameterNormlization = parameterNormlization.clone();
parameter.parameterILP = parameterILP.clone();
parameter.parameterTotalVariability = parameterTotalVariability.clone();
return parameter;
}
/**
* Adds the options.
*
* @param option the option
*/
public void addOptions(LongOptWithAction option) {
localOptionList.add(option);
optionList.add(option);
}
/**
* Log cmd line.
*
* @param args the args
*/
public void logCmdLine(String[] args) {
getSeparator2();
String message = "cmdLine:";
for (String arg : args) {
message += " " + arg;
}
logger.config(message);
getSeparator2();
}
/**
* Read parameters.
*
* @param args the args
*/
public void readParameters(String args[]) {
int c;
if (SpkDiarizationLogger.DEBUG) for (int i = 0; i < optionList.size(); i++) {
logger.finest("name:" + optionList.get(i).getName() + " idx=" + optionList.get(i).getVal());
}
LongOptWithAction[] LongOptWithActions = new LongOptWithAction[optionList.size()];
optionList.toArray(LongOptWithActions);
String message = new SimpleDateFormat("hh:mm.SSS").format(System.currentTimeMillis());
message += Utilities.pad(" Parameter ", 15);
message += Utilities.pad("WARNING ", 6);
message += "| ";
Getopt getOpt = new Getopt(message, args, "-", LongOptWithActions);
String optarg;
while ((c = getOpt.getopt()) != -1) {
optarg = getOpt.getOptarg();
for (ParameterBase p : listOfParameterObject) {
p.readParameter(c, optarg);
continue;
}
for (LongOptWithAction option : localOptionList) {
if (c == option.getVal()) {
option.execute(optarg);
continue;
}
}
if (c == 1) {
show = optarg;
}
}
}
/**
* Gets the separator2.
*
* @return the separator2
*/
public String getSeparator2() {
return " ====================================================== ";
}
/**
* Gets the separator.
*
* @return the separator
*/
public String getSeparator() {
return " ------------------------------------------------------ ";
}
/**
* Log show.
*/
public void logShow() {
logger.config("[options] show:" + show);
}
/**
* Gets the default charset.
*
* @return the defaultCharset
*/
protected static Charset getDefaultCharset() {
return DefaultCharset;
}
/**
* Gets the show.
*
* @return the show
*/
public String getShow() {
return show;
}
/**
* Checks if is help.
*
* @return the help
*/
public boolean isHelp() {
return help;
}
/**
* Gets the parameter video input feature.
*
* @return the parameter video input feature
*/
public ParameterVideoInputFeature getParameterVideoInputFeature() {
return parameterVideoInputFeature;
}
/**
* Gets the parameter input feature.
*
* @return the parameter input feature
*/
public ParameterAudioInputFeature getParameterInputFeature() {
return parameterInputFeature;
}
/**
* Gets the parameter input feature2.
*
* @return the parameter input feature2
*/
public ParameterInputFeature2 getParameterInputFeature2() {
return parameterInputFeature2;
}
/**
* Gets the parameter output feature.
*
* @return the parameter output feature
*/
public ParameterAudioOutputFeature getParameterOutputFeature() {
return parameterOutputFeature;
}
/**
* Gets the parameter segmentation.
*
* @return the parameter segmentation
*/
public ParameterSegmentation getParameterSegmentation() {
return parameterSegmentation;
}
/**
* Gets the parameter clustering.
*
* @return the parameter clustering
*/
public ParameterClustering getParameterClustering() {
return parameterClustering;
}
/**
* Gets the parameter em.
*
* @return the parameter em
*/
public ParameterEM getParameterEM() {
return parameterEM;
}
/**
* Gets the parameter ehmm.
*
* @return the parameter ehmm
*/
public ParameterEHMM getParameterEHMM() {
return parameterEHMM;
}
/**
* Gets the parameter map.
*
* @return the parameter map
*/
public ParameterMAP getParameterMAP() {
return parameterMAP;
}
/**
* Gets the parameter variance control.
*
* @return the parameter variance control
*/
public ParameterVarianceControl getParameterVarianceControl() {
return parameterVarianceControl;
}
/**
* Gets the parameter score.
*
* @return the parameter score
*/
public ParameterScore getParameterScore() {
return parameterScore;
}
/**
* Gets the parameter decoder.
*
* @return the parameter decoder
*/
public ParameterDecoder getParameterDecoder() {
return parameterDecoder;
}
/**
* Gets the parameter filter.
*
* @return the parameter filter
*/
public ParameterFilter getParameterFilter() {
return parameterFilter;
}
/**
* Gets the parameter adjust segmentation.
*
* @return the parameter adjust segmentation
*/
public ParameterAdjustSegmentation getParameterAdjustSegmentation() {
return parameterAdjustSegmentation;
}
/**
* Gets the parameter top gaussian.
*
* @return the parameter top gaussian
*/
public ParameterTopGaussian getParameterTopGaussian() {
return parameterTopGaussian;
}
/**
* Gets the parameter named speaker.
*
* @return the parameter named speaker
*/
public ParameterNamedSpeaker getParameterNamedSpeaker() {
return parameterNamedSpeaker;
}
/**
* Gets the parameter segmentation split.
*
* @return the parameter segmentation split
*/
public ParameterSegmentationSplit getParameterSegmentationSplit() {
return parameterSegmentationSplit;
}
/**
* Gets the parameter model.
*
* @return the parameter model
*/
public ParameterModel getParameterModel() {
return parameterModel;
}
/**
* Gets the parameter initialization em.
*
* @return the parameter initialization em
*/
public ParameterInitializationEM getParameterInitializationEM() {
return parameterInitializationEM;
}
/**
* Gets the parameter segmentation input file2.
*
* @return the parameter segmentation input file2
*/
public ParameterSegmentationInputFile2 getParameterSegmentationInputFile2() {
return parameterSegmentationInputFile2;
}
/**
* Gets the parameter segmentation input file3.
*
* @return the parameter segmentation input file3
*/
public ParameterSegmentationInputFile3 getParameterSegmentationInputFile3() {
return parameterSegmentationInputFile3;
}
/**
* Gets the parameter segmentation output file.
*
* @return the parameter segmentation output file
*/
public ParameterSegmentationOutputFile getParameterSegmentationOutputFile() {
return parameterSegmentationOutputFile;
}
/**
* Gets the parameter segmentation filter file.
*
* @return the parameter segmentation filter file
*/
public ParameterSegmentationFilterFile getParameterSegmentationFilterFile() {
return parameterSegmentationFilterFile;
}
/**
* Gets the parameter model set output file.
*
* @return the parameter model set output file
*/
public ParameterModelSetOutputFile getParameterModelSetOutputFile() {
return parameterModelSetOutputFile;
}
/**
* Gets the parameter model set input file.
*
* @return the parameter model set input file
*/
public ParameterModelSetInputFile getParameterModelSetInputFile() {
return parameterModelSetInputFile;
}
/**
* Gets the parameter diarization.
*
* @return the parameter diarization
*/
public ParameterBNDiarization getParameterDiarization() {
return parameterDiarization;
}
/**
* Gets the parameter segmentation input file.
*
* @return the parameter segmentation input file
*/
public ParameterSegmentationInputFile getParameterSegmentationInputFile() {
return parameterSegmentationInputFile;
}
/**
* Gets the option list.
*
* @return the option list
*/
public ArrayList<LongOptWithAction> getOptionList() {
return optionList;
}
/**
* Gets the parameter normlization.
*
* @return the parameter normlization
*/
public ParameterIVectorNormalization getParameterNormlization() {
return parameterNormlization;
}
/**
* Gets the parameter model set input file2.
*
* @return the parameter model set input file2
*/
public ParameterModelSetInputFile2 getParameterModelSetInputFile2() {
return parameterModelSetInputFile2;
}
/**
* Gets the parameter ilp.
*
* @return the parameterILP
*/
public ParameterILP getParameterILP() {
return parameterILP;
}
/**
* Gets the parameter total variability.
*
* @return the parameterIVector
*/
public ParameterTotalVariability getParameterTotalVariability() {
return parameterTotalVariability;
}
}
| 20,355
|
Java
|
.java
| 634
| 29.187697
| 250
| 0.766043
|
ahmetaa/lium-diarization
| 5
| 7
| 0
|
GPL-3.0
|
9/4/2024, 10:38:27 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 20,355
|
3,028,280
|
_284_MuertosFeather.java
|
Hl4p3x_L2Scripts_H5_2268/dist/gameserver/data/scripts/quests/_284_MuertosFeather.java
|
package quests;
import l2s.gameserver.model.instances.NpcInstance;
import l2s.gameserver.model.quest.QuestState;
/**
* Квест Muertos Feather
*
* @author Sergey Ibryaev aka Artful
*/
public class _284_MuertosFeather extends QuestScript
{
//NPC
private static final int Trevor = 32166;
//Quest Item
private static final int MuertosFeather = 9748;
//MOBs
private static final int MuertosGuard = 22239;
private static final int MuertosScout = 22240;
private static final int MuertosWarrior = 22242;
private static final int MuertosCaptain = 22243;
private static final int MuertosLieutenant = 22245;
private static final int MuertosCommander = 22246;
//Drop Cond
//# [COND, NEWCOND, ID, REQUIRED, ITEM, NEED_COUNT, CHANCE, DROP]
private static final int[][] DROPLIST_COND = {
{
1,
0,
MuertosGuard,
0,
MuertosFeather,
0,
44,
1
},
{
1,
0,
MuertosScout,
0,
MuertosFeather,
0,
48,
1
},
{
1,
0,
MuertosWarrior,
0,
MuertosFeather,
0,
56,
1
},
{
1,
0,
MuertosCaptain,
0,
MuertosFeather,
0,
60,
1
},
{
1,
0,
MuertosLieutenant,
0,
MuertosFeather,
0,
64,
1
},
{
1,
0,
MuertosCommander,
0,
MuertosFeather,
0,
69,
1
}
};
public _284_MuertosFeather()
{
super(PARTY_NONE, REPEATABLE);
addStartNpc(Trevor);
addTalkId(Trevor);
//Mob Drop
for(int i = 0; i < DROPLIST_COND.length; i++)
addKillId(DROPLIST_COND[i][2]);
addQuestItem(MuertosFeather);
}
@Override
public String onEvent(String event, QuestState st, NpcInstance npc)
{
String htmltext = event;
if(event.equalsIgnoreCase("trader_treauvi_q0284_0103.htm"))
{
st.setCond(1);
}
else if(event.equalsIgnoreCase("trader_treauvi_q0284_0203.htm"))
{
long counts = st.getQuestItemsCount(MuertosFeather) * 45;
st.takeItems(MuertosFeather, -1);
st.giveItems(ADENA_ID, counts, true, true);
}
else if(event.equalsIgnoreCase("trader_treauvi_q0284_0204.htm"))
st.finishQuest();
return htmltext;
}
@Override
public String onTalk(NpcInstance npc, QuestState st)
{
int npcId = npc.getNpcId();
String htmltext = NO_QUEST_DIALOG;
int cond = st.getCond();
if(npcId == Trevor)
if(cond == 0)
{
if(st.getPlayer().getLevel() < 11)
htmltext = "trader_treauvi_q0284_0102.htm";
else
htmltext = "trader_treauvi_q0284_0101.htm";
}
else if(cond == 1 && st.getQuestItemsCount(MuertosFeather) == 0)
htmltext = "trader_treauvi_q0284_0103.htm";
else
htmltext = "trader_treauvi_q0284_0105.htm";
return htmltext;
}
@Override
public String onKill(NpcInstance npc, QuestState st)
{
int npcId = npc.getNpcId();
int cond = st.getCond();
for(int i = 0; i < DROPLIST_COND.length; i++)
if(cond == DROPLIST_COND[i][0] && npcId == DROPLIST_COND[i][2])
if(DROPLIST_COND[i][3] == 0 || st.getQuestItemsCount(DROPLIST_COND[i][3]) > 0)
if(DROPLIST_COND[i][5] == 0)
st.rollAndGive(DROPLIST_COND[i][4], DROPLIST_COND[i][7], DROPLIST_COND[i][6]);
else if(st.rollAndGive(DROPLIST_COND[i][4], DROPLIST_COND[i][7], DROPLIST_COND[i][7], DROPLIST_COND[i][5], DROPLIST_COND[i][6]))
if(DROPLIST_COND[i][1] != cond && DROPLIST_COND[i][1] != 0)
{
st.setCond(Integer.valueOf(DROPLIST_COND[i][1]));
}
return null;
}
}
| 3,468
|
Java
|
.java
| 151
| 18.801325
| 133
| 0.653148
|
Hl4p3x/L2Scripts_H5_2268
| 5
| 6
| 0
|
GPL-3.0
|
9/4/2024, 10:43:16 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| true
| true
| 3,463
|
2,867,757
|
Send_rendez.java
|
statalign_statalign/lib/mpj-v0_44/test/mpi/pt2pt/Send_rendez.java
|
package mpi.pt2pt;
import mpi.*;
import java.util.Arrays;
public class Send_rendez {
int DATA_SIZE = 131073;
public Send_rendez() {
}
public Send_rendez(String args[]) throws Exception {
MPI.Init(args);
int me = MPI.COMM_WORLD.Rank();
int intArray[] = new int[DATA_SIZE];
float floatArray[] = new float[DATA_SIZE];
double doubleArray[] = new double[DATA_SIZE];
long longArray[] = new long[DATA_SIZE];
boolean booleanArray[] = new boolean[DATA_SIZE];
short shortArray[] = new short[DATA_SIZE];
char charArray[] = new char[DATA_SIZE];
byte byteArray[] = new byte[DATA_SIZE];
int intReadArray[] = new int[DATA_SIZE];
float floatReadArray[] = new float[DATA_SIZE];
double doubleReadArray[] = new double[DATA_SIZE];
long longReadArray[] = new long[DATA_SIZE];
boolean booleanReadArray[] = new boolean[DATA_SIZE];
short shortReadArray[] = new short[DATA_SIZE];
char charReadArray[] = new char[DATA_SIZE];
byte byteReadArray[] = new byte[DATA_SIZE];
for (int i = 0; i < intArray.length; i++) {
intArray[i] = i + 1;
floatArray[i] = i + 11;
doubleArray[i] = i + 11.11;
longArray[i] = i + 11;
booleanArray[i] = true;
shortArray[i] = 1;
charArray[i] = 's';
byteArray[i] = 's';
intReadArray[i] = 3;
floatReadArray[i] = i + 19;
doubleReadArray[i] = i + 99.11;
longReadArray[i] = i + 9;
shortReadArray[i] = 2;
booleanReadArray[i] = false;
charReadArray[i] = 'x';
byteReadArray[i] = 'x';
}
if (MPI.COMM_WORLD.Rank() == 0) {
MPI.COMM_WORLD.Send(intArray, 0, DATA_SIZE, MPI.INT, 1, 999);
MPI.COMM_WORLD.Send(byteArray, 0, DATA_SIZE, MPI.BYTE, 1, 998);
MPI.COMM_WORLD.Send(charArray, 0, DATA_SIZE, MPI.CHAR, 1, 997);
MPI.COMM_WORLD.Send(doubleArray, 0, DATA_SIZE, MPI.DOUBLE, 1, 996);
MPI.COMM_WORLD.Send(longArray, 0, DATA_SIZE, MPI.LONG, 1, 995);
MPI.COMM_WORLD.Send(booleanArray, 0, DATA_SIZE, MPI.BOOLEAN, 1, 994);
MPI.COMM_WORLD.Send(shortArray, 0, DATA_SIZE, MPI.SHORT, 1, 993);
MPI.COMM_WORLD.Send(floatArray, 0, DATA_SIZE, MPI.FLOAT, 1, 992);
// System.out.println("Send Completed \n\n");
} else if (MPI.COMM_WORLD.Rank() == 1) {
// try { Thread.currentThread().sleep(DATA_SIZE); }catch(Exception e){}
// System.out.println(" ** Recv calling ** ");
MPI.COMM_WORLD.Recv(intReadArray, 0, DATA_SIZE, MPI.INT, 0, 999);
MPI.COMM_WORLD.Recv(byteReadArray, 0, DATA_SIZE, MPI.BYTE, 0, 998);
MPI.COMM_WORLD.Recv(charReadArray, 0, DATA_SIZE, MPI.CHAR, 0, 997);
MPI.COMM_WORLD.Recv(doubleReadArray, 0, DATA_SIZE, MPI.DOUBLE, 0, 996);
MPI.COMM_WORLD.Recv(longReadArray, 0, DATA_SIZE, MPI.LONG, 0, 995);
MPI.COMM_WORLD.Recv(booleanReadArray, 0, DATA_SIZE, MPI.BOOLEAN, 0, 994);
MPI.COMM_WORLD.Recv(shortReadArray, 0, DATA_SIZE, MPI.SHORT, 0, 993);
MPI.COMM_WORLD.Recv(floatReadArray, 0, DATA_SIZE, MPI.FLOAT, 0, 992);
// System.out.println(" ** Recv completed ** ");
if (Arrays.equals(intArray, intReadArray)
&& Arrays.equals(floatArray, floatReadArray)
&& Arrays.equals(doubleArray, doubleReadArray)
&& Arrays.equals(longArray, longReadArray)
&& Arrays.equals(shortArray, shortReadArray)
&& Arrays.equals(charArray, charReadArray)
&& Arrays.equals(byteArray, byteReadArray)
&& Arrays.equals(booleanArray, booleanReadArray)) {
/*
* System.out.println("\n#################"+ "\n <<<<PASSED>>>> "+
* "\n################");
*/
} else {
System.out.println("\n#################" + "\n <<<<FAILED>>>> "
+ "\n################");
}
}
if (MPI.COMM_WORLD.Rank() == 0) {
System.out.println("Send_rendez TEST Completed");
}
MPI.COMM_WORLD.Barrier();
MPI.Finalize();
}
public static void main(String args[]) throws Exception {
Send_rendez test = new Send_rendez(args);
}
}
| 4,058
|
Java
|
.java
| 93
| 37.032258
| 80
| 0.612903
|
statalign/statalign
| 5
| 6
| 18
|
GPL-3.0
|
9/4/2024, 10:30:06 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 4,058
|
4,249,640
|
IntBufferAtomicityTests.java
|
rockleeprc_sourcecode/Java多线程实战指南/JavaMultiThreadInAction_jcstress-tests/src/main/java/org/openjdk/jcstress/tests/atomicity/buffers/IntBufferAtomicityTests.java
|
/*
* Copyright (c) 2005, 2013, 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 org.openjdk.jcstress.tests.atomicity.buffers;
import org.openjdk.jcstress.annotations.Actor;
import org.openjdk.jcstress.annotations.JCStressMeta;
import org.openjdk.jcstress.annotations.JCStressTest;
import org.openjdk.jcstress.annotations.State;
import org.openjdk.jcstress.infra.results.LongResult1;
import java.nio.IntBuffer;
public class IntBufferAtomicityTests {
@State
public static class MyState {
private final IntBuffer b;
public MyState() {
b = IntBuffer.allocate(16);
}
}
@JCStressTest
@JCStressMeta(GradeInt.class)
public static class IntTest {
@Actor public void actor1(MyState s) { s.b.put(0, -1); }
@Actor public void actor2(MyState s, LongResult1 r) { r.r1 = s.b.get(); }
}
}
| 2,090
|
Java
|
.java
| 46
| 42.043478
| 117
| 0.720177
|
rockleeprc/sourcecode
| 2
| 2
| 0
|
GPL-3.0
|
9/5/2024, 12:07:03 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 2,090
|
1,786,903
|
QuarterDateFormat.java
|
urluzhi_scripts/MISC_scripts/java/Kevin_scripts/org/jfree/chart/axis/QuarterDateFormat.java
|
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ----------------------
* QuarterDateFormat.java
* ----------------------
* (C) Copyright 2005-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 01-Mar-2005 : Version 1 (DG);
* 10-May-2005 : Added equals() method, and implemented Cloneable and
* Serializable (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 08-Jun-2007 : Added Greek symbols, and support for reversing the date - see
* patch 1577221 (DG);
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* A formatter that formats dates to show the year and quarter (for example,
* '2004 IV' for the last quarter of 2004.
*/
public class QuarterDateFormat extends DateFormat
implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -6738465248529797176L;
/** Symbols for regular quarters. */
public static final String[] REGULAR_QUARTERS = new String[] {"1", "2",
"3", "4"};
/** Symbols for roman numbered quarters. */
public static final String[] ROMAN_QUARTERS = new String[] {"I", "II",
"III", "IV"};
/**
* Symbols for greek numbered quarters.
*
* @since 1.0.6
*/
public static final String[] GREEK_QUARTERS = new String[] {"\u0391",
"\u0392", "\u0393", "\u0394"};
/** The strings. */
private String[] quarters = REGULAR_QUARTERS;
/** A flag that controls whether the quarter or the year goes first. */
private boolean quarterFirst;
/**
* Creates a new instance for the default time zone.
*/
public QuarterDateFormat() {
this(TimeZone.getDefault());
}
/**
* Creates a new instance for the specified time zone.
*
* @param zone the time zone (<code>null</code> not permitted).
*/
public QuarterDateFormat(TimeZone zone) {
this(zone, REGULAR_QUARTERS);
}
/**
* Creates a new instance for the specified time zone.
*
* @param zone the time zone (<code>null</code> not permitted).
* @param quarterSymbols the quarter symbols.
*/
public QuarterDateFormat(TimeZone zone, String[] quarterSymbols) {
this(zone, quarterSymbols, false);
}
/**
* Creates a new instance for the specified time zone.
*
* @param zone the time zone (<code>null</code> not permitted).
* @param quarterSymbols the quarter symbols.
* @param quarterFirst a flag that controls whether the quarter or the
* year is displayed first.
*
* @since 1.0.6
*/
public QuarterDateFormat(TimeZone zone, String[] quarterSymbols,
boolean quarterFirst) {
if (zone == null) {
throw new IllegalArgumentException("Null 'zone' argument.");
}
this.calendar = new GregorianCalendar(zone);
this.quarters = quarterSymbols;
this.quarterFirst = quarterFirst;
// the following is never used, but it seems that DateFormat requires
// it to be non-null. It isn't well covered in the spec, refer to
// bug parade 5061189 for more info.
this.numberFormat = NumberFormat.getNumberInstance();
}
/**
* Formats the given date.
*
* @param date the date.
* @param toAppendTo the string buffer.
* @param fieldPosition the field position.
*
* @return The formatted date.
*/
public StringBuffer format(Date date, StringBuffer toAppendTo,
FieldPosition fieldPosition) {
this.calendar.setTime(date);
int year = this.calendar.get(Calendar.YEAR);
int month = this.calendar.get(Calendar.MONTH);
int quarter = month / 3;
if (this.quarterFirst) {
toAppendTo.append(this.quarters[quarter]);
toAppendTo.append(" ");
toAppendTo.append(year);
}
else {
toAppendTo.append(year);
toAppendTo.append(" ");
toAppendTo.append(this.quarters[quarter]);
}
return toAppendTo;
}
/**
* Parses the given string (not implemented).
*
* @param source the date string.
* @param pos the parse position.
*
* @return <code>null</code>, as this method has not been implemented.
*/
public Date parse(String source, ParsePosition pos) {
return null;
}
/**
* Tests this formatter for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof QuarterDateFormat)) {
return false;
}
QuarterDateFormat that = (QuarterDateFormat) obj;
if (!Arrays.equals(this.quarters, that.quarters)) {
return false;
}
if (this.quarterFirst != that.quarterFirst) {
return false;
}
return super.equals(obj);
}
}
| 6,900
|
Java
|
.java
| 188
| 29.829787
| 80
| 0.60908
|
urluzhi/scripts
| 10
| 3
| 0
|
GPL-2.0
|
9/4/2024, 8:18:34 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 6,900
|
14,539
|
InputHideUtilityClassConstructorSerializable.java
|
checkstyle_checkstyle/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/hideutilityclassconstructor/InputHideUtilityClassConstructorSerializable.java
|
/*
HideUtilityClassConstructor
*/
package com.puppycrawl.tools.checkstyle.checks.design.hideutilityclassconstructor;
import java.io.Serializable;
/*input file*/
public class InputHideUtilityClassConstructorSerializable implements Serializable {
private static final long serialVersionUID = 1L;
}
| 305
|
Java
|
.java
| 9
| 31.888889
| 83
| 0.862543
|
checkstyle/checkstyle
| 8,277
| 3,649
| 906
|
LGPL-2.1
|
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 305
|
4,252,164
|
DataSourceJtaTransactionTests.java
|
rockleeprc_sourcecode/spring-framework/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java
|
/*
* Copyright 2002-2016 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.springframework.jdbc.datasource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.support.StaticListableBeanFactory;
import org.springframework.jdbc.datasource.lookup.BeanFactoryDataSourceLookup;
import org.springframework.jdbc.datasource.lookup.IsolationLevelDataSourceRouter;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.jta.JtaTransactionManager;
import org.springframework.transaction.jta.JtaTransactionObject;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
/**
* @author Juergen Hoeller
* @since 17.10.2005
*/
public class DataSourceJtaTransactionTests {
private Connection connection;
private DataSource dataSource;
private UserTransaction userTransaction;
private TransactionManager transactionManager;
private Transaction transaction;
@Before
public void setup() throws Exception {
connection =mock(Connection.class);
dataSource = mock(DataSource.class);
userTransaction = mock(UserTransaction.class);
transactionManager = mock(TransactionManager.class);
transaction = mock(Transaction.class);
given(dataSource.getConnection()).willReturn(connection);
}
@After
public void verifyTransactionSynchronizationManagerState() {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
assertNull(TransactionSynchronizationManager.getCurrentTransactionName());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertNull(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel());
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
}
@Test
public void testJtaTransactionCommit() throws Exception {
doTestJtaTransaction(false);
}
@Test
public void testJtaTransactionRollback() throws Exception {
doTestJtaTransaction(true);
}
private void doTestJtaTransaction(final boolean rollback) throws Exception {
if (rollback) {
given(userTransaction.getStatus()).willReturn(
Status.STATUS_NO_TRANSACTION,Status.STATUS_ACTIVE);
}
else {
given(userTransaction.getStatus()).willReturn(
Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
}
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
TransactionTemplate tt = new TransactionTemplate(ptm);
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
assertTrue("Is new transaction", status.isNewTransaction());
Connection c = DataSourceUtils.getConnection(dataSource);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
DataSourceUtils.releaseConnection(c, dataSource);
c = DataSourceUtils.getConnection(dataSource);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
DataSourceUtils.releaseConnection(c, dataSource);
if (rollback) {
status.setRollbackOnly();
}
}
});
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
verify(userTransaction).begin();
if (rollback) {
verify(userTransaction).rollback();
}
verify(connection).close();
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNew() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, false, false, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithAccessAfterResume() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, false, true, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnection() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, true, false, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAccessed() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, true, true, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSource() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, false, true, true);
}
@Test
public void testJtaTransactionRollbackWithPropagationRequiresNew() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, false, false, false);
}
@Test
public void testJtaTransactionRollbackWithPropagationRequiresNewWithAccessAfterResume() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, false, true, false);
}
@Test
public void testJtaTransactionRollbackWithPropagationRequiresNewWithOpenOuterConnection() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, true, false, false);
}
@Test
public void testJtaTransactionRollbackWithPropagationRequiresNewWithOpenOuterConnectionAccessed() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, true, true, false);
}
@Test
public void testJtaTransactionRollbackWithPropagationRequiresNewWithTransactionAwareDataSource() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, false, true, true);
}
private void doTestJtaTransactionWithPropagationRequiresNew(
final boolean rollback, final boolean openOuterConnection, final boolean accessAfterResume,
final boolean useTransactionAwareDataSource) throws Exception {
given(transactionManager.suspend()).willReturn(transaction);
if (rollback) {
given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE);
}
else {
given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
}
given(connection.isReadOnly()).willReturn(true);
final DataSource dsToUse = useTransactionAwareDataSource ?
new TransactionAwareDataSourceProxy(dataSource) : dataSource;
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
final TransactionTemplate tt = new TransactionTemplate(ptm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
assertTrue("Is new transaction", status.isNewTransaction());
Connection c = DataSourceUtils.getConnection(dsToUse);
try {
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
c.isReadOnly();
DataSourceUtils.releaseConnection(c, dsToUse);
c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
if (!openOuterConnection) {
DataSourceUtils.releaseConnection(c, dsToUse);
}
}
catch (SQLException ex) {
}
for (int i = 0; i < 5; i++) {
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
assertTrue("Is new transaction", status.isNewTransaction());
try {
Connection c = DataSourceUtils.getConnection(dsToUse);
c.isReadOnly();
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
DataSourceUtils.releaseConnection(c, dsToUse);
c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
DataSourceUtils.releaseConnection(c, dsToUse);
}
catch (SQLException ex) {
}
}
});
}
if (rollback) {
status.setRollbackOnly();
}
if (accessAfterResume) {
try {
if (!openOuterConnection) {
c = DataSourceUtils.getConnection(dsToUse);
}
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
c.isReadOnly();
DataSourceUtils.releaseConnection(c, dsToUse);
c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
DataSourceUtils.releaseConnection(c, dsToUse);
}
catch (SQLException ex) {
}
}
else {
if (openOuterConnection) {
DataSourceUtils.releaseConnection(c, dsToUse);
}
}
}
});
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
verify(userTransaction, times(6)).begin();
verify(transactionManager, times(5)).resume(transaction);
if (rollback) {
verify(userTransaction, times(5)).commit();
verify(userTransaction).rollback();
}
else {
verify(userTransaction, times(6)).commit();
}
if (accessAfterResume && !openOuterConnection) {
verify(connection, times(7)).close();
}
else {
verify(connection, times(6)).close();
}
}
@Test
public void testJtaTransactionCommitWithPropagationRequiredWithinSupports() throws Exception {
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(false, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiredWithinNotSupported() throws Exception {
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(false, true);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithinSupports() throws Exception {
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(true, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithinNotSupported() throws Exception {
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(true, true);
}
private void doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(
final boolean requiresNew, boolean notSupported) throws Exception {
if (notSupported) {
given(userTransaction.getStatus()).willReturn(
Status.STATUS_ACTIVE,
Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE,
Status.STATUS_ACTIVE);
given(transactionManager.suspend()).willReturn(transaction);
}
else {
given(userTransaction.getStatus()).willReturn(
Status.STATUS_NO_TRANSACTION,
Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE,
Status.STATUS_ACTIVE);
}
final DataSource dataSource = mock(DataSource.class);
final Connection connection1 = mock(Connection.class);
final Connection connection2 = mock(Connection.class);
given(dataSource.getConnection()).willReturn(connection1, connection2);
final JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
TransactionTemplate tt = new TransactionTemplate(ptm);
tt.setPropagationBehavior(notSupported ?
TransactionDefinition.PROPAGATION_NOT_SUPPORTED : TransactionDefinition.PROPAGATION_SUPPORTS);
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
assertSame(connection1, DataSourceUtils.getConnection(dataSource));
assertSame(connection1, DataSourceUtils.getConnection(dataSource));
TransactionTemplate tt2 = new TransactionTemplate(ptm);
tt2.setPropagationBehavior(requiresNew ?
TransactionDefinition.PROPAGATION_REQUIRES_NEW : TransactionDefinition.PROPAGATION_REQUIRED);
tt2.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
assertSame(connection2, DataSourceUtils.getConnection(dataSource));
assertSame(connection2, DataSourceUtils.getConnection(dataSource));
}
});
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
assertSame(connection1, DataSourceUtils.getConnection(dataSource));
}
});
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
verify(userTransaction).begin();
verify(userTransaction).commit();
if (notSupported) {
verify(transactionManager).resume(transaction);
}
verify(connection2).close();
verify(connection1).close();
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewAndSuspendException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, false, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndSuspendException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, true, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSourceAndSuspendException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, false, true);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndTransactionAwareDataSourceAndSuspendException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, true, true);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewAndBeginException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, false, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndBeginException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, true, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndTransactionAwareDataSourceAndBeginException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, true, true);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSourceAndBeginException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, false, true);
}
private void doTestJtaTransactionWithPropagationRequiresNewAndBeginException(boolean suspendException,
final boolean openOuterConnection, final boolean useTransactionAwareDataSource) throws Exception {
given(userTransaction.getStatus()).willReturn(
Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE,
Status.STATUS_ACTIVE);
if (suspendException) {
given(transactionManager.suspend()).willThrow(new SystemException());
}
else {
given(transactionManager.suspend()).willReturn(transaction);
willThrow(new SystemException()).given(userTransaction).begin();
}
given(connection.isReadOnly()).willReturn(true);
final DataSource dsToUse = useTransactionAwareDataSource ?
new TransactionAwareDataSourceProxy(dataSource) : dataSource;
if (dsToUse instanceof TransactionAwareDataSourceProxy) {
((TransactionAwareDataSourceProxy) dsToUse).setReobtainTransactionalConnections(true);
}
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
final TransactionTemplate tt = new TransactionTemplate(ptm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
try {
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
assertTrue("Is new transaction", status.isNewTransaction());
Connection c = DataSourceUtils.getConnection(dsToUse);
try {
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
c.isReadOnly();
DataSourceUtils.releaseConnection(c, dsToUse);
c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
if (!openOuterConnection) {
DataSourceUtils.releaseConnection(c, dsToUse);
}
}
catch (SQLException ex) {
}
try {
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
assertTrue("Is new transaction", status.isNewTransaction());
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
DataSourceUtils.releaseConnection(c, dsToUse);
c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
DataSourceUtils.releaseConnection(c, dsToUse);
}
});
}
finally {
if (openOuterConnection) {
try {
c.isReadOnly();
DataSourceUtils.releaseConnection(c, dsToUse);
}
catch (SQLException ex) {
}
}
}
}
});
fail("Should have thrown TransactionException");
}
catch (TransactionException ex) {
// expected
}
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
verify(userTransaction).begin();
if (suspendException) {
verify(userTransaction).rollback();
}
if (suspendException) {
verify(connection, atLeastOnce()).close();
}
else {
verify(connection, never()).close();
}
}
@Test
public void testJtaTransactionWithConnectionHolderStillBound() throws Exception {
@SuppressWarnings("serial")
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction) {
@Override
protected void doRegisterAfterCompletionWithJtaTransaction(
JtaTransactionObject txObject,
final List<TransactionSynchronization> synchronizations)
throws RollbackException, SystemException {
Thread async = new Thread() {
@Override
public void run() {
invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_COMMITTED);
}
};
async.start();
try {
async.join();
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
}
};
TransactionTemplate tt = new TransactionTemplate(ptm);
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE);
for (int i = 0; i < 3; i++) {
final boolean releaseCon = (i != 1);
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
assertTrue("Is existing transaction", !status.isNewTransaction());
Connection c = DataSourceUtils.getConnection(dataSource);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
DataSourceUtils.releaseConnection(c, dataSource);
c = DataSourceUtils.getConnection(dataSource);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
if (releaseCon) {
DataSourceUtils.releaseConnection(c, dataSource);
}
}
});
if (!releaseCon) {
assertTrue("Still has connection holder", TransactionSynchronizationManager.hasResource(dataSource));
}
else {
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
}
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
}
verify(connection, times(3)).close();
}
@Test
public void testJtaTransactionWithIsolationLevelDataSourceAdapter() throws Exception {
given(userTransaction.getStatus()).willReturn(
Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE,
Status.STATUS_ACTIVE,
Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE,
Status.STATUS_ACTIVE);
final IsolationLevelDataSourceAdapter dsToUse = new IsolationLevelDataSourceAdapter();
dsToUse.setTargetDataSource(dataSource);
dsToUse.afterPropertiesSet();
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
ptm.setAllowCustomIsolationLevels(true);
TransactionTemplate tt = new TransactionTemplate(ptm);
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
assertSame(connection, c);
DataSourceUtils.releaseConnection(c, dsToUse);
}
});
tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
tt.setReadOnly(true);
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
assertSame(connection, c);
DataSourceUtils.releaseConnection(c, dsToUse);
}
});
verify(userTransaction, times(2)).begin();
verify(userTransaction, times(2)).commit();
verify(connection).setReadOnly(true);
verify(connection).setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
verify(connection, times(2)).close();
}
@Test
public void testJtaTransactionWithIsolationLevelDataSourceRouter() throws Exception {
doTestJtaTransactionWithIsolationLevelDataSourceRouter(false);
}
@Test
public void testJtaTransactionWithIsolationLevelDataSourceRouterWithDataSourceLookup() throws Exception {
doTestJtaTransactionWithIsolationLevelDataSourceRouter(true);
}
private void doTestJtaTransactionWithIsolationLevelDataSourceRouter(boolean dataSourceLookup) throws Exception {
given( userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
final DataSource dataSource1 = mock(DataSource.class);
final Connection connection1 = mock(Connection.class);
given(dataSource1.getConnection()).willReturn(connection1);
final DataSource dataSource2 = mock(DataSource.class);
final Connection connection2 = mock(Connection.class);
given(dataSource2.getConnection()).willReturn(connection2);
final IsolationLevelDataSourceRouter dsToUse = new IsolationLevelDataSourceRouter();
Map<Object, Object> targetDataSources = new HashMap<>();
if (dataSourceLookup) {
targetDataSources.put("ISOLATION_REPEATABLE_READ", "ds2");
dsToUse.setDefaultTargetDataSource("ds1");
StaticListableBeanFactory beanFactory = new StaticListableBeanFactory();
beanFactory.addBean("ds1", dataSource1);
beanFactory.addBean("ds2", dataSource2);
dsToUse.setDataSourceLookup(new BeanFactoryDataSourceLookup(beanFactory));
}
else {
targetDataSources.put("ISOLATION_REPEATABLE_READ", dataSource2);
dsToUse.setDefaultTargetDataSource(dataSource1);
}
dsToUse.setTargetDataSources(targetDataSources);
dsToUse.afterPropertiesSet();
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
ptm.setAllowCustomIsolationLevels(true);
TransactionTemplate tt = new TransactionTemplate(ptm);
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
assertSame(connection1, c);
DataSourceUtils.releaseConnection(c, dsToUse);
}
});
tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
assertSame(connection2, c);
DataSourceUtils.releaseConnection(c, dsToUse);
}
});
verify(userTransaction, times(2)).begin();
verify(userTransaction, times(2)).commit();
verify(connection1).close();
verify(connection2).close();
}
}
| 28,947
|
Java
|
.java
| 618
| 42.796117
| 196
| 0.809679
|
rockleeprc/sourcecode
| 2
| 2
| 0
|
GPL-3.0
|
9/5/2024, 12:07:03 AM (Europe/Amsterdam)
| false
| true
| false
| true
| true
| true
| true
| true
| 28,947
|
4,047,451
|
HexString.java
|
banh-gao_CNSReader/ocf/de/cardcontact/tlv/HexString.java
|
/*
* ---------
* |.##> <##.| Open Smart Card Development Platform (www.openscdp.org)
* |# #|
* |# #| Copyright (c) 1999-2006 CardContact Software & System Consulting
* |'##> <##'| Andreas Schwier, 32429 Minden, Germany (www.cardcontact.de)
* ---------
*
* This file is part of OpenSCDP.
*
* OpenSCDP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* OpenSCDP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenSCDP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package de.cardcontact.tlv;
/**
* Utility class to handle all sorts of hexadecimal string conversions
*
* @author Andreas Schwier ([email protected])
*/
public class HexString {
final static char hexchar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
* Convert integer value to hexadecimal byte presentation
*
* @param val
* Value
* @return
* 2 digit hexadecimal string
*/
public static String hexifyByte(int val) {
return "" + hexchar[(val >>> 4) & 0x0F] + hexchar[val & 0x0F];
}
/**
* Convert byte value to hexadecimal byte presentation
*
* @param val
* Value
* @return
* 2 digit hexadecimal string
*/
public static String hexifyByte(byte val) {
return hexifyByte((int)val & 0xFF);
}
/**
* Convert int value to hexadecimal short presentation
*
* @param val
* Value
* @return
* 4 digit hexadecimal string
*/
public static String hexifyShort(int val) {
return hexifyByte((val >>> 8) & 0xFF) + hexifyByte(val & 0xFF);
}
/**
* Convert int value to hexadecimal int presentation
*
* @param val
* Value
* @return
* 8 digit hexadecimal string
*/
public static String hexifyInt(int val) {
return hexifyShort((val >> 16) & 0xFFFF) + hexifyShort(val & 0xFFFF);
}
/**
* Convert byte array to hexadecimal string
*
* @param buffer Buffer with bytes
* @param delimiter Delimiter to be inserted between bytes. Use 0 for none.
* @param length Number of byte to convert
* @return String with hexadecimal data
*/
public static String hexifyByteArray(byte[] buffer, char delimiter, int length) {
// Allocate buffer for 2 or 3 times the size in bytes, depending on whether a delimiter
// was given or not
StringBuffer sb = new StringBuffer((length << 1) + (delimiter == 0 ? 0 : length));
for (int i = 0; i < length; i++) {
sb.append(hexchar[(buffer[i] >>> 4) & 0x0F]);
sb.append(hexchar[buffer[i] & 0x0F]);
if ((delimiter != 0) && (i < length - 1)) {
sb.append(delimiter);
}
}
return sb.toString();
}
/**
* Convert byte array to hexadecimal string
*
* @param buffer Buffer with bytes
* @param delimiter Delimiter to be inserted between bytes. Use 0 for none.
* @return String with hexadecimal data
*/
public static String hexifyByteArray(byte[] buffer, char delimiter) {
return hexifyByteArray(buffer, delimiter, buffer.length);
}
/**
* Convert byte array to hexadecimal string
*
* @param buffer Buffer with bytes
* @return String with hexadecimal data
*/
public static String hexifyByteArray(byte[] buffer) {
return hexifyByteArray(buffer, (char)0, buffer.length);
}
/**
* Dump buffer in hexadecimal format with offset and character codes
*
* @param data
* Byte buffer
* @param offset
* Offset into byte buffer
* @param length
* Length of data to be dumped
* @param widths
* Number of bytes per line
* @param indent
* Number of blanks to indent each line
* @return
* String containing the dump
*/
public static String dump(byte[] data, int offset, int length, int widths, int indent) {
StringBuffer buffer = new StringBuffer(80);
int i, ofs, len;
char ch;
if ((data == null) || (widths == 0) || (length < 0) || (indent < 0))
throw new IllegalArgumentException();
while(length > 0) {
for (i = 0; i < indent; i++)
buffer.append(' ');
buffer.append(hexifyShort(offset));
buffer.append(" ");
ofs = offset;
len = widths < length ? widths : length;
for (i = 0; i < len; i++, ofs++) {
buffer.append(hexchar[(data[ofs] >>> 4) & 0x0F]);
buffer.append(hexchar[data[ofs] & 0x0F]);
buffer.append(' ');
}
for (; i < widths; i++) {
buffer.append(" ");
}
buffer.append(' ');
ofs = offset;
for (i = 0; i < len; i++, ofs++) {
ch = (char)(data[ofs] & 0xFF);
if ((ch < 32) || ((ch >= 127)))
ch = '.';
buffer.append(ch);
}
buffer.append('\n');
offset += len;
length -= len;
}
return buffer.toString();
}
/**
* Dump buffer in hexadecimal format with offset and character codes
*
* @param data
* Byte buffer
* @param offset
* Offset into byte buffer
* @param length
* Length of data to be dumped
* @param widths
* Number of bytes per line
* @return
* String containing the dump
*/
public static String dump(byte[] data, int offset, int length, int widths) {
return dump(data, offset, length, widths, 0);
}
/**
* Dump buffer in hexadecimal format with offset and character codes.
* Output 16 bytes per line
*
* @param data
* Byte buffer
* @param offset
* Offset into byte buffer
* @param length
* Length of data to be dumped
* @return
* String containing the dump
*/
public static String dump(byte[] data, int offset, int length) {
return dump(data, offset, length, 16, 0);
}
/**
* Dump buffer in hexadecimal format with offset and character codes
*
* @param data
* Byte buffer
* @return
* String containing the dump
*/
public static String dump(byte[] data) {
return dump(data, 0, data.length, 16, 0);
}
/**
* Parse string of hexadecimal characters into byte array
*
* @param str String to parse
* @return byte array containing the string
*/
public static byte[] parseHexString(String str) {
ByteBuffer b = new ByteBuffer(str.length() / 2);
int i = 0;
int size = str.length();
if (str.startsWith("0x")) {
i += 2;
size -= 2;
}
while (size > 0) {
if (!Character.isLetterOrDigit(str.charAt(i))) {
i++;
size--;
}
if (size < 2) {
throw new NumberFormatException("Odd number of hexadecimal digits");
}
String toParse = str.substring(i, i + 2);
b.append((byte)Integer.parseInt(toParse, 16));
i += 2;
size -= 2;
}
return b.getBytes();
}
}
| 7,384
|
Java
|
.java
| 241
| 25.356846
| 93
| 0.618187
|
banh-gao/CNSReader
| 2
| 3
| 1
|
GPL-2.0
|
9/5/2024, 12:00:55 AM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| true
| true
| 7,384
|
3,138,351
|
GuaranteeTypeService.java
|
crypto-coder_open-cyclos/src/nl/strohalm/cyclos/services/accounts/guarantees/GuaranteeTypeService.java
|
/*
This file is part of Cyclos (www.cyclos.org).
A project of the Social Trade Organisation (www.socialtrade.org).
Cyclos 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 2 of the License, or
(at your option) any later version.
Cyclos is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Cyclos; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package nl.strohalm.cyclos.services.accounts.guarantees;
import java.util.List;
import nl.strohalm.cyclos.entities.Relationship;
import nl.strohalm.cyclos.entities.accounts.guarantees.GuaranteeType;
import nl.strohalm.cyclos.entities.accounts.guarantees.GuaranteeTypeQuery;
import nl.strohalm.cyclos.entities.exceptions.EntityNotFoundException;
import nl.strohalm.cyclos.services.Service;
import nl.strohalm.cyclos.utils.validation.ValidationException;
/**
* Service interface for guarantee types
* @author Jefferson Magno
*/
public interface GuaranteeTypeService extends Service {
/**
* Loads the guarantee type, fetching the specified relationships
*/
GuaranteeType load(Long id, Relationship... fetch) throws EntityNotFoundException;
/**
* Removes the specified guarantee types
*/
int remove(Long... ids);
/**
* Saves the specified guarantee type, returning it with the generated id if it doesn't exist yet.
*/
GuaranteeType save(GuaranteeType guaranteeType);
/**
* Search guarantee types
*/
List<GuaranteeType> search(GuaranteeTypeQuery guaranteeTypeQuery);
/**
* Validates the specified guarantee type
*/
void validate(GuaranteeType guaranteeType) throws ValidationException;
}
| 2,113
|
Java
|
.java
| 49
| 38.877551
| 102
| 0.766455
|
crypto-coder/open-cyclos
| 4
| 9
| 0
|
GPL-2.0
|
9/4/2024, 10:59:44 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 2,113
|
4,136,207
|
FallingParticle.java
|
Snowy1013_Ayo2016/app/src/main/lib_particle/com/example/administrator/myapplication/particle/FallingParticle.java
|
package com.example.administrator.myapplication.particle;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import com.example.administrator.myapplication.factory.FallingParticleFactory;
import java.util.Random;
/**
* Created by Administrator on 2015/11/29 0029.
*/
public class FallingParticle extends Particle{
static Random random = new Random();
float radius = FallingParticleFactory.PART_WH;
float alpha = 1.0f;
Rect mBound;
/**
* @param color 颜色
* @param x
* @param y
*/
public FallingParticle(int color, float x, float y,Rect bound) {
super(color, x, y);
mBound = bound;
}
protected void draw(Canvas canvas,Paint paint){
paint.setColor(color);
paint.setAlpha((int) (Color.alpha(color) * alpha)); //这样透明颜色就不是黑色了
canvas.drawCircle(cx, cy, radius, paint);
}
protected void caculate(float factor){
cx = cx + factor * random.nextInt(mBound.width()) * (random.nextFloat() - 0.5f);
cy = cy + factor * random.nextInt(mBound.height() / 2);
radius = radius - factor * random.nextInt(2);
alpha = (1f - factor) * (1 + random.nextFloat());
}
}
| 1,318
|
Java
|
.java
| 37
| 29.891892
| 88
| 0.684887
|
Snowy1013/Ayo2016
| 2
| 0
| 0
|
GPL-3.0
|
9/5/2024, 12:04:01 AM (Europe/Amsterdam)
| true
| true
| true
| true
| false
| true
| true
| true
| 1,290
|
1,315,339
|
A_test3_out.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTemp/canRename/A_test3_out.java
|
//rename to: j1
package p;
class A{
int m(){
{
int i= 0;
int /*[*/j1/*]*/= 0;
return i + j1;
}
}
}
| 118
|
Java
|
.java
| 11
| 8
| 23
| 0.461538
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 118
|
4,131,638
|
PRPAMT201303UV02PatientOfOtherProvider.java
|
flaviociaware_cwEnsaiosWeb/cwCADSUS/src/main/java/org/hl7/v3/PRPAMT201303UV02PatientOfOtherProvider.java
|
package org.hl7.v3;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for PRPA_MT201303UV02.PatientOfOtherProvider complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="PRPA_MT201303UV02.PatientOfOtherProvider">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <group ref="{urn:hl7-org:v3}InfrastructureRootElements"/>
* <element name="subjectOf" type="{urn:hl7-org:v3}PRPA_MT201303UV02.Subject3"/>
* </sequence>
* <attGroup ref="{urn:hl7-org:v3}InfrastructureRootAttributes"/>
* <attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" />
* <attribute name="classCode" use="required" type="{urn:hl7-org:v3}RoleClass" fixed="PAT" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PRPA_MT201303UV02.PatientOfOtherProvider", propOrder = {
"realmCode",
"typeId",
"templateId",
"subjectOf"
})
public class PRPAMT201303UV02PatientOfOtherProvider {
protected List<CS> realmCode;
protected II typeId;
protected List<II> templateId;
@XmlElement(required = true)
protected PRPAMT201303UV02Subject3 subjectOf;
@XmlAttribute(name = "nullFlavor")
protected List<String> nullFlavor;
@XmlAttribute(name = "classCode", required = true)
protected List<String> classCode;
/**
* Gets the value of the realmCode property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the realmCode property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRealmCode().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CS }
*
*
*/
public List<CS> getRealmCode() {
if (realmCode == null) {
realmCode = new ArrayList<CS>();
}
return this.realmCode;
}
/**
* Gets the value of the typeId property.
*
* @return
* possible object is
* {@link II }
*
*/
public II getTypeId() {
return typeId;
}
/**
* Sets the value of the typeId property.
*
* @param value
* allowed object is
* {@link II }
*
*/
public void setTypeId(II value) {
this.typeId = value;
}
/**
* Gets the value of the templateId property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the templateId property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTemplateId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link II }
*
*
*/
public List<II> getTemplateId() {
if (templateId == null) {
templateId = new ArrayList<II>();
}
return this.templateId;
}
/**
* Gets the value of the subjectOf property.
*
* @return
* possible object is
* {@link PRPAMT201303UV02Subject3 }
*
*/
public PRPAMT201303UV02Subject3 getSubjectOf() {
return subjectOf;
}
/**
* Sets the value of the subjectOf property.
*
* @param value
* allowed object is
* {@link PRPAMT201303UV02Subject3 }
*
*/
public void setSubjectOf(PRPAMT201303UV02Subject3 value) {
this.subjectOf = value;
}
/**
* Gets the value of the nullFlavor property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the nullFlavor property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNullFlavor().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getNullFlavor() {
if (nullFlavor == null) {
nullFlavor = new ArrayList<String>();
}
return this.nullFlavor;
}
/**
* Gets the value of the classCode property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the classCode property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getClassCode().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getClassCode() {
if (classCode == null) {
classCode = new ArrayList<String>();
}
return this.classCode;
}
}
| 5,993
|
Java
|
.java
| 205
| 23.492683
| 102
| 0.611708
|
flaviociaware/cwEnsaiosWeb
| 2
| 0
| 13
|
GPL-2.0
|
9/5/2024, 12:03:50 AM (Europe/Amsterdam)
| false
| true
| true
| true
| false
| true
| true
| true
| 5,993
|
4,837,259
|
Validate.java
|
danielbenedykt_AngelList-Mobile/src/org/jsoup/helper/Validate.java
|
package org.jsoup.helper;
/**
* Simple validation methods. Designed for jsoup internal use
*/
public final class Validate {
private Validate() {}
/**
* Validates that the object is not null
* @param obj object to test
*/
public static void notNull(Object obj) {
if (obj == null)
throw new IllegalArgumentException("Object must not be null");
}
/**
* Validates that the object is not null
* @param obj object to test
* @param msg message to output if validation fails
*/
public static void notNull(Object obj, String msg) {
if (obj == null)
throw new IllegalArgumentException(msg);
}
/**
* Validates that the value is true
* @param val object to test
*/
public static void isTrue(boolean val) {
if (!val)
throw new IllegalArgumentException("Must be true");
}
/**
* Validates that the value is true
* @param val object to test
* @param msg message to output if validation fails
*/
public static void isTrue(boolean val, String msg) {
if (!val)
throw new IllegalArgumentException(msg);
}
/**
* Validates that the value is false
* @param val object to test
*/
public static void isFalse(boolean val) {
if (val)
throw new IllegalArgumentException("Must be false");
}
/**
* Validates that the value is false
* @param val object to test
* @param msg message to output if validation fails
*/
public static void isFalse(boolean val, String msg) {
if (val)
throw new IllegalArgumentException(msg);
}
/**
* Validates that the array contains no null elements
* @param objects the array to test
*/
public static void noNullElements(Object[] objects) {
noNullElements(objects, "Array must not contain any null objects");
}
/**
* Validates that the array contains no null elements
* @param objects the array to test
* @param msg message to output if validation fails
*/
public static void noNullElements(Object[] objects, String msg) {
for (Object obj : objects)
if (obj == null)
throw new IllegalArgumentException(msg);
}
/**
* Validates that the string is not empty
* @param string the string to test
*/
public static void notEmpty(String string) {
if (string == null || string.length() == 0)
throw new IllegalArgumentException("String must not be empty");
}
/**
* Validates that the string is not empty
* @param string the string to test
* @param msg message to output if validation fails
*/
public static void notEmpty(String string, String msg) {
if (string == null || string.length() == 0)
throw new IllegalArgumentException(msg);
}
/**
Cause a failure.
@param msg message to output.
*/
public static void fail(String msg) {
throw new IllegalArgumentException(msg);
}
}
| 3,118
|
Java
|
.java
| 99
| 24.868687
| 75
| 0.628248
|
danielbenedykt/AngelList-Mobile
| 1
| 1
| 0
|
GPL-2.0
|
9/5/2024, 12:33:21 AM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 3,118
|
49,493
|
WatchingVariable.java
|
SuperMonster003_AutoJs6/app/src/main/java/org/autojs/autojs/ui/edit/debug/WatchingVariable.java
|
package org.autojs.autojs.ui.edit.debug;
public class WatchingVariable {
private String mDisplayName;
private String mName;
private final boolean mPinned;
private String mValue;
private String mSingleLineValue;
public WatchingVariable(String displayName, String name, boolean pinned) {
mDisplayName = displayName;
mName = name;
mPinned = pinned;
}
public WatchingVariable(String name) {
this(name, name, false);
}
public boolean isPinned() {
return mPinned;
}
public String getValue() {
return mValue;
}
public void setValue(String value) {
mValue = value;
mSingleLineValue = value == null ? null : value.replaceAll("\n", " ");
}
public String getSingleLineValue() {
return mSingleLineValue;
}
public void setDisplayName(String displayName) {
mDisplayName = displayName;
}
public void setName(String name) {
mName = name;
}
public String getDisplayName() {
return mDisplayName;
}
public String getName() {
return mName;
}
}
| 1,140
|
Java
|
.java
| 41
| 21.536585
| 78
| 0.653174
|
SuperMonster003/AutoJs6
| 2,371
| 703
| 117
|
MPL-2.0
|
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 1,140
|
1,644,802
|
DFGUISearchAction.java
|
mru00_jade_agents/src/jade/tools/dfgui/DFGUISearchAction.java
|
/*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
GNU Lesser General Public License
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation,
version 2.1 of the License.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package jade.tools.dfgui;
// Import required Java classes
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Enumeration;
// Import required JADE classes
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAException;
import jade.core.AID;
import jade.domain.FIPAAgentManagement.SearchConstraints;
import jade.domain.DFGUIAdapter;
import jade.gui.ConstraintDlg;
import jade.gui.DFAgentDscDlg;
import jade.gui.GuiEvent;
/**
@author Tiziana Trucco - CSELT S.p.A.
@version $Date: 2000-11-08 15:54:37 +0100 (mer, 08 nov 2000) $ $Revision: 1961 $
*/
class DFGUISearchAction extends AbstractAction
{
private DFGUI gui;
public DFGUISearchAction(DFGUI gui)
{
super ("Search");
this.gui = gui;
}
public void actionPerformed(ActionEvent e)
{
int kind = gui.kindOfOperation();
AID df;
if ((kind == DFGUI.PARENT_VIEW) || (kind == DFGUI.CHILDREN_VIEW))// search on parent
{
AID name = gui.getSelectedAgentInTable();
if (name != null)
df = name; //find the address of the parent-df
else
df = gui.myAgent.getDescriptionOfThisDF().getName();
}
else
df = gui.myAgent.getDescriptionOfThisDF().getName();
ConstraintDlg constraintsGui = new ConstraintDlg(gui);
//insert the constraints for the search.
SearchConstraints constraints = constraintsGui.setConstraint();
if(constraints == null) //pressed the cancel button
return;
DFAgentDscDlg dlg = new DFAgentDscDlg((Frame) gui);
DFAgentDescription editedDfd = dlg.ShowDFDGui(null,true,false); //checkMandatorySlots = false
//If no df is selected, the df of the platform is used.
if (editedDfd != null)
{
GuiEvent ev = new GuiEvent((Object)gui,DFGUIAdapter.SEARCH);
ev.addParameter(df);
ev.addParameter(editedDfd);
ev.addParameter(constraints);
gui.myAgent.postGuiEvent(ev);
gui.setTab("Search",df);
}
}
}
| 3,061
|
Java
|
.java
| 78
| 34.615385
| 96
| 0.705519
|
mru00/jade_agents
| 11
| 9
| 0
|
LGPL-2.1
|
9/4/2024, 8:11:13 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 3,061
|
1,319,404
|
A_test323.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test323.java
|
package lambdaExpression18_in;
@FunctionalInterface
interface I1 {
int foo1(int s1, int s2);
}
@FunctionalInterface
interface I2 {
I1 foo2(int n1);
}
interface I_Test {
static I2 i2 = x1 -> (a1, b1) -> {/*]*/
int m = 4;
return m;
/*[*/};
}
| 250
|
Java
|
.java
| 15
| 15
| 40
| 0.67382
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 250
|
1,905,672
|
VicinityProvider.java
|
awojna_Rseslib/src/main/java/rseslib/processing/searching/metric/VicinityProvider.java
|
/*
* Copyright (C) 2002 - 2024 The Rseslib Contributors
*
* This file is part of Rseslib.
*
* Rseslib 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.
*
* Rseslib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package rseslib.processing.searching.metric;
import rseslib.structure.data.DoubleData;
import rseslib.structure.metric.Neighbour;
/**
* Provides vicinity of data objects
* extracted from a given data collection.
*
* @author Arkadiusz Wojna
*/
public interface VicinityProvider
{
/**
* Returns the average number of distance calculations.
*
* @return Average number of distance calculations.
*/
public abstract double getAverageNoOfDistCalculations();
/**
* Returns the standard deviation of the number of distance calculations.
*
* @return Standard deviation of the number of distance calculations.
*/
public abstract double getStdDevNoOfDistCalculations();
/**
* Provides nearest neighbours of a given data object
* and sorts them according to the growing distance.
*
* @param dObj Data object to be used for searching vicinity.
* @param noOfNearest Number of nearest neighbours to be returned.
* @return Vicinity of a given data object.
*/
public abstract Neighbour[] getVicinity(DoubleData dObj, int noOfNearest);
}
| 1,963
|
Java
|
.java
| 51
| 33.862745
| 79
| 0.707895
|
awojna/Rseslib
| 15
| 5
| 0
|
GPL-3.0
|
9/4/2024, 8:22:45 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 1,963
|
3,354,079
|
FormsViewPager.java
|
IShiraiKurokoI_DLUTToolBoxMobile/DLUTToolBoxMobile/DLUTToolBoxMobile.Android/obj/Debug/120/android/src/crc64720bb2db43a66fe9/FormsViewPager.java
|
package crc64720bb2db43a66fe9;
public class FormsViewPager
extends androidx.viewpager.widget.ViewPager
implements
mono.android.IGCUserPeer
{
/** @hide */
public static final String __md_methods;
static {
__md_methods =
"n_onInterceptTouchEvent:(Landroid/view/MotionEvent;)Z:GetOnInterceptTouchEvent_Landroid_view_MotionEvent_Handler\n" +
"n_onTouchEvent:(Landroid/view/MotionEvent;)Z:GetOnTouchEvent_Landroid_view_MotionEvent_Handler\n" +
"";
mono.android.Runtime.register ("Xamarin.Forms.Platform.Android.AppCompat.FormsViewPager, Xamarin.Forms.Platform.Android", FormsViewPager.class, __md_methods);
}
public FormsViewPager (android.content.Context p0)
{
super (p0);
if (getClass () == FormsViewPager.class)
mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.AppCompat.FormsViewPager, Xamarin.Forms.Platform.Android", "Android.Content.Context, Mono.Android", this, new java.lang.Object[] { p0 });
}
public FormsViewPager (android.content.Context p0, android.util.AttributeSet p1)
{
super (p0, p1);
if (getClass () == FormsViewPager.class)
mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.AppCompat.FormsViewPager, Xamarin.Forms.Platform.Android", "Android.Content.Context, Mono.Android:Android.Util.IAttributeSet, Mono.Android", this, new java.lang.Object[] { p0, p1 });
}
public boolean onInterceptTouchEvent (android.view.MotionEvent p0)
{
return n_onInterceptTouchEvent (p0);
}
private native boolean n_onInterceptTouchEvent (android.view.MotionEvent p0);
public boolean onTouchEvent (android.view.MotionEvent p0)
{
return n_onTouchEvent (p0);
}
private native boolean n_onTouchEvent (android.view.MotionEvent p0);
private java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
| 2,001
|
Java
|
.java
| 50
| 37.3
| 252
| 0.778523
|
IShiraiKurokoI/DLUTToolBoxMobile
| 4
| 0
| 0
|
GPL-2.0
|
9/4/2024, 11:14:57 PM (Europe/Amsterdam)
| false
| true
| false
| true
| true
| true
| true
| true
| 2,001
|
3,373,080
|
JtregTest8.java
|
CGCL-codes_JOpFuzzer/JOpFuzzer/JavaFuzzer/JtregTest8.java
|
/*
* Copyright (c) 2021, Red Hat, Inc. 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.
*
* 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.
*
*/
/*
* @test
* @library . /testlibrary
* @run driver JtregTest
*/
import java.io.*;
import java.nio.file.*;
import java.util.*;
import com.oracle.java.testlibrary.OutputAnalyzer;
import com.oracle.java.testlibrary.ProcessTools;
import com.oracle.java.testlibrary.Utils;
public class JtregTest {
public static void main(String... args) throws Throwable {
OutputAnalyzer output = ProcessTools.executeTestJvm(
"-Xmx512m",
"Test"
);
output.shouldHaveExitValue(0);
String goldenFile = Utils.TEST_SRC + File.separator + "golden.out";
List<String> expected = Files.readAllLines(new File(goldenFile).toPath());
List<String> actual = output.asLines();
if (expected.size() != actual.size()) {
throw new IllegalStateException("Expected and actual output length differ: " + expected.size() + " vs " + actual.size());
}
for (int c = 0; c < expected.size(); c++) {
String e = expected.get(c);
String a = actual.get(c);
if (!e.equals(a)) {
throw new IllegalStateException("Expected and actual output differ at line " + c + ":\n Expected: " + e + "\n Actual: " + a);
}
}
}
}
| 2,266
|
Java
|
.java
| 56
| 36.017857
| 141
| 0.69147
|
CGCL-codes/JOpFuzzer
| 4
| 0
| 0
|
GPL-3.0
|
9/4/2024, 11:16:33 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 2,266
|
1,319,008
|
A_test712.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/return_in/A_test712.java
|
package return_in;
import java.util.List;
public class A_test712 {
public List foo() {
/*[*/return null;/*]*/
}
}
| 120
|
Java
|
.java
| 7
| 15.285714
| 24
| 0.675676
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 120
|
1,318,439
|
A_test114.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/SelectionAnalyzerWorkSpace/SelectionAnalyzerTests/invalidSelection/A_test114.java
|
package invalidSelection;
public class A_test114 {
public void foo() {
try {
foo();
} /*]*/finally {
foo();
}/*[*/
}
}
| 133
|
Java
|
.java
| 10
| 10.9
| 25
| 0.577236
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 133
|
4,947,638
|
BenefitsCalculationDocumentRule.java
|
ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/ld/document/validation/impl/BenefitsCalculationDocumentRule.java
|
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.ld.document.validation.impl;
import org.kuali.kfs.module.ld.LaborConstants;
import org.kuali.kfs.module.ld.LaborKeyConstants;
import org.kuali.kfs.module.ld.businessobject.BenefitsCalculation;
import org.kuali.kfs.sys.KFSKeyConstants;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.service.impl.KfsParameterConstants;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kns.document.MaintenanceDocument;
import org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase;
import org.kuali.rice.krad.util.ObjectUtils;
/**
* Business rule(s) applicable to Benefit Calculation Documents.
*/
public class BenefitsCalculationDocumentRule extends MaintenanceDocumentRuleBase {
protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(BenefitsCalculationDocumentRule.class);
protected BenefitsCalculation oldBenefitsCalculation;
protected BenefitsCalculation newBenefitsCalculation;
/**
* Constructs a BenefitsCalculationDocumentRule.java.
*/
public BenefitsCalculationDocumentRule() {
super();
}
/**
* Processes the rules
*
* @param document MaintenanceDocument type of document to be processed.
* @return boolean true when success
* @see org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase#processCustomApproveDocumentBusinessRules(org.kuali.rice.kns.document.MaintenanceDocument)
*/
@Override
protected boolean processCustomApproveDocumentBusinessRules(MaintenanceDocument document) {
LOG.debug("Entering processCustomApproveDocumentBusinessRules()");
// process rules
checkRules(document);
return true;
}
/**
* Processes the rules
*
* @param document MaintenanceDocument type of document to be processed.
* @return boolean true when success
* @see org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase#processCustomRouteDocumentBusinessRules(org.kuali.rice.kns.document.MaintenanceDocument)
*/
@Override
protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument document) {
boolean success = true;
LOG.debug("Entering processCustomRouteDocumentBusinessRules()");
// process rules
success &= checkRules(document);
return success;
}
/**
* Processes the rules
*
* @param document MaintenanceDocument type of document to be processed.
* @return boolean true when success
* @see org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase#processCustomSaveDocumentBusinessRules(org.kuali.rice.kns.document.MaintenanceDocument)
*/
@Override
protected boolean processCustomSaveDocumentBusinessRules(MaintenanceDocument document) {
boolean success = true;
LOG.debug("Entering processCustomSaveDocumentBusinessRules()");
// process rules
success &= checkRules(document);
return success;
}
/**
* Checks the fringe benefit percentage cannot be equal to or over 100%
*
* @param document MaintenanceDocument type
* @return boolean false when the fringe benefit percentage cannot be equal to or over 100%
*/
protected boolean checkRules(MaintenanceDocument document) {
boolean success = true;
/* The fringe benefit percentage cannot be equal to or over 100% */
if (ObjectUtils.isNotNull(newBenefitsCalculation.getPositionFringeBenefitPercent())) {
if (newBenefitsCalculation.getPositionFringeBenefitPercent().isGreaterEqual(new KualiDecimal(100))) {
putFieldError("positionFringeBenefitPercent", LaborKeyConstants.ERROR_FRINGE_BENEFIT_PERCENTAGE_INVALID);
success = false;
}
}
success &= checkLaborBenefitRateCategory();
return success;
}
private boolean checkLaborBenefitRateCategory() {
boolean success = true;
//make sure the system parameter exists
if (SpringContext.getBean(ParameterService.class).parameterExists(KfsParameterConstants.FINANCIAL_SYSTEM_ALL.class, LaborConstants.BenefitCalculation.ENABLE_FRINGE_BENEFIT_CALC_BY_BENEFIT_RATE_CATEGORY_PARAMETER)) {
//check the system param to see if the labor benefit rate category should be filled in
String sysParam = SpringContext.getBean(ParameterService.class).getParameterValueAsString(KfsParameterConstants.FINANCIAL_SYSTEM_ALL.class, LaborConstants.BenefitCalculation.ENABLE_FRINGE_BENEFIT_CALC_BY_BENEFIT_RATE_CATEGORY_PARAMETER);
LOG.debug("sysParam: " + sysParam);
//if sysParam == Y then Labor Benefit Rate Category Code must be filled in
if (sysParam.equalsIgnoreCase("Y")) {
//check to see if the labor benefit category code is empty
if (ObjectUtils.isNull(newBenefitsCalculation.getLaborBenefitRateCategoryCode())) {
putFieldError("laborBenefitRateCategoryCode", KFSKeyConstants.ERROR_EMPTY_LABOR_BENEFIT_CATEGORY_CODE);
success = false;
} else {
newBenefitsCalculation.refreshReferenceObject("laborBenefitRateCategory");
if (newBenefitsCalculation.getLaborBenefitRateCategory() == null) {
putFieldError("laborBenefitRateCategoryCode", KFSKeyConstants.ERROR_LABOR_BENEFIT_CATEGORY_CODE);
success &= false;
}
}
}
}
return success;
}
/**
* This method sets the convenience objects like newAccount and oldAccount, so you have short and easy handles to the new and
* old objects contained in the maintenance document. It also calls the BusinessObjectBase.refresh(), which will attempt to load
* all sub-objects from the DB by their primary keys, if available.
*
* @param document - the maintenanceDocument being evaluated
* @return none
*/
@Override
public void setupConvenienceObjects() {
// setup oldBenefitsCalculation convenience objects, make sure all possible sub-objects are populated
oldBenefitsCalculation = (BenefitsCalculation) super.getOldBo();
// setup newBenefitsCalculation convenience objects, make sure all possible sub-objects are populated
newBenefitsCalculation = (BenefitsCalculation) super.getNewBo();
}
}
| 7,592
|
Java
|
.java
| 145
| 43.896552
| 250
| 0.719735
|
ua-eas/ua-kfs-5.3
| 1
| 0
| 0
|
AGPL-3.0
|
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
| true
| true
| true
| true
| false
| true
| false
| true
| 7,592
|
3,466,820
|
ParserQueryFactory.java
|
benblamey_stanford-nlp/src/edu/stanford/nlp/parser/lexparser/ParserQueryFactory.java
|
package edu.stanford.nlp.parser.lexparser;
/**
* An interface which indicates the class involved can return
* ParserQuery objects. Useful for something that wants to use
* ParserQueries in a multithreaded manner with more than one possible
* ParserQuery source. For example,
* {@link edu.stanford.nlp.parser.lexparser.EvaluateTreebank}
* does this.
*
* @author John Bauer
*/
public interface ParserQueryFactory {
ParserQuery parserQuery();
}
| 458
|
Java
|
.java
| 14
| 30.714286
| 70
| 0.785553
|
benblamey/stanford-nlp
| 3
| 1
| 0
|
GPL-2.0
|
9/4/2024, 11:29:27 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 458
|
1,445,447
|
SimpleValueChecker.java
|
biocompibens_SME/src_java/org/apache/commons/math3/optim/SimpleValueChecker.java
|
/*
* 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.commons.math3.optim;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.exception.NotStrictlyPositiveException;
/**
* Simple implementation of the {@link ConvergenceChecker} interface using
* only objective function values.
*
* Convergence is considered to have been reached if either the relative
* difference between the objective function values is smaller than a
* threshold or if either the absolute difference between the objective
* function values is smaller than another threshold.
* <br/>
* The {@link #converged(int,PointValuePair,PointValuePair) converged}
* method will also return {@code true} if the number of iterations has been set
* (see {@link #SimpleValueChecker(double,double,int) this constructor}).
*
* @since 3.0
*/
public class SimpleValueChecker
extends AbstractConvergenceChecker<PointValuePair> {
/**
* If {@link #maxIterationCount} is set to this value, the number of
* iterations will never cause
* {@link #converged(int,PointValuePair,PointValuePair)}
* to return {@code true}.
*/
private static final int ITERATION_CHECK_DISABLED = -1;
/**
* Number of iterations after which the
* {@link #converged(int,PointValuePair,PointValuePair)} method
* will return true (unless the check is disabled).
*/
private final int maxIterationCount;
/** Build an instance with specified thresholds.
*
* In order to perform only relative checks, the absolute tolerance
* must be set to a negative value. In order to perform only absolute
* checks, the relative tolerance must be set to a negative value.
*
* @param relativeThreshold relative tolerance threshold
* @param absoluteThreshold absolute tolerance threshold
*/
public SimpleValueChecker(final double relativeThreshold,
final double absoluteThreshold) {
super(relativeThreshold, absoluteThreshold);
maxIterationCount = ITERATION_CHECK_DISABLED;
}
/**
* Builds an instance with specified thresholds.
*
* In order to perform only relative checks, the absolute tolerance
* must be set to a negative value. In order to perform only absolute
* checks, the relative tolerance must be set to a negative value.
*
* @param relativeThreshold relative tolerance threshold
* @param absoluteThreshold absolute tolerance threshold
* @param maxIter Maximum iteration count.
* @throws NotStrictlyPositiveException if {@code maxIter <= 0}.
*
* @since 3.1
*/
public SimpleValueChecker(final double relativeThreshold,
final double absoluteThreshold,
final int maxIter) {
super(relativeThreshold, absoluteThreshold);
if (maxIter <= 0) {
throw new NotStrictlyPositiveException(maxIter);
}
maxIterationCount = maxIter;
}
/**
* Check if the optimization algorithm has converged considering the
* last two points.
* This method may be called several time from the same algorithm
* iteration with different points. This can be detected by checking the
* iteration number at each call if needed. Each time this method is
* called, the previous and current point correspond to points with the
* same role at each iteration, so they can be compared. As an example,
* simplex-based algorithms call this method for all points of the simplex,
* not only for the best or worst ones.
*
* @param iteration Index of current iteration
* @param previous Best point in the previous iteration.
* @param current Best point in the current iteration.
* @return {@code true} if the algorithm has converged.
*/
@Override
public boolean converged(final int iteration,
final PointValuePair previous,
final PointValuePair current) {
if (maxIterationCount != ITERATION_CHECK_DISABLED && iteration >= maxIterationCount) {
return true;
}
final double p = previous.getValue();
final double c = current.getValue();
final double difference = FastMath.abs(p - c);
final double size = FastMath.max(FastMath.abs(p), FastMath.abs(c));
return difference <= size * getRelativeThreshold() ||
difference <= getAbsoluteThreshold();
}
}
| 5,292
|
Java
|
.java
| 117
| 39.017094
| 94
| 0.707761
|
biocompibens/SME
| 21
| 3
| 12
|
GPL-3.0
|
9/4/2024, 7:51:38 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 5,292
|
858,173
|
NGram.java
|
joeywen_fudannlp/src/edu/fudan/nlp/pipe/NGram.java
|
package edu.fudan.nlp.pipe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import edu.fudan.ml.types.Instance;
import edu.fudan.util.exception.UnsupportedDataTypeException;
/**
* 由输入序列生成ngram特征,data类型转为List
* 输入数据类型:String[],List<String>,String
* 输出数据类型:List<String>
* @author xpqiu
*
*/
public class NGram extends Pipe{
private static final long serialVersionUID = -2329969202592736092L;
int[] gramSizes = null;
public NGram(int[] sizes) {
this.gramSizes = sizes;
}
@Override
public void addThruPipe(Instance inst) throws UnsupportedDataTypeException {
Object data = inst.getData();
ArrayList<String> list = null;
if (data instanceof String) {
list = ngram((String) data,gramSizes);
}else if (data instanceof List) {
list = ngram((List) data,gramSizes);
}else if(data instanceof String[]){
list = ngram((String[]) data,gramSizes);
}else{
throw new UnsupportedDataTypeException("不支持处理数据类型:"+data.getClass().toString());
}
inst.setData(list);
}
private ArrayList<String> ngram(String[] strs, int[] grams) {
ArrayList<String> list = new ArrayList<String>();
StringBuffer buf = new StringBuffer();
for (int j = 0; j < gramSizes.length; j++) {
int len = gramSizes[j];
if (len <= 0 || len > strs.length)
continue;
for (int i = 0; i < strs.length - len+1; i++) {
buf.delete(0, buf.length());
int k = 0;
for(; k < len-1; ++k) {
buf.append(strs[i+k]);
buf.append(' ');
}
buf.append(strs[i+k]);
list.add(buf.toString().intern());
}
}
return list;
}
private ArrayList<String> ngram(List tokens, int[] gramSizes2) {
ArrayList<String> list = new ArrayList<String>();
StringBuffer buf = new StringBuffer();
for (int j = 0; j < gramSizes.length; j++) {
int len = gramSizes[j];
if (len <= 0 || len > tokens.size())
continue;
for (int i = 0; i < tokens.size() - len+1; i++) {
buf.delete(0, buf.length());
int k = 0;
for(; k < len-1; ++k) {
buf.append(tokens.get(i+k));
buf.append(' ');
}
buf.append(tokens.get(i+k));
list.add(buf.toString().intern());
}
}
return list;
}
/**
* 提取ngram
* @param data
* @param gramSizes
* @return ngram字符串数组
*/
public static ArrayList<String> ngram(String data,int[] gramSizes) {
// 提取ngram
ArrayList<String> list = new ArrayList<String>();
ngram(data, gramSizes, list);
return list;
}
/**
* 提取ngram
* @param data
* @param gramSizes
* @return ngram字符串集合
*/
public static Set<String> ngramSet(String data,int[] gramSizes) {
// 提取ngram
Set<String> list = new HashSet<String>();
ngram(data, gramSizes, list);
return list;
}
private static void ngram(String data, int[] gramSizes, Collection<String> list) {
for (int j = 0; j < gramSizes.length; j++) {
int len = gramSizes[j];
if (len <= 0 || len > data.length())
continue;
for (int i = 0; i < data.length() - len; i++) {
list.add(data.substring(i, i + len));
}
}
}
}
| 3,907
|
Java
|
.java
| 113
| 24.389381
| 92
| 0.544408
|
joeywen/fudannlp
| 71
| 38
| 2
|
GPL-3.0
|
9/4/2024, 7:09:22 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 3,795
|
1,318,463
|
A.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test37/out/A.java
|
package p;
public class A {
B.Inner i;
B.Inner ii;
p.B.Inner iii;
}
class AA {
B.Inner Inner;
}
| 101
|
Java
|
.java
| 9
| 9.666667
| 16
| 0.692308
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 101
|
1,315,221
|
BoundedTypeParam_in.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceFactory/positive/BoundedTypeParam_in.java
|
package p;
public class BoundedTypeParam_in {
public void foo() {
NumberCell<Integer> c1= new NumberCell<Integer>(3);
NumberCell<Float> c2= new NumberCell<Float>(3.14F);
}
}
class NumberCell<T extends Number> {
T fData;
public /*[*/NumberCell/*]*/(T t) {
fData= t;
}
}
| 281
|
Java
|
.java
| 13
| 19.692308
| 53
| 0.70412
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 281
|
1,320,399
|
A.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/PullUp/test8/in/A.java
|
package p;
class A {
int x;
}
class B extends A {
public void m() {
new B(){
void f(){
super.x++;
}
};
}
}
| 127
|
Java
|
.java
| 13
| 7.230769
| 19
| 0.517857
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 127
|
4,136,424
|
BounceEaseIn.java
|
Snowy1013_Ayo2016/ayoview/src/main/java/com/daimajia/easing/bounce/BounceEaseIn.java
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 daimajia
*
* 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.daimajia.easing.bounce;
import com.daimajia.easing.BaseEasingMethod;
public class BounceEaseIn extends BaseEasingMethod {
private BounceEaseOut mBounceEaseOut;
public BounceEaseIn(float duration){
super(duration);
mBounceEaseOut = new BounceEaseOut(duration);
}
@Override
public Float calculate(float t, float b, float c, float d) {
return c - mBounceEaseOut.calculate(d-t, 0, c, d) + b;
}
}
| 1,599
|
Java
|
.java
| 36
| 41.305556
| 81
| 0.759794
|
Snowy1013/Ayo2016
| 2
| 0
| 0
|
GPL-3.0
|
9/5/2024, 12:04:01 AM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 1,599
|
1,872,752
|
Channel.java
|
masach_FaceWhat/FacewhatFire/src/java/org/jivesoftware/openfire/mediaproxy/Channel.java
|
/**
* $Revision$
* $Date$
*
* Copyright (C) 2005-2008 Jive Software. 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 org.jivesoftware.openfire.mediaproxy;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Listen packets from defined dataSocket and send packets to the defined host.
*
* @author Thiago Camargo
*/
abstract class Channel implements Runnable {
private static final Logger Log = LoggerFactory.getLogger(Channel.class);
protected byte[] buf = new byte[5000];
protected DatagramSocket dataSocket;
protected DatagramPacket packet;
protected boolean enabled = true;
List<DatagramListener> listeners = new ArrayList<>();
protected InetAddress host;
protected int port;
/**
* Creates a Channel according to the parameters.
*
* @param dataSocket
* @param host
* @param port
*/
public Channel(DatagramSocket dataSocket, InetAddress host, int port) {
this.dataSocket = dataSocket;
this.host = host;
this.port = port;
}
/**
* Get the host that the packet will be sent to.
*
* @return remote host address
*/
public InetAddress getHost() {
return host;
}
/**
* Set the host that the packet will be sent to.
*/
protected void setHost(InetAddress host) {
this.host = host;
}
/**
* Get the port that the packet will be sent to.
*
* @return The remote port number
*/
public int getPort() {
return port;
}
/**
* Set the port that the packet will be sent to.
*
* @param port
*/
protected void setPort(int port) {
this.port = port;
}
/**
* Adds a DatagramListener to the Channel
*
* @param datagramListener
*/
public void addListener(DatagramListener datagramListener) {
listeners.add(datagramListener);
}
/**
* Remove a DatagramListener from the Channel
*
* @param datagramListener
*/
public void removeListener(DatagramListener datagramListener) {
listeners.remove(datagramListener);
}
/**
* Remove every Listeners
*/
public void removeListeners() {
listeners.removeAll(listeners);
}
public void cancel() {
this.enabled = false;
if (dataSocket != null){
dataSocket.close();
}
}
/**
* Thread override method
*/
@Override
public void run() {
try {
while (enabled) {
// Block until a datagram appears:
packet = new DatagramPacket(buf, buf.length);
dataSocket.receive(packet);
if (handle(packet)) {
boolean resend = true;
for (DatagramListener dl : listeners) {
boolean send = dl.datagramReceived(packet);
if (resend && !send) {
resend = false;
}
}
if (resend) {
relayPacket(packet);
}
}
}
}
catch (UnknownHostException uhe) {
if (enabled) {
Log.error("Unknown Host", uhe);
}
}
catch (SocketException se) {
if (enabled) {
Log.error("Socket closed", se);
}
}
catch (IOException ioe) {
if (enabled) {
Log.error("Communication error", ioe);
}
}
}
public void relayPacket(DatagramPacket packet) {
try {
DatagramPacket echo = new DatagramPacket(packet.getData(), packet.getLength(), host, port);
dataSocket.send(echo);
}
catch (IOException e) {
Log.error(e.getMessage(), e);
}
}
/**
* Handles received packet and returns true if the packet should be processed by the channel.
*
* @param packet received datagram packet
* @return true if listeners will be alerted that a new packet was received.
*/
abstract boolean handle(DatagramPacket packet);
}
| 5,010
|
Java
|
.java
| 170
| 22.058824
| 103
| 0.604526
|
masach/FaceWhat
| 12
| 12
| 0
|
GPL-3.0
|
9/4/2024, 8:21:42 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 5,010
|
3,259,213
|
OrActionItem.java
|
wholesky_ffdec/libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/action/model/operations/OrActionItem.java
|
/*
* Copyright (C) 2010-2018 JPEXS, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*/
package com.jpexs.decompiler.flash.action.model.operations;
import com.jpexs.decompiler.flash.SourceGeneratorLocalData;
import com.jpexs.decompiler.flash.action.swf4.ActionOr;
import com.jpexs.decompiler.flash.ecma.EcmaScript;
import com.jpexs.decompiler.graph.CompilationException;
import com.jpexs.decompiler.graph.GraphSourceItem;
import com.jpexs.decompiler.graph.GraphTargetItem;
import com.jpexs.decompiler.graph.SourceGenerator;
import com.jpexs.decompiler.graph.TypeItem;
import com.jpexs.decompiler.graph.model.BinaryOpItem;
import java.util.List;
/**
*
* @author JPEXS
*/
public class OrActionItem extends BinaryOpItem {
public OrActionItem(GraphSourceItem instruction, GraphSourceItem lineStartIns, GraphTargetItem leftSide, GraphTargetItem rightSide) {
super(instruction, lineStartIns, PRECEDENCE_LOGICALOR, leftSide, rightSide, "or", "Boolean", "Boolean");
}
@Override
public Object getResult() {
return getResult(rightSide.getResult(), leftSide.getResult());
}
public static Boolean getResult(Object rightResult, Object leftResult) {
return EcmaScript.toBoolean(leftResult) || EcmaScript.toBoolean(rightResult);
}
@Override
public List<GraphSourceItem> toSource(SourceGeneratorLocalData localData, SourceGenerator generator) throws CompilationException {
return toSourceMerge(localData, generator, leftSide, rightSide, new ActionOr());
}
@Override
public GraphTargetItem returnType() {
return TypeItem.BOOLEAN;
}
}
| 2,224
|
Java
|
.java
| 50
| 41.1
| 137
| 0.78311
|
wholesky/ffdec
| 4
| 1
| 0
|
GPL-3.0
|
9/4/2024, 11:08:47 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| true
| false
| true
| 2,224
|
3,389,910
|
ConnectionPoolTimeoutException.java
|
FzArnob_Covidease/sources/org/shaded/apache/http/conn/ConnectionPoolTimeoutException.java
|
package org.shaded.apache.http.conn;
import org.shaded.apache.http.annotation.Immutable;
@Immutable
public class ConnectionPoolTimeoutException extends ConnectTimeoutException {
private static final long serialVersionUID = -7898874842020245128L;
public ConnectionPoolTimeoutException() {
}
/* JADX INFO: super call moved to the top of the method (can break code semantics) */
public ConnectionPoolTimeoutException(String message) {
super(message);
}
}
| 488
|
Java
|
.java
| 12
| 36.666667
| 89
| 0.786017
|
FzArnob/Covidease
| 4
| 0
| 0
|
GPL-3.0
|
9/4/2024, 11:17:41 PM (Europe/Amsterdam)
| false
| true
| false
| true
| false
| true
| true
| true
| 488
|
1,165,519
|
TownInfoCommand.java
|
netizen539_civcraft/civcraft/src/com/avrgaming/civcraft/command/town/TownInfoCommand.java
|
/*************************************************************************
*
* AVRGAMING LLC
* __________________
*
* [2013] AVRGAMING LLC
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of AVRGAMING LLC and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to AVRGAMING LLC
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from AVRGAMING LLC.
*/
package com.avrgaming.civcraft.command.town;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.avrgaming.civcraft.command.CommandBase;
import com.avrgaming.civcraft.config.CivSettings;
import com.avrgaming.civcraft.config.ConfigCultureLevel;
import com.avrgaming.civcraft.config.ConfigHappinessState;
import com.avrgaming.civcraft.config.ConfigTownLevel;
import com.avrgaming.civcraft.exception.CivException;
import com.avrgaming.civcraft.exception.InvalidConfiguration;
import com.avrgaming.civcraft.items.BonusGoodie;
import com.avrgaming.civcraft.main.CivGlobal;
import com.avrgaming.civcraft.main.CivMessage;
import com.avrgaming.civcraft.object.AttrSource;
import com.avrgaming.civcraft.object.Buff;
import com.avrgaming.civcraft.object.Civilization;
import com.avrgaming.civcraft.object.CultureChunk;
import com.avrgaming.civcraft.object.Relation;
import com.avrgaming.civcraft.object.Relation.Status;
import com.avrgaming.civcraft.object.Resident;
import com.avrgaming.civcraft.object.Town;
import com.avrgaming.civcraft.object.TradeGood;
import com.avrgaming.civcraft.structure.Bank;
import com.avrgaming.civcraft.structure.Buildable;
import com.avrgaming.civcraft.structure.Cottage;
import com.avrgaming.civcraft.structure.Mine;
import com.avrgaming.civcraft.structure.Structure;
import com.avrgaming.civcraft.structure.TownHall;
import com.avrgaming.civcraft.structure.wonders.Wonder;
import com.avrgaming.civcraft.util.CivColor;
public class TownInfoCommand extends CommandBase {
@Override
public void init() {
command = "/town info";
displayName = "Town Info";
commands.put("upkeep", "Shows town upkeep information.");
commands.put("cottage", "Shows cottage information for town.");
commands.put("structures", "Shows upkeep information related to structures.");
commands.put("culture", "Shows culture information for town.");
commands.put("trade", "Shows town trade good information.");
commands.put("mine", "Shows mine production information.");
commands.put("hammers", "Shows town hammer information.");
commands.put("goodies", "Shows which goodies are being used by the town.");
commands.put("rates", "Shows the culture,growth,trade and cottage rates of this town.");
commands.put("growth", "Shows growth info about the town.");
commands.put("buffs", "Show all special buffs awarded to this town.");
commands.put("online", "Shows a list of town members that are currently online.");
commands.put("happiness", "Shows information about this town's happiness.");
commands.put("beakers", "Shows information about this town's beakers");
commands.put("area", "Shows the various attributes generated by culture chunks.");
commands.put("disabled", "Shows information about disabled structures.");
}
public void disabled_cmd() throws CivException {
Town town = getSelectedTown();
CivMessage.sendHeading(sender, "Disabled Structures");
LinkedList<String> out = new LinkedList<String>();
boolean showhelp = false;
for (Buildable buildable : town.getDisabledBuildables()) {
showhelp = true;
out.add(CivColor.Green+buildable.getDisplayName()+CivColor.LightGreen+" Coord:"+buildable.getCorner().toString());
}
if (showhelp) {
out.add(CivColor.LightGray+"These structures have been disabled in this town since they've exceeded the structure limit.");
out.add(CivColor.LightGray+"To enable them, you must do one of the following:");
out.add(CivColor.LightGray+"1) Move this structure to another town using: /town movestructure <coord>");
out.add(CivColor.LightGray+"2) Demolish this structure with /build demolish <coord> or /build demolishnearest.");
out.add(CivColor.LightGray+"3) Move other structures of the same type to another town, or demolish them, and issue /town enablestructure <coord>");
}
CivMessage.send(sender, out);
}
public void area_cmd() throws CivException {
Town town = getSelectedTown();
CivMessage.sendHeading(sender, "Area Info");
HashMap<String, Integer> biomes = new HashMap<String, Integer>();
double hammers = 0.0;
double growth = 0.0;
double happiness = 0.0;
double beakers = 0.0;
DecimalFormat df = new DecimalFormat();
for (CultureChunk cc : town.getCultureChunks()) {
/* Increment biome counts. */
if (!biomes.containsKey(cc.getBiome().name())) {
biomes.put(cc.getBiome().name(), 1);
} else {
Integer value = biomes.get(cc.getBiome().name());
biomes.put(cc.getBiome().name(), value+1);
}
hammers += cc.getHammers();
growth += cc.getGrowth();
happiness += cc.getHappiness();
beakers += cc.getBeakers();
}
CivMessage.send(sender, CivColor.LightBlue+"Biome Counts");
String out = "";
//int totalBiomes = 0;
for (String biome : biomes.keySet()) {
Integer count = biomes.get(biome);
out += CivColor.Green+biome+": "+CivColor.LightGreen+count+CivColor.Green+", ";
// totalBiomes += count;
}
CivMessage.send(sender, out);
//CivMessage.send(sender, CivColor.Green+"Biome Count:"+CivColor.LightGreen+totalBiomes);
CivMessage.send(sender, CivColor.LightBlue+"Totals");
CivMessage.send(sender, CivColor.Green+" Happiness:"+CivColor.LightGreen+df.format(happiness)+
CivColor.Green+" Hammers:"+CivColor.LightGreen+df.format(hammers)+
CivColor.Green+" Growth:"+CivColor.LightGreen+df.format(growth)+
CivColor.Green+" Beakers:"+CivColor.LightGreen+df.format(beakers));
}
public void beakers_cmd() throws CivException {
Town town = getSelectedTown();
CivMessage.sendHeading(sender, "Beakers Info");
AttrSource beakerSources = town.getBeakers();
CivMessage.send(sender, beakerSources.getSourceDisplayString(CivColor.Green, CivColor.LightGreen));
CivMessage.send(sender, beakerSources.getRateDisplayString(CivColor.Green, CivColor.LightGreen));
CivMessage.send(sender, beakerSources.getTotalDisplayString(CivColor.Green, CivColor.LightGreen));
}
public void happiness_cmd() throws CivException {
Town town = getSelectedTown();
CivMessage.sendHeading(sender, "Happiness Info");
ArrayList<String> out = new ArrayList<String>();
out.add(CivMessage.buildSmallTitle("Happiness Sources"));
AttrSource happySources = town.getHappiness();
DecimalFormat df = new DecimalFormat();
df.applyPattern("###,###");
for (String source : happySources.sources.keySet()) {
Double value = happySources.sources.get(source);
out.add(CivColor.Green+source+": "+CivColor.LightGreen+df.format(value));
}
out.add(CivColor.LightPurple+"Total: "+CivColor.LightGreen+df.format(happySources.total));
out.add(CivMessage.buildSmallTitle("Unhappiness Sources"));
AttrSource unhappySources = town.getUnhappiness();
for (String source : unhappySources.sources.keySet()) {
Double value = unhappySources.sources.get(source);
out.add(CivColor.Green+source+": "+CivColor.LightGreen+value);
}
out.add(CivColor.LightPurple+"Total: "+CivColor.LightGreen+df.format(unhappySources.total));
out.add(CivMessage.buildSmallTitle("Total"));
ConfigHappinessState state = town.getHappinessState();
out.add(CivColor.LightGreen+df.format(town.getHappinessPercentage()*100)+"%"+CivColor.Green+" Happiness. State: "+CivColor.valueOf(state.color)+state.name);
CivMessage.send(sender, out);
}
public void online_cmd() throws CivException {
Town town = getSelectedTown();
CivMessage.sendHeading(sender, "Online Players In "+town.getName());
String out = "";
for (Resident resident : town.getOnlineResidents()) {
out += resident.getName()+" ";
}
CivMessage.send(sender, out);
}
public void buffs_cmd() throws CivException {
Town town = getSelectedTown();
CivMessage.sendHeading(sender, town.getName()+" Buffs");
ArrayList<String> out = new ArrayList<String>();
for (Buff buff : town.getBuffManager().getAllBuffs()) {
out.add(CivColor.Green+"Buff: "+CivColor.LightGreen+buff.getDisplayName()+CivColor.Green+" from "+CivColor.LightGreen+buff.getSource());
}
CivMessage.send(sender, out);
}
public void growth_cmd() throws CivException {
Town town = getSelectedTown();
AttrSource growthSources = town.getGrowth();
CivMessage.sendHeading(sender, town.getName()+" Growth");
CivMessage.send(sender, growthSources.getSourceDisplayString(CivColor.Green, CivColor.LightGreen));
CivMessage.send(sender, growthSources.getRateDisplayString(CivColor.Green, CivColor.LightGreen));
CivMessage.send(sender, growthSources.getTotalDisplayString(CivColor.Green, CivColor.LightGreen));
}
public void goodies_cmd() throws CivException {
Town town = getSelectedTown();
CivMessage.sendHeading(sender, town.getName()+" Goodies");
// HashSet<BonusGoodie> effectiveGoodies = town.getEffectiveBonusGoodies();
for (BonusGoodie goodie : town.getBonusGoodies()) {
CivMessage.send(sender, CivColor.LightGreen+goodie.getDisplayName());
String goodBonuses = goodie.getBonusDisplayString();
String[] split = goodBonuses.split(";");
for (String str : split) {
CivMessage.send(sender, " "+CivColor.LightPurple+str);
}
}
}
public void hammers_cmd() throws CivException {
Town town = getSelectedTown();
CivMessage.sendHeading(sender, "Hammer Info");
AttrSource hammerSources = town.getHammers();
CivMessage.send(sender, hammerSources.getSourceDisplayString(CivColor.Green, CivColor.LightGreen));
CivMessage.send(sender, hammerSources.getRateDisplayString(CivColor.Green, CivColor.LightGreen));
CivMessage.send(sender, hammerSources.getTotalDisplayString(CivColor.Green, CivColor.LightGreen));
}
public void culture_cmd() throws CivException {
Town town = getSelectedTown();
AttrSource cultureSources = town.getCulture();
CivMessage.sendHeading(sender, "Culture Info");
CivMessage.send(sender, cultureSources.getSourceDisplayString(CivColor.Green, CivColor.LightGreen));
CivMessage.send(sender, cultureSources.getRateDisplayString(CivColor.Green, CivColor.LightGreen));
CivMessage.send(sender, cultureSources.getTotalDisplayString(CivColor.Green, CivColor.LightGreen));
}
public void rates_cmd() throws CivException {
Town town = getSelectedTown();
CivMessage.sendHeading(sender, town.getName()+" Rates Summary");
CivMessage.send(sender,
CivColor.Green+"Growth: "+CivColor.LightGreen+(town.getGrowthRate().total*100)+
CivColor.Green+" Culture: "+CivColor.LightGreen+(town.getCulture().total*100)+
CivColor.Green+" Cottage: "+CivColor.LightGreen+(town.getCottageRate()*100)+
CivColor.Green+" Trade: "+CivColor.LightGreen+(town.getTradeRate()*100)+
CivColor.Green+" Beakers: "+CivColor.LightGreen+(town.getBeakerRate().total*100)
);
}
public void trade_cmd() throws CivException {
Town town = getSelectedTown();
ArrayList<String> out = new ArrayList<String>();
CivMessage.sendHeading(sender, town.getName()+" Trade Good Summary");
out.add(CivColor.Green+"Trade Mulitplier: "+CivColor.LightGreen+df.format(town.getTradeRate()));
boolean maxedCount = false;
int goodMax;
try {
goodMax = (Integer)CivSettings.getInteger(CivSettings.goodsConfig, "trade_good_multiplier_max");
} catch (InvalidConfiguration e) {
e.printStackTrace();
throw new CivException("Invalid configuration error.");
}
if (town.getBonusGoodies().size() > 0) {
for (BonusGoodie goodie : town.getBonusGoodies()) {
TradeGood good = goodie.getOutpost().getGood();
int count = TradeGood.getTradeGoodCount(goodie, town)-1;
String countString = ""+count;
if (count > goodMax) {
maxedCount = true;
count = goodMax;
countString = CivColor.LightPurple+count+CivColor.Yellow;
}
CultureChunk cc = CivGlobal.getCultureChunk(goodie.getOutpost().getCorner().getLocation());
if (cc == null) {
out.add(CivColor.Rose+goodie.getDisplayName()+" - Trade Outpost not inside culture! Goodie cannot be used.");
} else {
out.add(CivColor.LightGreen+goodie.getDisplayName()+"("+goodie.getOutpost().getCorner()+")"+CivColor.Yellow+" "+
TradeGood.getBaseValue(good)+" * (1.0 + (0.5 * "+(countString)+") = "+df.format(TradeGood.getTradeGoodValue(goodie, town)));
}
}
} else {
out.add(CivColor.Rose+"No trade goods.");
}
out.add(CivColor.LightBlue+"=================================================");
if (maxedCount) {
out.add(CivColor.LightPurple+"Goods in this color have reached the max good multiplier");
}
out.add(CivColor.LightGray+"Base Value * ( 100% + ( 50% * MIN(ExtraGoods,"+goodMax+") )) = Good Value");
out.add(CivColor.Green+"Total Trade: Good Total: "+CivColor.Yellow+df.format(TradeGood.getTownBaseGoodPaymentViaGoodie(town))+" * "+df.format(town.getTradeRate())+" = "
+df.format(TradeGood.getTownTradePayment(town)));
CivMessage.send(sender, out);
return;
}
public void showDebugStructureInfo(Town town) {
CivMessage.sendHeading(sender, "Structures In Town");
for (Structure struct : town.getStructures()) {
CivMessage.send(sender, struct.getDisplayName()+": Corner:"+struct.getCorner()+" center:"+struct.getCenterLocation());
}
}
public void structures_cmd() throws CivException {
Town town = getSelectedTown();
if (args.length > 1) {
if (args[1].equalsIgnoreCase("debug")) {
showDebugStructureInfo(town);
return;
}
}
HashMap<String, Double> structsByName = new HashMap<String, Double>();
for (Structure struct : town.getStructures()) {
Double upkeep = structsByName.get(struct.getConfigId());
if (upkeep == null) {
structsByName.put(struct.getDisplayName(), struct.getUpkeepCost());
} else {
upkeep += struct.getUpkeepCost();
structsByName.put(struct.getDisplayName(), upkeep);
}
}
CivMessage.sendHeading(sender, town.getName()+" Structure Info");
for (String structName : structsByName.keySet()) {
Double upkeep = structsByName.get(structName);
CivMessage.send(sender, CivColor.Green+structName+" Upkeep: "+CivColor.LightGreen+upkeep);
}
CivMessage.sendHeading(sender, town.getName()+" Wonder Info");
for (Wonder wonder : town.getWonders()) {
CivMessage.send(sender, CivColor.Green+wonder.getDisplayName()+" Upkeep: "+CivColor.LightGreen+wonder.getUpkeepCost());
}
}
public void cottage_cmd() throws CivException {
Town town = getSelectedTown();
ArrayList<String> out = new ArrayList<String>();
CivMessage.sendHeading(sender, town.getName()+" Cottage Info");
double total = 0;
for (Structure struct : town.getStructures()) {
if (!struct.getConfigId().equals("ti_cottage")) {
continue;
}
Cottage cottage = (Cottage)struct;
String color;
if (struct.isActive()) {
color = CivColor.LightGreen;
} else {
color = CivColor.Rose;
}
double coins = cottage.getCoinsGenerated();
if (town.getCiv().hasTechnology("tech_taxation")) {
double taxation_bonus;
try {
taxation_bonus = CivSettings.getDouble(CivSettings.techsConfig, "taxation_cottage_buff");
coins *= taxation_bonus;
} catch (InvalidConfiguration e) {
e.printStackTrace();
}
}
if (!struct.isDestroyed()) {
out.add(color+"Cottage ("+struct.getCorner()+")");
out.add(CivColor.Green+" level: "+CivColor.Yellow+cottage.getLevel()+
CivColor.Green+" count: "+CivColor.Yellow+"("+cottage.getCount()+"/"+cottage.getMaxCount()+")");
out.add(CivColor.Green+" base coins: "+CivColor.Yellow+coins+
CivColor.Green+" Last Result: "+CivColor.Yellow+cottage.getLastResult().name());
} else {
out.add(color+"Cottage ("+struct.getCorner()+")");
out.add(CivColor.Rose+" DESTROYED ");
}
total += coins;
}
out.add(CivColor.Green+"----------------------------");
out.add(CivColor.Green+"Sub Total: "+CivColor.Yellow+total);
out.add(CivColor.Green+"Cottage Rate: "+CivColor.Yellow+df.format(town.getCottageRate()*100)+"%");
total *= town.getCottageRate();
out.add(CivColor.Green+"Total: "+CivColor.Yellow+df.format(total)+" coins.");
CivMessage.send(sender, out);
}
public void mine_cmd() throws CivException {
Town town = getSelectedTown();
ArrayList<String> out = new ArrayList<String>();
CivMessage.sendHeading(sender, town.getName()+" Mine Info");
double total = 0;
for (Structure struct : town.getStructures()) {
if (!struct.getConfigId().equals("ti_mine")) {
continue;
}
Mine mine = (Mine)struct;
String color;
if (struct.isActive()) {
color = CivColor.LightGreen;
} else {
color = CivColor.Rose;
}
out.add(color+"Mine ("+struct.getCorner()+")");
out.add(CivColor.Green+" level: "+CivColor.Yellow+mine.getLevel()+
CivColor.Green+" count: "+CivColor.Yellow+"("+mine.getCount()+"/"+mine.getMaxCount()+")");
out.add(CivColor.Green+" hammers per tile: "+CivColor.Yellow+mine.getHammersPerTile()+
CivColor.Green+" Last Result: "+CivColor.Yellow+mine.getLastResult().name());
total += mine.getHammersPerTile()*9; //XXX estimate based on tile radius of 1.
}
out.add(CivColor.Green+"----------------------------");
out.add(CivColor.Green+"Sub Total: "+CivColor.Yellow+total);
out.add(CivColor.Green+"Total: "+CivColor.Yellow+df.format(total)+" hammers (estimate).");
CivMessage.send(sender, out);
}
public void upkeep_cmd() throws CivException {
Town town = getSelectedTown();
CivMessage.sendHeading(sender, town.getName()+" Upkeep Info");
CivMessage.send(sender, CivColor.Green+"Base Upkeep: "+CivColor.LightGreen+town.getBaseUpkeep());
try {
CivMessage.send(sender, CivColor.Green+"Spread Upkeep: "+CivColor.LightGreen+town.getSpreadUpkeep());
} catch (InvalidConfiguration e) {
e.printStackTrace();
throw new CivException("Internal configuration error.");
}
CivMessage.send(sender, CivColor.Green+"Structure Upkeep: "+CivColor.LightGreen+town.getStructureUpkeep());
try {
CivMessage.send(sender, CivColor.Green+"SubTotal: "+CivColor.LightGreen+town.getTotalUpkeep()+
CivColor.Green+" Upkeep Rate: "+CivColor.LightGreen+town.getGovernment().upkeep_rate);
} catch (InvalidConfiguration e) {
e.printStackTrace();
throw new CivException("Internal configuration error.");
}
CivMessage.send(sender, CivColor.LightGray+"---------------------------------");
try {
CivMessage.send(sender, CivColor.Green+"Total: "+CivColor.LightGreen+town.getTotalUpkeep()*town.getCiv().getGovernment().upkeep_rate);
} catch (InvalidConfiguration e) {
e.printStackTrace();
throw new CivException("Internal configuration error.");
}
}
public static void show(CommandSender sender, Resident resident, Town town, Civilization civ, CommandBase parent) throws CivException {
DecimalFormat df = new DecimalFormat();
boolean isAdmin = false;
if (resident != null) {
Player player = CivGlobal.getPlayer(resident);
isAdmin = player.hasPermission(CivSettings.MINI_ADMIN);
} else {
/* We're the console! */
isAdmin = true;
}
CivMessage.sendHeading(sender, town.getName()+" Info ");
ConfigTownLevel level = CivSettings.townLevels.get(town.getLevel());
CivMessage.send(sender, CivColor.Green+"Civilization: "+CivColor.LightGreen+town.getCiv().getName());
CivMessage.send(sender, CivColor.Green+"Town Level: "+CivColor.LightGreen+town.getLevel()+" ("+town.getLevelTitle()+") "+
CivColor.Green+"Score: "+CivColor.LightGreen+town.getScore());
if (town.getMayorGroup() == null) {
CivMessage.send(sender, CivColor.Green+"Mayors: "+CivColor.Rose+"NONE");
} else {
CivMessage.send(sender, CivColor.Green+"Mayors: "+CivColor.LightGreen+town.getMayorGroup().getMembersString());
}
if (town.getAssistantGroup() == null) {
CivMessage.send(sender, CivColor.Green+"Assistants: "+CivColor.Rose+"NONE");
} else {
CivMessage.send(sender, CivColor.Green+"Assistants: "+CivColor.LightGreen+town.getAssistantGroup().getMembersString());
}
if (resident == null || civ.hasResident(resident) || isAdmin) {
String color = CivColor.LightGreen;
if (town.getTileImprovementCount() > level.tile_improvements) {
color = CivColor.Rose;
}
CivMessage.send(sender, CivColor.Green+"Plots: "+CivColor.LightGreen+"("+town.getTownChunks().size()+"/"+town.getMaxPlots()+") "+
CivColor.Green+" Tile Improvements: "+CivColor.LightGreen+"("+color+town.getTileImprovementCount()+CivColor.LightGreen+"/"+level.tile_improvements+")");
//CivMessage.send(sender, CivColor.Green+"Outposts: "+CivColor.LightGreen+town.getOutpostChunks().size()+" "+
CivMessage.send(sender, CivColor.Green+"Growth: "+CivColor.LightGreen+df.format(town.getGrowth().total)+" " +
CivColor.Green+"Hammers: "+CivColor.LightGreen+df.format(town.getHammers().total)+" "+
CivColor.Green+"Beakers: "+CivColor.LightGreen+df.format(town.getBeakers().total));
CivMessage.send(sender, CivColor.Green+"Members: "+CivColor.LightGreen+town.getResidentCount()+" "+
CivColor.Green+"Tax Rate: "+CivColor.LightGreen+town.getTaxRateString()+" "+
CivColor.Green+"Flat Tax: "+CivColor.LightGreen+town.getFlatTax()+" coins.");
HashMap<String,String> info = new HashMap<String, String>();
// info.put("Happiness", CivColor.White+"("+CivColor.LightGreen+"H"+CivColor.Yellow+town.getHappinessTotal()
// +CivColor.White+"/"+CivColor.Rose+"U"+CivColor.Yellow+town.getUnhappinessTotal()+CivColor.White+") = "+
// CivColor.LightGreen+df.format(town.getHappinessPercentage()*100)+"%");
info.put("Happiness", CivColor.LightGreen+df.format(Math.floor(town.getHappinessPercentage()*100))+"%");
ConfigHappinessState state = town.getHappinessState();
info.put("State", ""+CivColor.valueOf(state.color)+state.name);
CivMessage.send(sender, parent.makeInfoString(info, CivColor.Green, CivColor.LightGreen));
ConfigCultureLevel clc = CivSettings.cultureLevels.get(town.getCultureLevel());
CivMessage.send(sender, CivColor.Green+"Culture: "+CivColor.LightGreen+"Level: "+clc.level+" ("+town.getAccumulatedCulture()+"/"+clc.amount+")"+
CivColor.Green+" Online: "+CivColor.LightGreen+town.getOnlineResidents().size());
}
if (town.getBonusGoodies().size() > 0) {
String goodies = "";
for (BonusGoodie goodie : town.getBonusGoodies()) {
goodies += goodie.getDisplayName()+",";
}
CivMessage.send(sender, CivColor.Green+"Goodies: "+CivColor.LightGreen+goodies);
}
if (resident == null || town.isInGroup("mayors", resident) || town.isInGroup("assistants", resident) ||
civ.getLeaderGroup().hasMember(resident) || civ.getAdviserGroup().hasMember(resident) || isAdmin) {
try {
CivMessage.send(sender, CivColor.Green+"Treasury: "+CivColor.LightGreen+town.getBalance()+CivColor.Green+" coins. Upkeep: "+CivColor.LightGreen+town.getTotalUpkeep()*town.getGovernment().upkeep_rate);
Structure bank = town.getStructureByType("s_bank");
if (bank != null) {
CivMessage.send(sender, CivColor.Green+"Interest Rate: "+CivColor.LightGreen+df.format(((Bank)bank).getInterestRate()*100)+"%"+
CivColor.Green+" Principle: "+CivColor.LightGreen+town.getTreasury().getPrincipalAmount());
} else {
CivMessage.send(sender, CivColor.Green+"Interest Rate: "+CivColor.LightGreen+"N/A(No Bank) "+
CivColor.Green+"Principal: "+CivColor.LightGreen+"N/A(No Bank)");
}
} catch (InvalidConfiguration e) {
e.printStackTrace();
throw new CivException("Internal configuration error.");
}
}
if (town.inDebt()) {
CivMessage.send(sender, CivColor.Green+"Debt: "+CivColor.Yellow+town.getDebt()+" coins");
CivMessage.send(sender, CivColor.Yellow+"Our town is in debt! Use '/town deposit' to pay it off.");
}
if (town.getMotherCiv() != null) {
CivMessage.send(sender, CivColor.Yellow+"We yearn for our old motherland of "+CivColor.LightPurple+town.getMotherCiv().getName()+CivColor.Yellow+"!");
}
if (town.hasDisabledStructures()) {
CivMessage.send(sender, CivColor.Rose+"Town has some disabled structures. See /town info disabled.");
}
if (isAdmin) {
TownHall townhall = town.getTownHall();
if (townhall == null) {
CivMessage.send(sender, CivColor.LightPurple+"NO TOWN HALL");
} else {
CivMessage.send(sender, CivColor.LightPurple+"Location:"+townhall.getCorner());
}
String wars = "";
for (Relation relation : town.getCiv().getDiplomacyManager().getRelations()) {
if (relation.getStatus() == Status.WAR) {
wars += relation.getOtherCiv().getName()+", ";
}
}
CivMessage.send(sender, CivColor.LightPurple+"Wars: "+wars);
}
}
private void show_info() throws CivException {
Civilization civ = getSenderCiv();
Town town = getSelectedTown();
Resident resident = getResident();
show(sender, resident, town, civ, this);
}
@Override
public void doDefaultAction() throws CivException {
show_info();
CivMessage.send(sender, CivColor.LightGray+"Subcommands available: See /town info help");
}
@Override
public void showHelp() {
showBasicHelp();
}
@Override
public void permissionCheck() throws CivException {
}
}
| 26,041
|
Java
|
.java
| 526
| 45.326996
| 204
| 0.731544
|
netizen539/civcraft
| 35
| 62
| 7
|
GPL-2.0
|
9/4/2024, 7:20:46 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 26,041
|
1,405,767
|
ExShowQuestMark.java
|
oonym_l2InterludeServer/L2J_Server/java/net/sf/l2j/gameserver/serverpackets/ExShowQuestMark.java
|
/* 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 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* http://www.gnu.org/copyleft/gpl.html
*/
package net.sf.l2j.gameserver.serverpackets;
/**
* @author Luca Baldi
*/
public class ExShowQuestMark extends L2GameServerPacket
{
private final int _questId;
public ExShowQuestMark(int questId)
{
_questId = questId;
}
/**
* @see net.sf.l2j.gameserver.serverpackets.L2GameServerPacket#getType()
*/
@Override
public String getType()
{
// TODO Auto-generated method stub
return null;
}
/**
* @see net.sf.l2j.gameserver.serverpackets.L2GameServerPacket#writeImpl()
*/
@Override
protected void writeImpl()
{
// TODO Auto-generated method stub
writeC(0xfe);
writeH(0x1a);
writeD(_questId);
}
}
| 1,439
|
Java
|
.java
| 49
| 25.979592
| 76
| 0.726017
|
oonym/l2InterludeServer
| 22
| 13
| 0
|
GPL-2.0
|
9/4/2024, 7:49:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| true
| true
| 1,439
|
4,838,369
|
UndoCoreHelperDecorator.java
|
kopl_misc/JaMoPP Performance Test/testcode/argouml-usecase-variant/src/org/argouml/model/mdr/UndoCoreHelperDecorator.java
|
// $Id: UndoCoreHelperDecorator.java 29 2010-04-03 18:35:11Z marcusvnac $
// Copyright (c) 2005-2007 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.model.mdr;
import java.util.Collection;
import java.util.List;
import org.argouml.model.AbstractCoreHelperDecorator;
import org.argouml.model.CoreHelper;
import org.argouml.model.DummyModelCommand;
import org.argouml.model.Model;
import org.argouml.model.ModelCommand;
/**
* This Decorator is responsible for generating commands for any
* mutable methods.
*
* @author Bob Tarling
* @author Linus Tolke
*/
@SuppressWarnings("deprecation")
class UndoCoreHelperDecorator extends AbstractCoreHelperDecorator {
/**
* Constructor.
*
* @param component The component we are decorating.
*/
UndoCoreHelperDecorator(CoreHelper component) {
super(component);
}
// Helper interfaces and methods.
/**
* Interface to set a boolean value.
*/
protected interface BooleanSetter {
/**
* Do the actual setting.
*
* @param value The new value.
*/
void set(boolean value);
}
/**
* Interface to set a Object value.
*/
protected interface ObjectSetter {
/**
* Do the actual setting.
*
* @param value The new value.
*/
void set(Object value);
}
/**
* Interface to set a String value.
*/
protected interface StringSetter {
/**
* Do the actual setting.
*
* @param value The new value.
*/
void set(String value);
}
/**
* Create a command for a setter of a boolean value.
*
* @param accesser The accesser.
* @param newValue The new value.
* @param oldValue The old value.
*/
private void createCommand(
final BooleanSetter accesser,
final boolean newValue, final boolean oldValue) {
if (newValue == oldValue) {
return;
}
ModelCommand command = new ModelCommand() {
public void undo() {
accesser.set(oldValue);
}
public Object execute() {
accesser.set(newValue);
return null;
}
public boolean isUndoable() {
return true;
}
public boolean isRedoable() {
return true;
}
};
Model.execute(command);
}
/**
* Create a command for a setter of a Object value.
*
* @param accesser The accesser.
* @param newValue The new value.
* @param oldValue The old value.
*/
private void createCommand(
final ObjectSetter accesser,
final Object newValue, final Object oldValue) {
if (newValue == oldValue) {
return;
}
if (newValue != null
&& newValue.equals(oldValue)) {
return;
}
ModelCommand command = new ModelCommand() {
public void undo() {
accesser.set(oldValue);
}
public Object execute() {
accesser.set(newValue);
return null;
}
public boolean isUndoable() {
return true;
}
public boolean isRedoable() {
return true;
}
};
Model.execute(command);
}
/**
* Create a command for a setter of a String value.
*
* @param accesser The accesser.
* @param newValue The new value.
* @param oldValue The old value.
*/
private void createCommand(
final StringSetter accesser,
final String newValue, final String oldValue) {
if (newValue == oldValue) {
return;
}
if (newValue != null
&& newValue.equals(oldValue)) {
return;
}
ModelCommand command = new ModelCommand() {
public void undo() {
accesser.set(oldValue);
}
public Object execute() {
accesser.set(newValue);
return null;
}
public boolean isUndoable() {
return true;
}
public boolean isRedoable() {
return true;
}
};
Model.execute(command);
}
public void setAbstract(final Object handle, boolean flag) {
createCommand(new BooleanSetter() {
public void set(boolean value) {
getComponent().setAbstract(handle, value);
}
}, flag, Model.getFacade().isAbstract(handle));
}
public void setActive(final Object handle, boolean active) {
createCommand(new BooleanSetter() {
public void set(boolean value) {
getComponent().setActive(handle, value);
}
}, active, Model.getFacade().isActive(handle));
}
public void setAggregation(final Object handle, Object aggregationKind) {
createCommand(new ObjectSetter() {
public void set(Object value) {
getComponent().setAggregation(handle, value);
}
}, aggregationKind, Model.getFacade().getAggregation(handle));
}
public void setLeaf(final Object handle, boolean flag) {
createCommand(new BooleanSetter() {
public void set(boolean value) {
getComponent().setLeaf(handle, value);
}
}, flag, Model.getFacade().isLeaf(handle));
}
@Override
public void setChangeability(final Object handle, Object ck) {
createCommand(new ObjectSetter() {
public void set(Object value) {
getComponent().setChangeability(handle, value);
}
}, ck, Model.getFacade().getChangeability(handle));
}
@Override
public void setReadOnly(final Object handle, boolean flag) {
createCommand(new BooleanSetter() {
public void set(boolean value) {
getComponent().setReadOnly(handle, value);
}
}, flag, Model.getFacade().isReadOnly(handle));
}
public void setConcurrency(final Object handle, Object concurrencyKind) {
createCommand(new ObjectSetter() {
public void set(Object value) {
getComponent().setConcurrency(handle, value);
}
}, concurrencyKind, Model.getFacade().getConcurrency(handle));
}
public void setKind(final Object handle, Object kind) {
createCommand(new ObjectSetter() {
public void set(Object value) {
getComponent().setKind(handle, value);
}
}, kind, Model.getFacade().getKind(handle));
}
public void setMultiplicity(final Object handle, Object arg) {
createCommand(new ObjectSetter() {
public void set(Object value) {
getComponent().setMultiplicity(handle, value);
}
}, arg, Model.getFacade().getMultiplicity(handle));
}
public void setBody(final Object handle, String body) {
createCommand(new StringSetter() {
public void set(String value) {
getComponent().setBody(handle, value);
}
}, body, Model.getCoreHelper().getBody(handle));
}
public void setNavigable(final Object handle, boolean flag) {
createCommand(new BooleanSetter() {
public void set(boolean value) {
getComponent().setNavigable(handle, value);
}
}, flag, Model.getFacade().isNavigable(handle));
}
public void setOrdering(final Object handle, Object ok) {
createCommand(new ObjectSetter() {
public void set(Object value) {
getComponent().setOrdering(handle, value);
}
}, ok, Model.getFacade().getOrdering(handle));
}
public void setPowertype(final Object handle, Object pt) {
createCommand(new ObjectSetter() {
public void set(Object value) {
getComponent().setPowertype(handle, value);
}
}, pt, Model.getFacade().getPowertype(handle));
}
public void setQuery(final Object handle, boolean flag) {
createCommand(new BooleanSetter() {
public void set(boolean value) {
getComponent().setQuery(handle, value);
}
}, flag, Model.getFacade().isQuery(handle));
}
public void setRoot(final Object handle, boolean flag) {
createCommand(new BooleanSetter() {
public void set(boolean value) {
getComponent().setRoot(handle, value);
}
}, flag, Model.getFacade().isRoot(handle));
}
public void setSpecification(final Object handle, boolean specification) {
createCommand(new BooleanSetter() {
public void set(boolean value) {
getComponent().setSpecification(handle, value);
}
}, specification, Model.getFacade().isSpecification(handle));
}
public void setSpecification(final Object handle, String specification) {
createCommand(new StringSetter() {
public void set(String value) {
getComponent().setSpecification(handle, value);
}
}, specification, Model.getFacade().getSpecification(handle));
}
public void setSpecification(final Object handle, Object specification) {
createCommand(new ObjectSetter() {
public void set(Object value) {
getComponent().setSpecification(handle, value);
}
}, specification, Model.getCoreHelper().getSpecification(handle));
}
@Override
public void setTargetScope(final Object handle, Object scopeKind) {
createCommand(new ObjectSetter() {
public void set(Object value) {
getComponent().setTargetScope(handle, value);
}
}, scopeKind, Model.getFacade().getTargetScope(handle));
}
@Override
public void setVisibility(final Object handle, Object visibility) {
createCommand(new ObjectSetter() {
public void set(Object value) {
getComponent().setVisibility(handle, value);
}
}, visibility, Model.getFacade().getVisibility(handle));
}
public void addAllStereotypes(Object modelElement, Collection stereotypes) {
super.addAllStereotypes(modelElement, stereotypes);
Model.execute(new DummyModelCommand());
}
public void addAnnotatedElement(Object comment, Object annotatedElement) {
super.addAnnotatedElement(comment, annotatedElement);
Model.execute(new DummyModelCommand());
}
public void addClient(Object handle, Object element) {
super.addClient(handle, element);
Model.execute(new DummyModelCommand());
}
public void addClientDependency(Object handle, Object dependency) {
super.addClientDependency(handle, dependency);
Model.execute(new DummyModelCommand());
}
public void addComment(Object element, Object comment) {
super.addComment(element, comment);
Model.execute(new DummyModelCommand());
}
public void addConnection(Object handle, Object connection) {
super.addConnection(handle, connection);
Model.execute(new DummyModelCommand());
}
public void addConnection(Object handle, int position, Object connection) {
super.addConnection(handle, position, connection);
Model.execute(new DummyModelCommand());
}
public void addConstraint(Object handle, Object mc) {
super.addConstraint(handle, mc);
Model.execute(new DummyModelCommand());
}
public void addDeploymentLocation(Object handle, Object node) {
super.addDeploymentLocation(handle, node);
Model.execute(new DummyModelCommand());
}
public void addElementResidence(Object handle, Object residence) {
super.addElementResidence(handle, residence);
Model.execute(new DummyModelCommand());
}
public void addFeature(Object handle, int index, Object f) {
super.addFeature(handle, index, f);
Model.execute(new DummyModelCommand());
}
public void addLiteral(Object handle, int index, Object literal) {
super.addLiteral(handle, index, literal);
Model.execute(new DummyModelCommand());
}
public void addFeature(Object handle, Object f) {
super.addFeature(handle, f);
Model.execute(new DummyModelCommand());
}
public void addLink(Object handle, Object link) {
super.addLink(handle, link);
Model.execute(new DummyModelCommand());
}
public void addMethod(Object handle, Object m) {
super.addMethod(handle, m);
Model.execute(new DummyModelCommand());
}
public void addOwnedElement(Object handle, Object me) {
super.addOwnedElement(handle, me);
Model.execute(new DummyModelCommand());
}
public void addParameter(Object handle, int index, Object parameter) {
super.addParameter(handle, index, parameter);
Model.execute(new DummyModelCommand());
}
public void addParameter(Object handle, Object parameter) {
super.addParameter(handle, parameter);
Model.execute(new DummyModelCommand());
}
public void addQualifier(Object handle, int index, Object qualifier) {
super.addQualifier(handle, index, qualifier);
Model.execute(new DummyModelCommand());
}
public void addRaisedSignal(Object handle, Object sig) {
super.addRaisedSignal(handle, sig);
Model.execute(new DummyModelCommand());
}
public void addSourceFlow(Object handle, Object flow) {
super.addSourceFlow(handle, flow);
Model.execute(new DummyModelCommand());
}
public void addStereotype(Object modelElement, Object stereotype) {
super.addStereotype(modelElement, stereotype);
Model.execute(new DummyModelCommand());
}
public void addSupplier(Object handle, Object element) {
super.addSupplier(handle, element);
Model.execute(new DummyModelCommand());
}
public void addSupplierDependency(Object supplier, Object dependency) {
super.addSupplierDependency(supplier, dependency);
Model.execute(new DummyModelCommand());
}
public void addTargetFlow(Object handle, Object flow) {
super.addTargetFlow(handle, flow);
Model.execute(new DummyModelCommand());
}
public void addTemplateParameter(Object handle, int index,
Object parameter) {
super.addTemplateParameter(handle, index, parameter);
Model.execute(new DummyModelCommand());
}
public void addTemplateParameter(Object handle, Object parameter) {
super.addTemplateParameter(handle, parameter);
Model.execute(new DummyModelCommand());
}
public void clearStereotypes(Object modelElement) {
super.clearStereotypes(modelElement);
Model.execute(new DummyModelCommand());
}
public void removeAnnotatedElement(Object handle, Object me) {
super.removeAnnotatedElement(handle, me);
Model.execute(new DummyModelCommand());
}
public void removeClientDependency(Object handle, Object dep) {
super.removeClientDependency(handle, dep);
Model.execute(new DummyModelCommand());
}
public void removeConnection(Object handle, Object connection) {
super.removeConnection(handle, connection);
Model.execute(new DummyModelCommand());
}
public void removeConstraint(Object handle, Object cons) {
super.removeConstraint(handle, cons);
Model.execute(new DummyModelCommand());
}
public void removeDeploymentLocation(Object handle, Object node) {
super.removeDeploymentLocation(handle, node);
Model.execute(new DummyModelCommand());
}
public void removeElementResidence(Object handle, Object residence) {
super.removeElementResidence(handle, residence);
Model.execute(new DummyModelCommand());
}
public void removeFeature(Object cls, Object feature) {
super.removeFeature(cls, feature);
Model.execute(new DummyModelCommand());
}
public void removeLiteral(Object enu, Object literal) {
super.removeLiteral(enu, literal);
Model.execute(new DummyModelCommand());
}
public void removeOwnedElement(Object handle, Object value) {
super.removeOwnedElement(handle, value);
Model.execute(new DummyModelCommand());
}
public void removeParameter(Object handle, Object parameter) {
super.removeParameter(handle, parameter);
Model.execute(new DummyModelCommand());
}
public void removeQualifier(Object handle, Object qualifier) {
super.removeQualifier(handle, qualifier);
Model.execute(new DummyModelCommand());
}
/**
* @see org.argouml.model.AbstractCoreHelperDecorator#removeSourceFlow(
* java.lang.Object, java.lang.Object)
*/
public void removeSourceFlow(Object handle, Object flow) {
super.removeSourceFlow(handle, flow);
Model.execute(new DummyModelCommand());
}
/**
* @see org.argouml.model.AbstractCoreHelperDecorator#removeStereotype(
* java.lang.Object, java.lang.Object)
*/
public void removeStereotype(Object modelElement, Object stereotype) {
super.removeStereotype(modelElement, stereotype);
Model.execute(new DummyModelCommand());
}
/**
* @see org.argouml.model.AbstractCoreHelperDecorator#removeSupplierDependency(
* java.lang.Object, java.lang.Object)
*/
public void removeSupplierDependency(Object supplier, Object dependency) {
super.removeSupplierDependency(supplier, dependency);
Model.execute(new DummyModelCommand());
}
public void removeTargetFlow(Object handle, Object flow) {
super.removeTargetFlow(handle, flow);
Model.execute(new DummyModelCommand());
}
public void removeTemplateArgument(Object handle, Object argument) {
super.removeTemplateArgument(handle, argument);
Model.execute(new DummyModelCommand());
}
public void removeTemplateParameter(Object handle, Object parameter) {
super.removeTemplateParameter(handle, parameter);
Model.execute(new DummyModelCommand());
}
public void setAnnotatedElements(Object handle, Collection elems) {
super.setAnnotatedElements(handle, elems);
Model.execute(new DummyModelCommand());
}
public void setAssociation(Object handle, Object association) {
super.setAssociation(handle, association);
Model.execute(new DummyModelCommand());
}
public void setAttributes(Object classifier, List attributes) {
super.setAttributes(classifier, attributes);
Model.execute(new DummyModelCommand());
}
public void setBody(Object handle, Object expr) {
super.setBody(handle, expr);
Model.execute(new DummyModelCommand());
}
public void setChild(Object handle, Object child) {
super.setChild(handle, child);
Model.execute(new DummyModelCommand());
}
public void setConnections(Object handle, Collection elems) {
super.setConnections(handle, elems);
Model.execute(new DummyModelCommand());
}
public void setContainer(Object handle, Object component) {
super.setContainer(handle, component);
Model.execute(new DummyModelCommand());
}
public void setDefaultElement(Object handle, Object element) {
super.setDefaultElement(handle, element);
Model.execute(new DummyModelCommand());
}
public void setDefaultValue(Object handle, Object expr) {
super.setDefaultValue(handle, expr);
Model.execute(new DummyModelCommand());
}
public void setDiscriminator(Object handle, String discriminator) {
super.setDiscriminator(handle, discriminator);
Model.execute(new DummyModelCommand());
}
public void setEnumerationLiterals(Object enumeration, List literals) {
super.setEnumerationLiterals(enumeration, literals);
Model.execute(new DummyModelCommand());
}
public void setFeature(Object elem, int i, Object feature) {
super.setFeature(elem, i, feature);
Model.execute(new DummyModelCommand());
}
public void setFeatures(Object handle, Collection features) {
super.setFeatures(handle, features);
Model.execute(new DummyModelCommand());
}
public void setInitialValue(Object at, Object expr) {
super.setInitialValue(at, expr);
Model.execute(new DummyModelCommand());
}
public void setModelElementContainer(Object handle, Object container) {
super.setModelElementContainer(handle, container);
Model.execute(new DummyModelCommand());
}
public void setNamespace(Object handle, Object ns) {
super.setNamespace(handle, ns);
Model.execute(new DummyModelCommand());
}
public void setOperations(Object classifier, List operations) {
super.setOperations(classifier, operations);
Model.execute(new DummyModelCommand());
}
public void setOwner(Object handle, Object owner) {
super.setOwner(handle, owner);
Model.execute(new DummyModelCommand());
}
public void setStatic(Object handle, boolean isStatic) {
super.setStatic(handle, isStatic);
Model.execute(new DummyModelCommand());
}
public void setParameters(Object handle, Collection parameters) {
super.setParameters(handle, parameters);
Model.execute(new DummyModelCommand());
}
public void setParent(Object handle, Object parent) {
super.setParent(handle, parent);
Model.execute(new DummyModelCommand());
}
public void setQualifiers(Object handle, List elems) {
super.setQualifiers(handle, elems);
Model.execute(new DummyModelCommand());
}
public void setRaisedSignals(Object handle, Collection raisedSignals) {
super.setRaisedSignals(handle, raisedSignals);
Model.execute(new DummyModelCommand());
}
public void setResident(Object handle, Object resident) {
super.setResident(handle, resident);
Model.execute(new DummyModelCommand());
}
public void setResidents(Object handle, Collection residents) {
super.setResidents(handle, residents);
Model.execute(new DummyModelCommand());
}
public void setSources(Object handle, Collection specifications) {
super.setSources(handle, specifications);
Model.execute(new DummyModelCommand());
}
public void setSpecifications(Object handle, Collection specifications) {
super.setSpecifications(handle, specifications);
Model.execute(new DummyModelCommand());
}
public void setTaggedValue(Object handle, String tag, String value) {
super.setTaggedValue(handle, tag, value);
Model.execute(new DummyModelCommand());
}
public void setType(Object handle, Object type) {
super.setType(handle, type);
Model.execute(new DummyModelCommand());
}
}
| 25,764
|
Java
|
.java
| 634
| 31.287066
| 84
| 0.645409
|
kopl/misc
| 1
| 0
| 0
|
EPL-1.0
|
9/5/2024, 12:33:21 AM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| true
| true
| 25,764
|
576,459
|
WHttpManager.java
|
AppCanOpenSource_appcan-android/Engine/src/main/java/org/zywx/wbpalmstar/widgetone/dataservice/WHttpManager.java
|
/*
* Copyright (C) 2014 The AppCan Open Source Project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.zywx.wbpalmstar.widgetone.dataservice;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import org.zywx.wbpalmstar.base.ResoureFinder;
import org.zywx.wbpalmstar.engine.EBrowserActivity;
import org.zywx.wbpalmstar.engine.ESystemInfo;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Process;
import android.util.Xml;
public class WHttpManager {
private static final String F_WIDGETONE_REGIST_URL = "http://wgb.tx100.com/mobile/wg-reg.wg";
// http://wgb.3g2win.com/mobile/wg-reg.wg?ver=4030.1.01.439.00.00.9999.000&screenSize=320*240
private static final String F_WIDGET_REGIST_URL = "http://wgb.tx100.com/mobile/soft-reg.wg";
private static final String F_WIDGET_REPORT_URL = "http://wgb.tx100.com/mobile/soft-startup-report.wg";
private static final String F_WIDGETONE_RE_XML_TAGNAME_WIDGETONEID = "widgetOneId";
private static final String F_WIDGET_RE_XML_TAGNAME_WIDGETID = "widgetId";
private static final String F_WIDGET_RE_XML_TAGNAME_FILENAME = "updateFileName";
private static final String F_WIDGET_RE_XML_TAGNAME_FILEURL = "updateFileUrl";
private static final String F_WIDGET_RE_XML_TAGNAME_FILESIZE = "fileSize";
private static final String F_WIDGET_RE_XML_TAGNAME_VERSION = "version";
private static final String F_WIDGET_RE_XML_TAGNAME_MYSPACESTATUS = "mySpaceStatus";
private static final String F_WIDGET_RE_XML_TAGNAME_MYSPACEMOREAPP = "mySpaceMoreApp";
private static final String F_WIDGET_RE_XML_TAGNAME_WIDGETSTATUS = "widgetStatus";
private static final String F_WIDGET_RE_XML_TAGNAME_WIDGETADSTATUS = "widgetAdStatus";
private static final String F_WIDGET_RE_XML_TAGNAME_ERRORCODE = "errorCode";
private static final String F_WIDGET_ERRORCODE_APPID = "9998";
// private static final String ERROR_RES_XML_TAGNAME = "errorCode";
private static final int F_PARSE_XML_TYPE_WIDGETONEID = 0;
private static final int F_PARSE_XML_TYPE_WIDGETID = 1;
private static final int F_PARSE_XML_TYPE_WIDGET_UPDATE = 2;
private static final int F_PARSE_XML_TYPE_WIDGET_REPORT = 3;
private static final int F_PARSE_XML_TYPE_SERVER_ERROR = 4;
// private String widgetOneVer;
// private String screenSize;
// private String widgetOneId;
// private String appId;
// private String widgetVer;
// private String channelCode;
// private String imei;
// private String md5Code;
// private String widgetId;
/**
* WidgetOne 注册
*
* @param widgetOneVer widgetOne 版本号
* @param screenSize 手机屏幕大小(320×480)
*/
public static String widgetOneRegist(Context context, String widgetOneVer,
String screenSize, String imei) {
String url = F_WIDGETONE_REGIST_URL + "?ver=" + widgetOneVer
+ "&screenSize=" + screenSize + "&imei=" + imei;
ReData reData = getHttpReData(context, url,
F_PARSE_XML_TYPE_WIDGETONEID);
if (reData != null) {
return reData.widgetOneId;
}
return null;
}
/**
* Widget 注册
*
* @param widgetOneId 手机端WidgetOne系统的唯一标识
* @param appId 应用程序标识
* @param ver Widget版本号(String类型)
* @param channelCode 渠道号
* @param imei 手机IMEI号码
* @param md5Code 上传参数校验码
*/
public static String widgetRegist(Context context, String widgetOneId,
String appId, String ver, String channelCode, String imei,
String md5Code) {
String url = F_WIDGET_REGIST_URL + "?widgetOneId=" + widgetOneId
+ "&appId=" + appId + "&ver=" + ver + "&channelCode="
+ channelCode + "&imei=" + imei + "&md5Code=" + md5Code;
ReData reData = getHttpReData(context, url, F_PARSE_XML_TYPE_WIDGETID);
if (reData != null) {
return reData.widgetId;
}
return null;
}
/**
* Widget 更新
*
* @param widgetId 应用程序标识
* @param ver 版本号(String类型)
*/
public static ReData getUpdate(Context context, String updateurl,
String appId, String ver) {
String url = null;
if (updateurl.indexOf("?") == -1) {
url = updateurl + "?appId=" + appId + "&ver=" + ver + "&platform=1";
} else {
url = updateurl + "&appId=" + appId + "&ver=" + ver + "&platform=1";
}
ReData reData = getHttpReData(context, url,
F_PARSE_XML_TYPE_WIDGET_UPDATE);
return reData;
}
/**
* Widget 上报
*
* @param widgetId 应用程序标识
*/
public static ReData widgetReport(Context context, String widgetId) {
String url = F_WIDGET_REPORT_URL + "?widgetId=" + widgetId;
return getHttpReData(context, url, F_PARSE_XML_TYPE_WIDGET_REPORT);
}
private static ReData getHttpReData(Context context, String httpUrl,
int type) {
URL url = null;
HttpURLConnection httpconn = null;
InputStream is = null;
try {
url = new URL(httpUrl);
httpconn = (HttpURLConnection) url.openConnection();
httpconn.setConnectTimeout(90000);
httpconn.setReadTimeout(100000);
int responseCode = httpconn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
is = httpconn.getInputStream();
if (type == -1) {
return null;
}
// int size = httpconn.getContentLength();
// if(size == 0 || size == -1){
// return new ReData();
// }
return getHttpDataOfXML(context, is, type);
} else if (responseCode == 400) {
is = httpconn.getErrorStream();
return getHttpDataOfXML(context, is,
F_PARSE_XML_TYPE_SERVER_ERROR);
}
} catch (Exception e) {
if (is != null) {
try {
is.close();
is = null;
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
e.printStackTrace();
} finally {
if (httpconn != null) {
httpconn.disconnect();
httpconn = null;
}
if (is != null) {
try {
is.close();
is = null;
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
return null;
}
private static ReData getHttpDataOfXML(Context context, InputStream is,
int type) {
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(is, "utf-8");
ReData reData = null;
int tokenType = 0;
while (true) {
tokenType = parser.next();
switch (tokenType) {
case XmlPullParser.START_TAG:
switch (type) {
case F_PARSE_XML_TYPE_WIDGETONEID:
if (F_WIDGETONE_RE_XML_TAGNAME_WIDGETONEID
.equals(parser.getName())) {
reData = new ReData();
reData.widgetOneId = parser.nextText();
// return reData;
}
break;
case F_PARSE_XML_TYPE_WIDGETID:
if (F_WIDGET_RE_XML_TAGNAME_WIDGETID.equals(parser
.getName())) {
reData = new ReData();
reData.widgetId = parser.nextText();
// return reData;
}
break;
case F_PARSE_XML_TYPE_WIDGET_UPDATE:
if (F_WIDGET_RE_XML_TAGNAME_FILENAME.equals(parser
.getName())) {
reData = new ReData();
reData.fileName = parser.nextText();
} else if (F_WIDGET_RE_XML_TAGNAME_FILEURL
.equals(parser.getName())) {
reData.fileUrl = parser.nextText();
} else if (F_WIDGET_RE_XML_TAGNAME_FILESIZE
.equals(parser.getName())) {
String text = parser.nextText();
if (text != null && text.length() > 0) {
reData.fileSize = Integer.parseInt(text);
}
} else if (F_WIDGET_RE_XML_TAGNAME_VERSION
.equals(parser.getName())) {
reData.version = parser.nextText();
return reData;
}
break;
case F_PARSE_XML_TYPE_WIDGET_REPORT:
if (reData == null) {
reData = new ReData();
}
if (F_WIDGET_RE_XML_TAGNAME_MYSPACESTATUS.equals(parser
.getName())) {
String value = parser.nextText();
if ("000".equals(value)) {
reData.mySpaceStatus = WWidgetData.F_SPACESTATUS_CLOSE;
} else {
reData.mySpaceStatus = WWidgetData.F_SPACESTATUS_OPEN;
}
} else if (F_WIDGET_RE_XML_TAGNAME_WIDGETSTATUS
.equals(parser.getName())) {
String value = parser.nextText();
if ("000".equals(value)) {
showDialog(
context,
ResoureFinder.getInstance().getString(
context, "exit_message_server"));
}
} else if (F_WIDGET_RE_XML_TAGNAME_MYSPACEMOREAPP
.equals(parser.getName())) {
String value = parser.nextText();
if ("000".equals(value)) {
reData.mySpaceMoreApp = WWidgetData.F_MYSPACEMOREAPP_CLOSE;
} else {
reData.mySpaceMoreApp = WWidgetData.F_MYSPACEMOREAPP_OPEN;
}
} else if (F_WIDGET_RE_XML_TAGNAME_WIDGETADSTATUS
.equals(parser.getName())) {
String value = parser.nextText();
if ("000".equals(value)) {
reData.widgetAdStatus = WWidgetData.F_WIDGETADSTATUS_CLOSE;
} else {
reData.widgetAdStatus = WWidgetData.F_WIDGETADSTATUS_OPEN;
}
}
break;
case F_PARSE_XML_TYPE_SERVER_ERROR:
if (F_WIDGET_RE_XML_TAGNAME_ERRORCODE.equals(parser
.getName())) {
String value = parser.nextText();
if (F_WIDGET_ERRORCODE_APPID.equals(value)) {
showDialog(
context,
ResoureFinder.getInstance().getString(
context, "exit_message_appid"));
if (reData == null) {
reData = new ReData();
}
reData.widgetId = "-1";
}
}
break;
}
break;
case XmlPullParser.END_DOCUMENT:
return reData;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
if (F_PARSE_XML_TYPE_WIDGET_UPDATE == type) {
return new ReData();
}
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
is = null;
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
return null;
}
private static void showDialog(final Context context, final String message) {
if (ESystemInfo.getIntence().mIsDevelop) {
return;
}
if (context instanceof Activity) {
Activity uiThread = (Activity) context;
Runnable showDialog = new Runnable() {
@Override
public void run() {
Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton(
ResoureFinder.getInstance().getString(
context, "confirm"),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
dialog.dismiss();
Process.killProcess(Process.myUid());
}
}).show();
}
};
uiThread.runOnUiThread(showDialog);
}
}
// public static class ReData {
// public String widgetOneId;
// public String widgetId;
// public String fileName;
// public String fileUrl;
// public int fileSize;
// public String version;
// public int mySpaceStatus;
// public int mySpaceMoreApp;
// public int widgetAdStatus;
// // public String widgetStatus;
// // public int errorCode;
// }
}
| 16,721
|
Java
|
.java
| 352
| 28.684659
| 107
| 0.476765
|
AppCanOpenSource/appcan-android
| 144
| 130
| 10
|
LGPL-3.0
|
9/4/2024, 7:08:18 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 16,570
|
3,513,856
|
InBandBytestreamSession.java
|
ikantech_xmppsupport_v2/src/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSession.java
|
/**
* 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 org.jivesoftware.smackx.bytestreams.ibb;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.SyncPacketSend;
import org.jivesoftware.smackx.bytestreams.BytestreamSession;
import org.jivesoftware.smackx.bytestreams.ibb.packet.Close;
import org.jivesoftware.smackx.bytestreams.ibb.packet.Data;
import org.jivesoftware.smackx.bytestreams.ibb.packet.DataPacketExtension;
import org.jivesoftware.smackx.bytestreams.ibb.packet.Open;
/**
* InBandBytestreamSession class represents an In-Band Bytestream session.
* <p>
* In-band bytestreams are bidirectional and this session encapsulates the
* streams for both directions.
* <p>
* Note that closing the In-Band Bytestream session will close both streams. If
* both streams are closed individually the session will be closed automatically
* once the second stream is closed. Use the
* {@link #setCloseBothStreamsEnabled(boolean)} method if both streams should be
* closed automatically if one of them is closed.
*
* @author Henning Staib
*/
public class InBandBytestreamSession implements BytestreamSession {
/* XMPP connection */
private final Connection connection;
/* the In-Band Bytestream open request for this session */
private final Open byteStreamRequest;
/*
* the input stream for this session (either IQIBBInputStream or
* MessageIBBInputStream)
*/
private IBBInputStream inputStream;
/*
* the output stream for this session (either IQIBBOutputStream or
* MessageIBBOutputStream)
*/
private IBBOutputStream outputStream;
/* JID of the remote peer */
private String remoteJID;
/* flag to close both streams if one of them is closed */
private boolean closeBothStreamsEnabled = false;
/* flag to indicate if session is closed */
private boolean isClosed = false;
/**
* Constructor.
*
* @param connection
* the XMPP connection
* @param byteStreamRequest
* the In-Band Bytestream open request for this session
* @param remoteJID
* JID of the remote peer
*/
protected InBandBytestreamSession(Connection connection,
Open byteStreamRequest, String remoteJID) {
this.connection = connection;
this.byteStreamRequest = byteStreamRequest;
this.remoteJID = remoteJID;
// initialize streams dependent to the uses stanza type
switch (byteStreamRequest.getStanza()) {
case IQ:
this.inputStream = new IQIBBInputStream();
this.outputStream = new IQIBBOutputStream();
break;
case MESSAGE:
this.inputStream = new MessageIBBInputStream();
this.outputStream = new MessageIBBOutputStream();
break;
}
}
public InputStream getInputStream() {
return this.inputStream;
}
public OutputStream getOutputStream() {
return this.outputStream;
}
public int getReadTimeout() {
return this.inputStream.readTimeout;
}
public void setReadTimeout(int timeout) {
if (timeout < 0) {
throw new IllegalArgumentException("Timeout must be >= 0");
}
this.inputStream.readTimeout = timeout;
}
/**
* Returns whether both streams should be closed automatically if one of the
* streams is closed. Default is <code>false</code>.
*
* @return <code>true</code> if both streams will be closed if one of the
* streams is closed, <code>false</code> if both streams can be
* closed independently.
*/
public boolean isCloseBothStreamsEnabled() {
return closeBothStreamsEnabled;
}
/**
* Sets whether both streams should be closed automatically if one of the
* streams is closed. Default is <code>false</code>.
*
* @param closeBothStreamsEnabled
* <code>true</code> if both streams should be closed if one of
* the streams is closed, <code>false</code> if both streams
* should be closed independently
*/
public void setCloseBothStreamsEnabled(boolean closeBothStreamsEnabled) {
this.closeBothStreamsEnabled = closeBothStreamsEnabled;
}
public void close() throws IOException {
closeByLocal(true); // close input stream
closeByLocal(false); // close output stream
}
/**
* This method is invoked if a request to close the In-Band Bytestream has
* been received.
*
* @param closeRequest
* the close request from the remote peer
*/
protected void closeByPeer(Close closeRequest) {
/*
* close streams without flushing them, because stream is already
* considered closed on the remote peers side
*/
this.inputStream.closeInternal();
this.inputStream.cleanup();
this.outputStream.closeInternal(false);
// acknowledge close request
IQ confirmClose = IQ.createResultIQ(closeRequest);
this.connection.sendPacket(confirmClose);
}
/**
* This method is invoked if one of the streams has been closed locally, if
* an error occurred locally or if the whole session should be closed.
*
* @throws IOException
* if an error occurs while sending the close request
*/
protected synchronized void closeByLocal(boolean in) throws IOException {
if (this.isClosed) {
return;
}
if (this.closeBothStreamsEnabled) {
this.inputStream.closeInternal();
this.outputStream.closeInternal(true);
} else {
if (in) {
this.inputStream.closeInternal();
} else {
// close stream but try to send any data left
this.outputStream.closeInternal(true);
}
}
if (this.inputStream.isClosed && this.outputStream.isClosed) {
this.isClosed = true;
// send close request
Close close = new Close(this.byteStreamRequest.getSessionID());
close.setTo(this.remoteJID);
try {
SyncPacketSend.getReply(this.connection, close);
} catch (XMPPException e) {
throw new IOException("Error while closing stream: "
+ e.getMessage());
}
this.inputStream.cleanup();
// remove session from manager
InBandBytestreamManager.getByteStreamManager(this.connection)
.getSessions().remove(this);
}
}
/**
* IBBInputStream class is the base implementation of an In-Band Bytestream
* input stream. Subclasses of this input stream must provide a packet
* listener along with a packet filter to collect the In-Band Bytestream
* data packets.
*/
private abstract class IBBInputStream extends InputStream {
/* the data packet listener to fill the data queue */
private final PacketListener dataPacketListener;
/* queue containing received In-Band Bytestream data packets */
protected final BlockingQueue<DataPacketExtension> dataQueue = new LinkedBlockingQueue<DataPacketExtension>();
/* buffer containing the data from one data packet */
private byte[] buffer;
/* pointer to the next byte to read from buffer */
private int bufferPointer = -1;
/* data packet sequence (range from 0 to 65535) */
private long seq = -1;
/* flag to indicate if input stream is closed */
private boolean isClosed = false;
/* flag to indicate if close method was invoked */
private boolean closeInvoked = false;
/* timeout for read operations */
private int readTimeout = 0;
/**
* Constructor.
*/
public IBBInputStream() {
// add data packet listener to connection
this.dataPacketListener = getDataPacketListener();
connection.addPacketListener(this.dataPacketListener,
getDataPacketFilter());
}
/**
* Returns the packet listener that processes In-Band Bytestream data
* packets.
*
* @return the data packet listener
*/
protected abstract PacketListener getDataPacketListener();
/**
* Returns the packet filter that accepts In-Band Bytestream data
* packets.
*
* @return the data packet filter
*/
protected abstract PacketFilter getDataPacketFilter();
public synchronized int read() throws IOException {
checkClosed();
// if nothing read yet or whole buffer has been read fill buffer
if (bufferPointer == -1 || bufferPointer >= buffer.length) {
// if no data available and stream was closed return -1
if (!loadBuffer()) {
return -1;
}
}
// return byte and increment buffer pointer
return ((int) buffer[bufferPointer++]) & 0xff;
}
public synchronized int read(byte[] b, int off, int len)
throws IOException {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0)
|| ((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
checkClosed();
// if nothing read yet or whole buffer has been read fill buffer
if (bufferPointer == -1 || bufferPointer >= buffer.length) {
// if no data available and stream was closed return -1
if (!loadBuffer()) {
return -1;
}
}
// if more bytes wanted than available return all available
int bytesAvailable = buffer.length - bufferPointer;
if (len > bytesAvailable) {
len = bytesAvailable;
}
System.arraycopy(buffer, bufferPointer, b, off, len);
bufferPointer += len;
return len;
}
public synchronized int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
/**
* This method blocks until a data packet is received, the stream is
* closed or the current thread is interrupted.
*
* @return <code>true</code> if data was received, otherwise
* <code>false</code>
* @throws IOException
* if data packets are out of sequence
*/
private synchronized boolean loadBuffer() throws IOException {
// wait until data is available or stream is closed
DataPacketExtension data = null;
try {
if (this.readTimeout == 0) {
while (data == null) {
if (isClosed && this.dataQueue.isEmpty()) {
return false;
}
data = this.dataQueue.poll(1000, TimeUnit.MILLISECONDS);
}
} else {
data = this.dataQueue.poll(this.readTimeout,
TimeUnit.MILLISECONDS);
if (data == null) {
throw new SocketTimeoutException();
}
}
} catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
return false;
}
// handle sequence overflow
if (this.seq == 65535) {
this.seq = -1;
}
// check if data packets sequence is successor of last seen sequence
long seq = data.getSeq();
if (seq - 1 != this.seq) {
// packets out of order; close stream/session
InBandBytestreamSession.this.close();
throw new IOException("Packets out of sequence");
} else {
this.seq = seq;
}
// set buffer to decoded data
buffer = data.getDecodedData();
bufferPointer = 0;
return true;
}
/**
* Checks if this stream is closed and throws an IOException if
* necessary
*
* @throws IOException
* if stream is closed and no data should be read anymore
*/
private void checkClosed() throws IOException {
/*
* throw no exception if there is data available, but not if close
* method was invoked
*/
if ((isClosed && this.dataQueue.isEmpty()) || closeInvoked) {
// clear data queue in case additional data was received after
// stream was closed
this.dataQueue.clear();
throw new IOException("Stream is closed");
}
}
public boolean markSupported() {
return false;
}
public void close() throws IOException {
if (isClosed) {
return;
}
this.closeInvoked = true;
InBandBytestreamSession.this.closeByLocal(true);
}
/**
* This method sets the close flag and removes the data packet listener.
*/
private void closeInternal() {
if (isClosed) {
return;
}
isClosed = true;
}
/**
* Invoked if the session is closed.
*/
private void cleanup() {
connection.removePacketListener(this.dataPacketListener);
}
}
/**
* IQIBBInputStream class implements IBBInputStream to be used with IQ
* stanzas encapsulating the data packets.
*/
private class IQIBBInputStream extends IBBInputStream {
protected PacketListener getDataPacketListener() {
return new PacketListener() {
private long lastSequence = -1;
public void processPacket(Packet packet) {
// get data packet extension
DataPacketExtension data = (DataPacketExtension) packet
.getExtension(DataPacketExtension.ELEMENT_NAME,
InBandBytestreamManager.NAMESPACE);
/*
* check if sequence was not used already (see XEP-0047
* Section 2.2)
*/
if (data.getSeq() <= this.lastSequence) {
IQ unexpectedRequest = IQ
.createErrorResponse(
(IQ) packet,
new XMPPError(
XMPPError.Condition.unexpected_request));
connection.sendPacket(unexpectedRequest);
return;
}
// check if encoded data is valid (see XEP-0047 Section 2.2)
if (data.getDecodedData() == null) {
// data is invalid; respond with bad-request error
IQ badRequest = IQ.createErrorResponse((IQ) packet,
new XMPPError(XMPPError.Condition.bad_request));
connection.sendPacket(badRequest);
return;
}
// data is valid; add to data queue
dataQueue.offer(data);
// confirm IQ
IQ confirmData = IQ.createResultIQ((IQ) packet);
connection.sendPacket(confirmData);
// set last seen sequence
this.lastSequence = data.getSeq();
if (this.lastSequence == 65535) {
this.lastSequence = -1;
}
}
};
}
protected PacketFilter getDataPacketFilter() {
/*
* filter all IQ stanzas having type 'SET' (represented by Data
* class), containing a data packet extension, matching session ID
* and recipient
*/
return new AndFilter(new PacketTypeFilter(Data.class),
new IBBDataPacketFilter());
}
}
/**
* MessageIBBInputStream class implements IBBInputStream to be used with
* message stanzas encapsulating the data packets.
*/
private class MessageIBBInputStream extends IBBInputStream {
protected PacketListener getDataPacketListener() {
return new PacketListener() {
public void processPacket(Packet packet) {
// get data packet extension
DataPacketExtension data = (DataPacketExtension) packet
.getExtension(DataPacketExtension.ELEMENT_NAME,
InBandBytestreamManager.NAMESPACE);
// check if encoded data is valid
if (data.getDecodedData() == null) {
/*
* TODO once a majority of XMPP server implementation
* support XEP-0079 Advanced Message Processing the
* invalid message could be answered with an appropriate
* error. For now we just ignore the packet. Subsequent
* packets with an increased sequence will cause the
* input stream to close the stream/session.
*/
return;
}
// data is valid; add to data queue
dataQueue.offer(data);
// TODO confirm packet once XMPP servers support XEP-0079
}
};
}
@Override
protected PacketFilter getDataPacketFilter() {
/*
* filter all message stanzas containing a data packet extension,
* matching session ID and recipient
*/
return new AndFilter(new PacketTypeFilter(Message.class),
new IBBDataPacketFilter());
}
}
/**
* IBBDataPacketFilter class filters all packets from the remote peer of
* this session, containing an In-Band Bytestream data packet extension
* whose session ID matches this sessions ID.
*/
private class IBBDataPacketFilter implements PacketFilter {
public boolean accept(Packet packet) {
// sender equals remote peer
if (!packet.getFrom().equalsIgnoreCase(remoteJID)) {
return false;
}
// stanza contains data packet extension
PacketExtension packetExtension = packet.getExtension(
DataPacketExtension.ELEMENT_NAME,
InBandBytestreamManager.NAMESPACE);
if (packetExtension == null
|| !(packetExtension instanceof DataPacketExtension)) {
return false;
}
// session ID equals this session ID
DataPacketExtension data = (DataPacketExtension) packetExtension;
if (!data.getSessionID().equals(byteStreamRequest.getSessionID())) {
return false;
}
return true;
}
}
/**
* IBBOutputStream class is the base implementation of an In-Band Bytestream
* output stream. Subclasses of this output stream must provide a method to
* send data over XMPP stream.
*/
private abstract class IBBOutputStream extends OutputStream {
/* buffer with the size of this sessions block size */
protected final byte[] buffer;
/* pointer to next byte to write to buffer */
protected int bufferPointer = 0;
/* data packet sequence (range from 0 to 65535) */
protected long seq = 0;
/* flag to indicate if output stream is closed */
protected boolean isClosed = false;
/**
* Constructor.
*/
public IBBOutputStream() {
this.buffer = new byte[(byteStreamRequest.getBlockSize() / 4) * 3];
}
/**
* Writes the given data packet to the XMPP stream.
*
* @param data
* the data packet
* @throws IOException
* if an I/O error occurred while sending or if the stream
* is closed
*/
protected abstract void writeToXML(DataPacketExtension data)
throws IOException;
public synchronized void write(int b) throws IOException {
if (this.isClosed) {
throw new IOException("Stream is closed");
}
// if buffer is full flush buffer
if (bufferPointer >= buffer.length) {
flushBuffer();
}
buffer[bufferPointer++] = (byte) b;
}
public synchronized void write(byte b[], int off, int len)
throws IOException {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0)
|| ((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
if (this.isClosed) {
throw new IOException("Stream is closed");
}
// is data to send greater than buffer size
if (len >= buffer.length) {
// "byte" off the first chunk to write out
writeOut(b, off, buffer.length);
// recursively call this method with the lesser amount
write(b, off + buffer.length, len - buffer.length);
} else {
writeOut(b, off, len);
}
}
public synchronized void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
/**
* Fills the buffer with the given data and sends it over the XMPP
* stream if the buffers capacity has been reached. This method is only
* called from this class so it is assured that the amount of data to
* send is <= buffer capacity
*
* @param b
* the data
* @param off
* the data
* @param len
* the number of bytes to write
* @throws IOException
* if an I/O error occurred while sending or if the stream
* is closed
*/
private synchronized void writeOut(byte b[], int off, int len)
throws IOException {
if (this.isClosed) {
throw new IOException("Stream is closed");
}
// set to 0 in case the next 'if' block is not executed
int available = 0;
// is data to send greater that buffer space left
if (len > buffer.length - bufferPointer) {
// fill buffer to capacity and send it
available = buffer.length - bufferPointer;
System.arraycopy(b, off, buffer, bufferPointer, available);
bufferPointer += available;
flushBuffer();
}
// copy the data left to buffer
System.arraycopy(b, off + available, buffer, bufferPointer, len
- available);
bufferPointer += len - available;
}
public synchronized void flush() throws IOException {
if (this.isClosed) {
throw new IOException("Stream is closed");
}
flushBuffer();
}
private synchronized void flushBuffer() throws IOException {
// do nothing if no data to send available
if (bufferPointer == 0) {
return;
}
// create data packet
String enc = StringUtils.encodeBase64(buffer, 0, bufferPointer,
false);
DataPacketExtension data = new DataPacketExtension(
byteStreamRequest.getSessionID(), this.seq, enc);
// write to XMPP stream
writeToXML(data);
// reset buffer pointer
bufferPointer = 0;
// increment sequence, considering sequence overflow
this.seq = (this.seq + 1 == 65535 ? 0 : this.seq + 1);
}
public void close() throws IOException {
if (isClosed) {
return;
}
InBandBytestreamSession.this.closeByLocal(false);
}
/**
* Sets the close flag and optionally flushes the stream.
*
* @param flush
* if <code>true</code> flushes the stream
*/
protected void closeInternal(boolean flush) {
if (this.isClosed) {
return;
}
this.isClosed = true;
try {
if (flush) {
flushBuffer();
}
} catch (IOException e) {
/*
* ignore, because writeToXML() will not throw an exception if
* stream is already closed
*/
}
}
}
/**
* IQIBBOutputStream class implements IBBOutputStream to be used with IQ
* stanzas encapsulating the data packets.
*/
private class IQIBBOutputStream extends IBBOutputStream {
@Override
protected synchronized void writeToXML(DataPacketExtension data)
throws IOException {
// create IQ stanza containing data packet
IQ iq = new Data(data);
iq.setTo(remoteJID);
try {
SyncPacketSend.getReply(connection, iq);
} catch (XMPPException e) {
// close session unless it is already closed
if (!this.isClosed) {
InBandBytestreamSession.this.close();
throw new IOException("Error while sending Data: "
+ e.getMessage());
}
}
}
}
/**
* MessageIBBOutputStream class implements IBBOutputStream to be used with
* message stanzas encapsulating the data packets.
*/
private class MessageIBBOutputStream extends IBBOutputStream {
@Override
protected synchronized void writeToXML(DataPacketExtension data) {
// create message stanza containing data packet
Message message = new Message(remoteJID);
message.addExtension(data);
connection.sendPacket(message);
}
}
}
| 24,235
|
Java
|
.java
| 700
| 29.385714
| 113
| 0.690211
|
ikantech/xmppsupport_v2
| 3
| 16
| 0
|
GPL-2.0
|
9/4/2024, 11:30:47 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 24,235
|
3,081,355
|
Employee.java
|
taylorswift58037_WIPRO-PJP/Collection/Mini Projects/Manage Employee Details/Employee.java
|
public class Employee implements Comparable<Employee> {
private String firstName;
private String lastName;
private long mobileNumber;
private String emailId;
private String address;
public Employee() {
super();
}
public Employee(String firstName, String lastName, long mobileNumber, String emailId, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.mobileNumber = mobileNumber;
this.emailId = emailId;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public long getMobileNumber() {
return mobileNumber;
}
public String getEmailId() {
return emailId;
}
public String getAddress() {
return address;
}
@Override
public String toString() {
return "Employee [firstName=" + firstName + ", lastName=" + lastName + ", mobileNumber=" + mobileNumber
+ ", emailId=" + emailId + ", address=" + address + "]";
}
@Override
public int compareTo(Employee emp) {
return this.firstName.compareTo(emp.getFirstName()) * -1;
}
}
| 1,094
|
Java
|
.java
| 42
| 23.333333
| 105
| 0.736538
|
taylorswift58037/WIPRO-PJP
| 5
| 0
| 0
|
GPL-3.0
|
9/4/2024, 10:46:59 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 1,094
|
47,674
|
JSONTokener.java
|
fossasia_susi_server/src/org/json/JSONTokener.java
|
package org.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
/*
Copyright (c) 2002 JSON.org
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 shall be used for Good, not Evil.
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.
*/
/**
* A JSONTokener takes a source string and extracts characters and tokens from
* it. It is used by the JSONObject and JSONArray constructors to parse
* JSON source strings.
* @author JSON.org
* @version 2014-05-03
*/
public class JSONTokener {
/** current read character position on the current line. */
private long character;
/** flag to indicate if the end of the input has been found. */
private boolean eof;
/** current read index of the input. */
private long index;
/** current line of the input. */
private long line;
/** previous character read from the input. */
private char previous;
/** Reader for the input. */
private final Reader reader;
/** flag to indicate that a previous character was requested. */
private boolean usePrevious;
/** the number of characters read in the previous line. */
private long characterPreviousLine;
/**
* Construct a JSONTokener from a Reader. The caller must close the Reader.
*
* @param reader A reader.
*/
public JSONTokener(Reader reader) {
this.reader = reader.markSupported()
? reader
: new BufferedReader(reader);
this.eof = false;
this.usePrevious = false;
this.previous = 0;
this.index = 0;
this.character = 1;
this.characterPreviousLine = 0;
this.line = 1;
}
/**
* Construct a JSONTokener from an InputStream. The caller must close the input stream.
* @param inputStream The source.
*/
public JSONTokener(InputStream inputStream) {
this(new InputStreamReader(inputStream));
}
/**
* Construct a JSONTokener from a string.
*
* @param s A source string.
*/
public JSONTokener(String s) {
this(new StringReader(s));
}
/**
* Back up one character. This provides a sort of lookahead capability,
* so that you can test for a digit or letter before attempting to parse
* the next number or identifier.
* @throws JSONException Thrown if trying to step back more than 1 step
* or if already at the start of the string
*/
public void back() throws JSONException {
if (this.usePrevious || this.index <= 0) {
throw new JSONException("Stepping back two steps is not supported");
}
this.decrementIndexes();
this.usePrevious = true;
this.eof = false;
}
/**
* Decrements the indexes for the {@link #back()} method based on the previous character read.
*/
private void decrementIndexes() {
this.index--;
if(this.previous=='\r' || this.previous == '\n') {
this.line--;
this.character=this.characterPreviousLine ;
} else if(this.character > 0){
this.character--;
}
}
/**
* Get the hex value of a character (base16).
* @param c A character between '0' and '9' or between 'A' and 'F' or
* between 'a' and 'f'.
* @return An int between 0 and 15, or -1 if c was not a hex digit.
*/
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
}
/**
* Checks if the end of the input has been reached.
*
* @return true if at the end of the file and we didn't step back
*/
public boolean end() {
return this.eof && !this.usePrevious;
}
/**
* Determine if the source string still contains characters that next()
* can consume.
* @return true if not yet at the end of the source.
* @throws JSONException thrown if there is an error stepping forward
* or backward while checking for more data.
*/
public boolean more() throws JSONException {
if(this.usePrevious) {
return true;
}
try {
this.reader.mark(1);
} catch (IOException e) {
throw new JSONException("Unable to preserve stream position", e);
}
try {
// -1 is EOF, but next() can not consume the null character '\0'
if(this.reader.read() <= 0) {
this.eof = true;
return false;
}
this.reader.reset();
} catch (IOException e) {
throw new JSONException("Unable to read the next character from the stream", e);
}
return true;
}
/**
* Get the next character in the source string.
*
* @return The next character, or 0 if past the end of the source string.
* @throws JSONException Thrown if there is an error reading the source string.
*/
public char next() throws JSONException {
int c;
if (this.usePrevious) {
this.usePrevious = false;
c = this.previous;
} else {
try {
c = this.reader.read();
} catch (IOException exception) {
throw new JSONException(exception);
}
}
if (c <= 0) { // End of stream
this.eof = true;
return 0;
}
this.incrementIndexes(c);
this.previous = (char) c;
return this.previous;
}
/**
* Increments the internal indexes according to the previous character
* read and the character passed as the current character.
* @param c the current character read.
*/
private void incrementIndexes(int c) {
if(c > 0) {
this.index++;
if(c=='\r') {
this.line++;
this.characterPreviousLine = this.character;
this.character=0;
}else if (c=='\n') {
if(this.previous != '\r') {
this.line++;
this.characterPreviousLine = this.character;
}
this.character=0;
} else {
this.character++;
}
}
}
/**
* Consume the next character, and check that it matches a specified
* character.
* @param c The character to match.
* @return The character.
* @throws JSONException if the character does not match.
*/
public char next(char c) throws JSONException {
char n = this.next();
if (n != c) {
if(n > 0) {
throw this.syntaxError("Expected '" + c + "' and instead saw '" +
n + "'");
}
throw this.syntaxError("Expected '" + c + "' and instead saw ''");
}
return n;
}
/**
* Get the next n characters.
*
* @param n The number of characters to take.
* @return A string of n characters.
* @throws JSONException
* Substring bounds error if there are not
* n characters remaining in the source string.
*/
public String next(int n) throws JSONException {
if (n == 0) {
return "";
}
char[] chars = new char[n];
int pos = 0;
while (pos < n) {
chars[pos] = this.next();
if (this.end()) {
throw this.syntaxError("Substring bounds error");
}
pos += 1;
}
return new String(chars);
}
/**
* Get the next char in the string, skipping whitespace.
* @throws JSONException Thrown if there is an error reading the source string.
* @return A character, or 0 if there are no more characters.
*/
public char nextClean() throws JSONException {
for (;;) {
char c = this.next();
if (c == 0 || c > ' ') {
return c;
}
}
}
/**
* Return the characters up to the next close quote character.
* Backslash processing is done. The formal JSON format does not
* allow strings in single quotes, but an implementation is allowed to
* accept them.
* @param quote The quoting character, either
* <code>"</code> <small>(double quote)</small> or
* <code>'</code> <small>(single quote)</small>.
* @return A String.
* @throws JSONException Unterminated string.
*/
public String nextString(char quote) throws JSONException {
char c;
StringBuilder sb = new StringBuilder();
for (;;) {
c = this.next();
switch (c) {
case 0:
case '\n':
case '\r':
throw this.syntaxError("Unterminated string");
case '\\':
c = this.next();
switch (c) {
case 'b':
sb.append('\b');
break;
case 't':
sb.append('\t');
break;
case 'n':
sb.append('\n');
break;
case 'f':
sb.append('\f');
break;
case 'r':
sb.append('\r');
break;
case 'u':
try {
sb.append((char)Integer.parseInt(this.next(4), 16));
} catch (NumberFormatException e) {
throw this.syntaxError("Illegal escape.", e);
}
break;
case '"':
case '\'':
case '\\':
case '/':
sb.append(c);
break;
default:
throw this.syntaxError("Illegal escape.");
}
break;
default:
if (c == quote) {
return sb.toString();
}
sb.append(c);
}
}
}
/**
* Get the text up but not including the specified character or the
* end of line, whichever comes first.
* @param delimiter A delimiter character.
* @return A string.
* @throws JSONException Thrown if there is an error while searching
* for the delimiter
*/
public String nextTo(char delimiter) throws JSONException {
StringBuilder sb = new StringBuilder();
for (;;) {
char c = this.next();
if (c == delimiter || c == 0 || c == '\n' || c == '\r') {
if (c != 0) {
this.back();
}
return sb.toString().trim();
}
sb.append(c);
}
}
/**
* Get the text up but not including one of the specified delimiter
* characters or the end of line, whichever comes first.
* @param delimiters A set of delimiter characters.
* @return A string, trimmed.
* @throws JSONException Thrown if there is an error while searching
* for the delimiter
*/
public String nextTo(String delimiters) throws JSONException {
char c;
StringBuilder sb = new StringBuilder();
for (;;) {
c = this.next();
if (delimiters.indexOf(c) >= 0 || c == 0 ||
c == '\n' || c == '\r') {
if (c != 0) {
this.back();
}
return sb.toString().trim();
}
sb.append(c);
}
}
/**
* Get the next value. The value can be a Boolean, Double, Integer,
* JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
* @throws JSONException If syntax error.
*
* @return An object.
*/
public Object nextValue() throws JSONException {
char c = this.nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
case '{':
this.back();
return new JSONObject(this);
case '[':
this.back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuilder sb = new StringBuilder();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = this.next();
}
if (!this.eof) {
this.back();
}
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
}
/**
* Skip characters until the next character is the requested character.
* If the requested character is not found, no characters are skipped.
* @param to A character to skip to.
* @return The requested character, or zero if the requested character
* is not found.
* @throws JSONException Thrown if there is an error while searching
* for the to character
*/
public char skipTo(char to) throws JSONException {
char c;
try {
long startIndex = this.index;
long startCharacter = this.character;
long startLine = this.line;
this.reader.mark(1000000);
do {
c = this.next();
if (c == 0) {
// in some readers, reset() may throw an exception if
// the remaining portion of the input is greater than
// the mark size (1,000,000 above).
this.reader.reset();
this.index = startIndex;
this.character = startCharacter;
this.line = startLine;
return 0;
}
} while (c != to);
this.reader.mark(1);
} catch (IOException exception) {
throw new JSONException(exception);
}
this.back();
return c;
}
/**
* Make a JSONException to signal a syntax error.
*
* @param message The error message.
* @return A JSONException object, suitable for throwing
*/
public JSONException syntaxError(String message) {
return new JSONException(message + this.toString());
}
/**
* Make a JSONException to signal a syntax error.
*
* @param message The error message.
* @param causedBy The throwable that caused the error.
* @return A JSONException object, suitable for throwing
*/
public JSONException syntaxError(String message, Throwable causedBy) {
return new JSONException(message + this.toString(), causedBy);
}
/**
* Make a printable string of this JSONTokener.
*
* @return " at {index} [character {character} line {line}]"
*/
@Override
public String toString() {
return " at " + this.index + " [character " + this.character + " line " +
this.line + "]";
}
}
| 16,719
|
Java
|
.java
| 484
| 25.144628
| 98
| 0.54979
|
fossasia/susi_server
| 2,500
| 1,073
| 55
|
LGPL-2.1
|
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 16,719
|
3,808,667
|
SimpleHTMLTokenizer.java
|
divestedcg_Bayebot/src/net/sf/classifier4J/SimpleHTMLTokenizer.java
|
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2003 Nick Lothian. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* developers of Classifier4J (http://classifier4j.sf.net/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The name "Classifier4J" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* http://sourceforge.net/users/nicklothian/.
*
* 5. Products derived from this software may not be called
* "Classifier4J", nor may "Classifier4J" appear in their names
* without prior written permission. For written permission, please
* contact http://sourceforge.net/users/nicklothian/.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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 net.sf.classifier4J;
import java.util.Stack;
/**
* <p>Simple HTML Tokenizer. Its goal is to tokenize words that would be displayed
* in a normal web browser.</p>
*
* <p>It does not handle meta tags, alt or text attributes, but it does remove
* CSS style definitions and javascript code.</p>
*
* <p>It handles entity references by replacing them with a space(!!). This can be
* overridden.</p>
*
* @author Nick Lothian
* @since 18 Nov 2003
*/
public class SimpleHTMLTokenizer extends DefaultTokenizer {
/**
* Constructor that using the BREAK_ON_WORD_BREAKS tokenizer config by default
*/
public SimpleHTMLTokenizer() {
super();
}
public SimpleHTMLTokenizer(int tokenizerConfig) {
super(tokenizerConfig);
}
public SimpleHTMLTokenizer(String regularExpression) {
super(regularExpression);
}
/**
* Replaces entity references with spaces
*
* @param contentsWithUnresolvedEntityReferences the contents with the entity references
* @return the contents with the entities replaces with spaces
*/
protected String resolveEntities(String contentsWithUnresolvedEntityReferences) {
if (contentsWithUnresolvedEntityReferences == null) {
throw new IllegalArgumentException("Cannot pass null");
}
return contentsWithUnresolvedEntityReferences.replaceAll("&.{2,8};", " ");
}
/**
* @see net.sf.classifier4J.ITokenizer#tokenize(java.lang.String)
*/
public String[] tokenize(String input) {
Stack stack = new Stack();
Stack tagStack = new Stack();
// iterate over the input string and parse find text that would be displayed
char[] chars = input.toCharArray();
StringBuffer result = new StringBuffer();
StringBuffer currentTagName = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
switch (chars[i]) {
case '<':
stack.push(Boolean.TRUE);
currentTagName = new StringBuffer();
break;
case '>':
stack.pop();
if (currentTagName != null) {
String currentTag = currentTagName.toString();
if (currentTag.startsWith("/")) {
tagStack.pop();
} else {
tagStack.push(currentTag.toLowerCase());
}
}
break;
default:
if (stack.size() == 0) {
String currentTag = (String) tagStack.peek();
// ignore everything inside <script></script> or <style></style> tags
if (currentTag != null) {
if (!(currentTag.startsWith("script") || currentTag.startsWith("style"))) {
result.append(chars[i]);
}
} else {
result.append(chars[i]);
}
} else {
currentTagName.append(chars[i]);
}
break;
}
}
return super.tokenize(resolveEntities(result.toString()).trim());
}
}
| 5,852
|
Java
|
.java
| 137
| 34.328467
| 103
| 0.619449
|
divestedcg/Bayebot
| 3
| 2
| 0
|
AGPL-3.0
|
9/4/2024, 11:43:31 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 5,852
|
3,881,893
|
ModelAdapterWitherSkull.java
|
llyxa05_ZeUsClient-1_12_2/net/optifine/entity/model/ModelAdapterWitherSkull.java
|
package net.optifine.entity.model;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.model.ModelSkeletonHead;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.entity.RenderWitherSkull;
import net.minecraft.entity.projectile.EntityWitherSkull;
import optifine.Config;
import optifine.Reflector;
public class ModelAdapterWitherSkull extends ModelAdapter
{
public ModelAdapterWitherSkull()
{
super(EntityWitherSkull.class, "wither_skull", 0.0F);
}
public ModelBase makeModel()
{
return new ModelSkeletonHead();
}
public ModelRenderer getModelRenderer(ModelBase model, String modelPart)
{
if (!(model instanceof ModelSkeletonHead))
{
return null;
}
else
{
ModelSkeletonHead modelskeletonhead = (ModelSkeletonHead)model;
return modelPart.equals("head") ? modelskeletonhead.skeletonHead : null;
}
}
public IEntityRenderer makeEntityRender(ModelBase modelBase, float shadowSize)
{
RenderManager rendermanager = Minecraft.getMinecraft().getRenderManager();
RenderWitherSkull renderwitherskull = new RenderWitherSkull(rendermanager);
if (!Reflector.RenderWitherSkull_model.exists())
{
Config.warn("Field not found: RenderWitherSkull_model");
return null;
}
else
{
Reflector.setFieldValue(renderwitherskull, Reflector.RenderWitherSkull_model, modelBase);
renderwitherskull.shadowSize = shadowSize;
return renderwitherskull;
}
}
}
| 1,756
|
Java
|
.java
| 49
| 29.163265
| 101
| 0.719577
|
llyxa05/ZeUsClient-1.12.2
| 3
| 0
| 0
|
GPL-3.0
|
9/4/2024, 11:46:40 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 1,756
|
2,918,818
|
CreatedMessagesReport.java
|
barun-saha_one-simulator/one_1.5.1-RC2/report/CreatedMessagesReport.java
|
/*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package report;
import core.DTNHost;
import core.Message;
import core.MessageListener;
/**
* Reports information about all created messages. Messages created during
* the warm up period are ignored.
* For output syntax, see {@link #HEADER}.
*/
public class CreatedMessagesReport extends Report implements MessageListener {
public static String HEADER = "# time ID size fromHost toHost TTL " +
"isResponse";
/**
* Constructor.
*/
public CreatedMessagesReport() {
init();
}
@Override
public void init() {
super.init();
write(HEADER);
}
public void newMessage(Message m) {
if (isWarmup()) {
return;
}
int ttl = m.getTtl();
write(format(getSimTime()) + " " + m.getId() + " " +
m.getSize() + " " + m.getFrom() + " " + m.getTo() + " " +
(ttl != Integer.MAX_VALUE ? ttl : "n/a") +
(m.isResponse() ? " Y " : " N "));
}
// nothing to implement for the rest
public void messageTransferred(Message m, DTNHost f, DTNHost t,boolean b) {}
public void messageDeleted(Message m, DTNHost where, boolean dropped) {}
public void messageTransferAborted(Message m, DTNHost from, DTNHost to) {}
public void messageTransferStarted(Message m, DTNHost from, DTNHost to) {}
@Override
public void done() {
super.done();
}
}
| 1,419
|
Java
|
.java
| 47
| 26.744681
| 79
| 0.677014
|
barun-saha/one-simulator
| 5
| 3
| 0
|
GPL-3.0
|
9/4/2024, 10:35:02 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 1,419
|
2,527,418
|
DisableOpenInventoryListener.java
|
AzisabaNetwork_LeonGunWar/src/main/java/net/azisaba/lgw/core/listeners/others/DisableOpenInventoryListener.java
|
package net.azisaba.lgw.core.listeners.others;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryType;
// 金床とかまどを開けれないようにするリスナー
public class DisableOpenInventoryListener implements Listener {
@EventHandler
public void onInventoryOpen(InventoryOpenEvent e) {
Player p = (Player) e.getPlayer();
if (e.getInventory().getType() == InventoryType.ANVIL) {
// 金床だった場合はキャンセル
e.setCancelled(true);
// 音を鳴らす
p.playSound(p.getLocation(), Sound.ENTITY_VILLAGER_NO, 1, 1);
}
if (e.getInventory().getType() == InventoryType.FURNACE) {
// かまどならキャンセル
e.setCancelled(true);
// 音を鳴らす
p.playSound(p.getLocation(), Sound.ENTITY_VILLAGER_NO, 1, 1);
}
}
}
| 1,000
|
Java
|
.java
| 26
| 30.192308
| 67
| 0.734575
|
AzisabaNetwork/LeonGunWar
| 7
| 3
| 9
|
GPL-3.0
|
9/4/2024, 9:46:18 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 892
|
4,731,140
|
MultiSessionProfileProvider.java
|
beangle_beanfuse/beanfuse-security/beanfuse-security-core/src/main/java/org/beanfuse/security/dao/MultiSessionProfileProvider.java
|
package org.beanfuse.security.dao;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.beanfuse.persist.hibernate.BaseDaoHibernate;
import org.beanfuse.security.UserCategory;
import org.beanfuse.security.online.CategoryProfile;
import org.beanfuse.security.online.SessionProfile;
public class MultiSessionProfileProvider extends BaseDaoHibernate implements SessionProfileProvider {
private Long sessionProfileId;
public List getProfiles() {
List profiles = entityDao.loadAll(CategoryProfile.class);
for (Iterator iterator = profiles.iterator(); iterator.hasNext();) {
CategoryProfile profile = (CategoryProfile) iterator.next();
profile.setCategory((UserCategory) entityDao.get(UserCategory.class, profile
.getCategory().getId()));
}
return profiles;
}
public SessionProfile getProfile() {
// read min(id) as needed
if (null == sessionProfileId) {
List profileIds = entityDao.searchHQLQuery("select min(id) from "
+ SessionProfile.class.getName());
if (profileIds.isEmpty()) {
return null;
} else {
sessionProfileId = (Long) profileIds.get(0);
}
}
SessionProfile profile = (SessionProfile) entityDao.get(SessionProfile.class,
sessionProfileId);
List<CategoryProfile> categoryProfiles = entityDao.searchHQLQuery("from CategoryProfile");
// initialize profile.categoryprofiles
Map newCategoryProfiles=new HashMap();
for (Iterator iterator = categoryProfiles.iterator(); iterator.hasNext();) {
CategoryProfile cp = (CategoryProfile) iterator.next();
Long categoryId=cp.getCategory().getId();
cp.setCategory((UserCategory) entityDao.get(UserCategory.class, categoryId));
newCategoryProfiles.put(categoryId, cp);
}
profile.setCategoryProfiles(newCategoryProfiles);
return profile;
}
public Long getSessionProfileId() {
return sessionProfileId;
}
public void setSessionProfileId(Long sessionProfileId) {
this.sessionProfileId = sessionProfileId;
}
}
| 2,005
|
Java
|
.java
| 52
| 35.557692
| 101
| 0.788066
|
beangle/beanfuse
| 1
| 2
| 0
|
LGPL-3.0
|
9/5/2024, 12:28:11 AM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 2,005
|
953,512
|
DataCleaner.java
|
Jude95_Fishing/app/src/main/java/com/jude/fishing/utils/DataCleaner.java
|
package com.jude.fishing.utils;
import android.content.Context;
import com.jude.fishing.model.db.DBHelper;
import com.jude.fishing.model.db.PlaceDBTable;
import com.jude.utils.JFileManager;
import com.jude.utils.JUtils;
import com.squareup.sqlbrite.SqlBrite;
/**
* Created by Mr.Jude on 2015/9/4.
*/
public class DataCleaner {
public static void Update(Context ctx,int version){
int versionOld = JUtils.getSharedPreference().getInt("data_version",0);
if (version>versionOld){
Clean(ctx);
JUtils.getSharedPreference().edit().putInt("data_version", version).apply();
}
}
public static void Clean(Context ctx){
JUtils.getSharedPreference().edit().clear().apply();
JFileManager.getInstance().clearAllData();
SqlBrite.create().wrapDatabaseHelper(new DBHelper(ctx)).delete(PlaceDBTable.TABLE_NAME,"");
}
}
| 894
|
Java
|
.java
| 24
| 32.333333
| 99
| 0.715935
|
Jude95/Fishing
| 57
| 26
| 2
|
GPL-3.0
|
9/4/2024, 7:10:21 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 894
|
3,639,999
|
DwVec2.java
|
kefik_Pogamut3/Utils/SpacePartitioning/src/DwMath/DwVec2.java
|
/**
*
* author: (c)thomas diewald, http://thomasdiewald.com/
* date: 23.04.2012
*
*
* This source 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 2 of the License, or
* (at your option) any later version.
*
* 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 for more details.
*
* A copy of the GNU General Public License is available on the World
* Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also
* obtain it by writing to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package DwMath;
import java.util.Locale;
public class DwVec2 {
public static float[] nullvector() {
return new float[]{0, 0};
}
public static void copy_ref(float[]a, float[]dst) {
dst[0] = a[0];
dst[1] = a[1];
};
public static float[] copy_new(float[]a) {
return new float[]{a[0], a[1]};
};
public static boolean equals(float[]a, float[]b) {
return (a[0] == b[0] && a[1] == b[1] );
};
public static void add_ref(float[]a, float[]b, float[]dst) {
dst[0] = a[0]+b[0]; dst[1] = a[1]+b[1];
};
public static float[] add_new(float[]a, float[]b) {
return new float[]{(a[0]+b[0]), (a[1]+b[1])};
};
public static void sub_ref(float[]a, float[]b, float[]dst) {
dst[0] = a[0]-b[0]; dst[1] = a[1]-b[1];
};
public static float[] sub_new(float[]a, float[]b) {
return new float[]{(a[0]-b[0]), (a[1]-b[1])};
};
public static void line_midpoint_ref(float[]a, float[]b, float[]dst) {
dst[0] = (a[0] + b[0]) * 0.5f;
dst[1] = (a[1] + b[1]) * 0.5f;
};
public static float[] line_midpoint_new(float[]a, float[]b) {
return new float[]{(a[0]+b[0])*0.5f, (a[1]+b[1])*0.5f};
};
public static void triangle_midpoint_ref(float[]a, float[]b, float[]c, float[]dst) {
float f = 1/3f;
dst[0] = (a[0]+b[0]+c[0]) * f;
dst[1] = (a[1]+b[1]+c[1]) * f;
};
public static float[] triangle_midpoint_new(float[]a, float[]b, float[]c) {
float f = 1/3;
return new float[]{(a[0]+b[0]+c[0]) * f, (a[1]+b[1]+c[1]) * f};
};
public static void sum_ref(float[]a, float[]b, float[]c, float[]dst){
dst[0] = a[0]+b[0]+c[0];
dst[1] = a[1]+b[1]+c[1];
}
public static float[] sum_new(float[]a, float[]b, float[]c){
return new float[]{a[0]+b[0]+c[0], a[1]+b[1]+c[1]};
}
public static void sumlist_ref(float[][] arr, float[]dst){
float len = arr.length;
for(int i = 0; i < len; i++){
dst[0] += arr[i][0];
dst[1] += arr[i][1];
}
}
public static float[] sumlist_new(float[][] arr){
float[] dst = new float[3];
int len = arr.length;
for(int i = 0; i < len; i++){
dst[0] += arr[i][0];
dst[1] += arr[i][1];
}
return dst;
}
public static void multiply_ref(float[]a, float[]b, float[]dst) {
dst[0] = a[0] * b[0];
dst[1] = a[1] * b[1];
};
public static float[] multiply_new(float[]a, float[]b) {
return new float[]{a[0]*b[0], a[1]*b[1]};
};
public static void negate_ref(float[]a, float[]dst) {
dst[0] = -a[0];
dst[1] = -a[1];
};
public static void negate_ref_slf(float[]a) {
a[0] = -a[0];
a[1] = -a[1];
};
public static float[] negate_new(float[]a) {
return new float[]{-a[0], -a[1]};
};
public static void scale_ref(float[]a, float val, float[]dst) {
dst[0] = a[0] * val;
dst[1] = a[1] * val;
};
public static void scale_ref_slf(float[]a, float val) {
a[0] *= val;
a[1] *= val;
};
public static float[] scale_new(float[]a, float val) {
return new float[]{a[0] * val, a[1] * val};
};
public static void normalize_ref_slf(float[]a) {
float x = a[0], y = a[1];
float len = (float) Math.sqrt(x*x + y*y);
if (len != 1) {
len = 1 / len;
a[0] *= len;
a[1] *= len;
}
};
public static void normalize_ref(float[]a, float[]dst) {
float x = a[0], y = a[1];
float len = (float) Math.sqrt(x*x + y*y);
if (len == 0) {
dst[0] = 0;
dst[1] = 0;
} else if (len == 1) {
dst[0] = x;
dst[1] = y;
} else {
len = 1 / len;
dst[0] = x * len;
dst[1] = y * len;
}
};
public static float[] normalize_new(float[]a) {
float x = a[0], y = a[1];
float len = (float) Math.sqrt(x*x + y*y);
if (len == 0) {
return new float[3];
} else if (len == 1) {
return new float[]{x, y};
} else {
return new float[]{x*len, y*len};
}
};
public static float dot(float[]a, float[]b) {
return a[0]*b[0] + a[1]*b[1];
};
public static float angleBetween(float[]a, float[]b){
return (float) Math.acos( DwVec2.dot(a,b)/(DwVec2.mag(a)*DwVec2.mag(b)) );
}
public static float angleBetween_unit(float[]a, float[]b){
return (float) Math.acos( DwVec2.dot(a,b) );
}
public static float mag(float[]a) {
float x = a[0], y = a[1];
return (float) Math.sqrt(x*x + y*y);
};
public static float mag_sq(float[]a) {
float x = a[0], y = a[1];
return x*x + y*y;
};
public static void dir_unit_ref(float[]a, float[]b, float[]dst) {
DwVec2.sub_ref(a, b, dst);
DwVec2.normalize_ref_slf(dst);
};
public static float[] dir_unit_new(float[]a, float[]b) {
float[] dst = new float[3];
DwVec2.sub_ref(a, b, dst);
DwVec2.normalize_ref_slf(dst);
return dst;
};
public static void lerp_ref(float[]a, float[]b, float val, float[]dst) {
dst[0] = a[0] + val * (b[0] - a[0]);
dst[1] = a[1] + val * (b[1] - a[1]);
};
public static float[] lerp_new(float[]a, float[]b, float val) {
return new float[]{a[0]+val*(b[0]-a[0]), a[1]+val*(b[1]-a[1])};
};
public static float dist(float[]a, float[]b) {
float[] dst = DwVec2.sub_new(a, b);
return DwVec2.mag(dst);
};
public static String toStr(float[] a, int prec) {
return String.format(Locale.ENGLISH, "[%+3.3f, %+3.3f]", a[0], a[1]);
};
public static void print(float[] a, int prec) {
System.out.println(toStr(a, prec));
}
}
| 6,326
|
Java
|
.java
| 197
| 27.741117
| 86
| 0.570249
|
kefik/Pogamut3
| 3
| 1
| 29
|
GPL-3.0
|
9/4/2024, 11:36:28 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 6,326
|
4,314,942
|
TraceBuilderPhase.java
|
hzio_OpenJDK10/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir/src/org/graalvm/compiler/lir/alloc/trace/TraceBuilderPhase.java
|
/*
* Copyright (c) 2016, 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.
*
* 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 org.graalvm.compiler.lir.alloc.trace;
import static org.graalvm.compiler.lir.alloc.trace.TraceUtil.isTrivialTrace;
import java.util.ArrayList;
import org.graalvm.compiler.core.common.alloc.BiDirectionalTraceBuilder;
import org.graalvm.compiler.core.common.alloc.SingleBlockTraceBuilder;
import org.graalvm.compiler.core.common.alloc.Trace;
import org.graalvm.compiler.core.common.alloc.TraceBuilderResult;
import org.graalvm.compiler.core.common.alloc.TraceBuilderResult.TrivialTracePredicate;
import org.graalvm.compiler.core.common.alloc.TraceStatisticsPrinter;
import org.graalvm.compiler.core.common.alloc.UniDirectionalTraceBuilder;
import org.graalvm.compiler.core.common.cfg.AbstractBlockBase;
import org.graalvm.compiler.debug.DebugContext;
import org.graalvm.compiler.debug.GraalError;
import org.graalvm.compiler.lir.LIR;
import org.graalvm.compiler.lir.gen.LIRGenerationResult;
import org.graalvm.compiler.lir.phases.AllocationPhase;
import org.graalvm.compiler.options.EnumOptionKey;
import org.graalvm.compiler.options.Option;
import org.graalvm.compiler.options.OptionKey;
import org.graalvm.compiler.options.OptionType;
import org.graalvm.compiler.options.OptionValues;
import jdk.vm.ci.code.TargetDescription;
public class TraceBuilderPhase extends AllocationPhase {
public enum TraceBuilder {
UniDirectional,
BiDirectional,
SingleBlock
}
public static class Options {
// @formatter:off
@Option(help = "Trace building algorithm.", type = OptionType.Debug)
public static final EnumOptionKey<TraceBuilder> TraceBuilding = new EnumOptionKey<>(TraceBuilder.UniDirectional);
@Option(help = "Schedule trivial traces as early as possible.", type = OptionType.Debug)
public static final OptionKey<Boolean> TraceRAScheduleTrivialTracesEarly = new OptionKey<>(true);
// @formatter:on
}
@Override
protected void run(TargetDescription target, LIRGenerationResult lirGenRes, AllocationContext context) {
AbstractBlockBase<?>[] linearScanOrder = lirGenRes.getLIR().linearScanOrder();
AbstractBlockBase<?> startBlock = linearScanOrder[0];
LIR lir = lirGenRes.getLIR();
assert startBlock.equals(lir.getControlFlowGraph().getStartBlock());
final TraceBuilderResult traceBuilderResult = getTraceBuilderResult(lir, startBlock, linearScanOrder);
DebugContext debug = lir.getDebug();
if (debug.isLogEnabled(DebugContext.BASIC_LEVEL)) {
ArrayList<Trace> traces = traceBuilderResult.getTraces();
for (int i = 0; i < traces.size(); i++) {
Trace trace = traces.get(i);
debug.log(DebugContext.BASIC_LEVEL, "Trace %5d: %s%s", i, trace, isTrivialTrace(lirGenRes.getLIR(), trace) ? " (trivial)" : "");
}
}
TraceStatisticsPrinter.printTraceStatistics(debug, traceBuilderResult, lirGenRes.getCompilationUnitName());
debug.dump(DebugContext.VERBOSE_LEVEL, traceBuilderResult, "TraceBuilderResult");
context.contextAdd(traceBuilderResult);
}
private static TraceBuilderResult getTraceBuilderResult(LIR lir, AbstractBlockBase<?> startBlock, AbstractBlockBase<?>[] linearScanOrder) {
TraceBuilderResult.TrivialTracePredicate pred = getTrivialTracePredicate(lir);
OptionValues options = lir.getOptions();
TraceBuilder selectedTraceBuilder = Options.TraceBuilding.getValue(options);
DebugContext debug = lir.getDebug();
debug.log(DebugContext.BASIC_LEVEL, "Building Traces using %s", selectedTraceBuilder);
switch (Options.TraceBuilding.getValue(options)) {
case SingleBlock:
return SingleBlockTraceBuilder.computeTraces(debug, startBlock, linearScanOrder, pred);
case BiDirectional:
return BiDirectionalTraceBuilder.computeTraces(debug, startBlock, linearScanOrder, pred);
case UniDirectional:
return UniDirectionalTraceBuilder.computeTraces(debug, startBlock, linearScanOrder, pred);
}
throw GraalError.shouldNotReachHere("Unknown trace building algorithm: " + Options.TraceBuilding.getValue(options));
}
public static TraceBuilderResult.TrivialTracePredicate getTrivialTracePredicate(LIR lir) {
if (!Options.TraceRAScheduleTrivialTracesEarly.getValue(lir.getOptions())) {
return null;
}
return new TrivialTracePredicate() {
@Override
public boolean isTrivialTrace(Trace trace) {
return TraceUtil.isTrivialTrace(lir, trace);
}
};
}
}
| 5,703
|
Java
|
.java
| 105
| 48.07619
| 144
| 0.74915
|
hzio/OpenJDK10
| 2
| 4
| 0
|
GPL-2.0
|
9/5/2024, 12:08:58 AM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| true
| true
| true
| 5,703
|
1,247,623
|
RawRes.java
|
Cloudslab_FogBus/Android-app/New-BLE/Java-src/android/support/annotation/RawRes.java
|
package android.support.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.LOCAL_VARIABLE})
@Retention(RetentionPolicy.CLASS)
public @interface RawRes {
}
| 414
|
Java
|
.java
| 11
| 36.454545
| 99
| 0.860349
|
Cloudslab/FogBus
| 39
| 17
| 0
|
GPL-2.0
|
9/4/2024, 7:28:16 PM (Europe/Amsterdam)
| false
| true
| false
| true
| true
| true
| true
| true
| 414
|
3,019,313
|
package-info.java
|
FCWorkgroupMC_F2C/src/main/java/net/fabricmc/loader/gui/package-info.java
|
/*
* Copyright 2016 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2020 FCWorkgroupMC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** The swing GUI shown if any major errors are thrown while obtaining the list of mods in
* {@link io.github.fcworkgroupmc.f2c.f2c.fabric.FabricLoader#loadMods()} .
* <p>
* This could potentially be useful for showing an tree-like structure while in-game, however this usecase is rather
* limited. */
package net.fabricmc.loader.gui;
| 1,627
|
Java
|
.java
| 37
| 42.054054
| 116
| 0.759597
|
FCWorkgroupMC/F2C
| 5
| 1
| 1
|
GPL-3.0
|
9/4/2024, 10:42:50 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 1,627
|
39,504
|
FileUtils.java
|
cropsly_ffmpeg-android-java/FFmpegAndroid/src/main/java/com/github/hiteshsondhi88/libffmpeg/FileUtils.java
|
package com.github.hiteshsondhi88.libffmpeg;
import android.content.Context;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.Map;
class FileUtils {
static final String ffmpegFileName = "ffmpeg";
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final int EOF = -1;
static boolean copyBinaryFromAssetsToData(Context context, String fileNameFromAssets, String outputFileName) {
// create files directory under /data/data/package name
File filesDirectory = getFilesDirectory(context);
InputStream is;
try {
is = context.getAssets().open(fileNameFromAssets);
// copy ffmpeg file from assets to files dir
final FileOutputStream os = new FileOutputStream(new File(filesDirectory, outputFileName));
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int n;
while(EOF != (n = is.read(buffer))) {
os.write(buffer, 0, n);
}
Util.close(os);
Util.close(is);
return true;
} catch (IOException e) {
Log.e("issue in coping binary from assets to data. ", e);
}
return false;
}
static File getFilesDirectory(Context context) {
// creates files directory under data/data/package name
return context.getFilesDir();
}
static String getFFmpeg(Context context) {
return getFilesDirectory(context).getAbsolutePath() + File.separator + FileUtils.ffmpegFileName;
}
static String getFFmpeg(Context context, Map<String,String> environmentVars) {
String ffmpegCommand = "";
if (environmentVars != null) {
for (Map.Entry<String, String> var : environmentVars.entrySet()) {
ffmpegCommand += var.getKey()+"="+var.getValue()+" ";
}
}
ffmpegCommand += getFFmpeg(context);
return ffmpegCommand;
}
static String SHA1(String file) {
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
return SHA1(is);
} catch (IOException e) {
Log.e(e);
} finally {
Util.close(is);
}
return null;
}
static String SHA1(InputStream is) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
for (int read; (read = is.read(buffer)) != -1; ) {
messageDigest.update(buffer, 0, read);
}
Formatter formatter = new Formatter();
// Convert the byte to hex format
for (final byte b : messageDigest.digest()) {
formatter.format("%02x", b);
}
return formatter.toString();
} catch (NoSuchAlgorithmException e) {
Log.e(e);
} catch (IOException e) {
Log.e(e);
} finally {
Util.close(is);
}
return null;
}
}
| 3,190
|
Java
|
.java
| 89
| 28.449438
| 114
| 0.644018
|
cropsly/ffmpeg-android-java
| 3,321
| 831
| 275
|
GPL-3.0
|
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 3,190
|
4,796,355
|
PrimaryExpr.java
|
millecker_soot-rb/generated/jastadd/soot/JastAddJ/PrimaryExpr.java
|
/* This file was generated with JastAdd2 (http://jastadd.org) version R20121122 (r889) */
package soot.JastAddJ;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.io.File;
import java.util.*;
import beaver.*;
import java.util.ArrayList;
import java.util.zip.*;
import java.io.*;
import java.io.FileNotFoundException;
import java.util.Collection;
import soot.*;
import soot.util.*;
import soot.jimple.*;
import soot.coffi.ClassFile;
import soot.coffi.method_info;
import soot.coffi.CONSTANT_Utf8_info;
import soot.tagkit.SourceFileTag;
import soot.coffi.CoffiMethodSource;
/**
* @production PrimaryExpr : {@link Expr};
* @ast node
* @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/java.ast:129
*/
public abstract class PrimaryExpr extends Expr implements Cloneable {
/**
* @apilevel low-level
*/
public void flushCache() {
super.flushCache();
}
/**
* @apilevel internal
*/
public void flushCollectionCache() {
super.flushCollectionCache();
}
/**
* @apilevel internal
*/
@SuppressWarnings({"unchecked", "cast"})
public PrimaryExpr clone() throws CloneNotSupportedException {
PrimaryExpr node = (PrimaryExpr)super.clone();
node.in$Circle(false);
node.is$Final(false);
return node;
}
/**
* @ast method
*
*/
public PrimaryExpr() {
super();
}
/**
* Initializes the child array to the correct size.
* Initializes List and Opt nta children.
* @apilevel internal
* @ast method
* @ast method
*
*/
public void init$Children() {
}
/**
* @apilevel low-level
* @ast method
*
*/
protected int numChildren() {
return 0;
}
/**
* @apilevel internal
* @ast method
*
*/
public boolean mayHaveRewrite() {
return false;
}
/**
* @apilevel internal
*/
public ASTNode rewriteTo() {
return super.rewriteTo();
}
}
| 1,923
|
Java
|
.java
| 88
| 18.772727
| 96
| 0.695961
|
millecker/soot-rb
| 1
| 5
| 0
|
LGPL-2.1
|
9/5/2024, 12:32:12 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| true
| true
| true
| 1,923
|
3,442,755
|
SimpleASNWriter.java
|
petergeneric_j2ssh/src/main/java/com/sshtools/j2ssh/util/SimpleASNWriter.java
|
/*
* SSHTools - Java SSH2 API
*
* Copyright (C) 2002-2003 Lee David Painter and Contributors.
*
* Contributions made by:
*
* Brett Smith
* Richard Pernavas
* Erwin Bolwidt
*
* 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 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.sshtools.j2ssh.util;
import java.io.*;
/**
*
*
* @author $author$
* @version $Revision: 1.12 $
*/
public class SimpleASNWriter {
private ByteArrayOutputStream data;
/**
* Creates a new SimpleASNWriter object.
*/
public SimpleASNWriter() {
this.data = new ByteArrayOutputStream();
}
/**
*
*
* @param b
*/
public void writeByte(int b) {
data.write(b);
}
/**
*
*
* @param b
*/
public void writeData(byte[] b) {
writeLength(b.length);
this.data.write(b, 0, b.length);
}
/**
*
*
* @param length
*/
public void writeLength(int length) {
if (length < 0x80) {
data.write(length);
} else {
if (length < 0x100) {
data.write(0x81);
data.write(length);
} else if (length < 0x10000) {
data.write(0x82);
data.write(length >>> 8);
data.write(length);
} else if (length < 0x1000000) {
data.write(0x83);
data.write(length >>> 16);
data.write(length >>> 8);
data.write(length);
} else {
data.write(0x84);
data.write(length >>> 24);
data.write(length >>> 16);
data.write(length >>> 8);
data.write(length);
}
}
}
/**
*
*
* @return
*/
public byte[] toByteArray() {
return data.toByteArray();
}
}
| 2,538
|
Java
|
.java
| 97
| 19.484536
| 83
| 0.565146
|
petergeneric/j2ssh
| 3
| 4
| 1
|
GPL-2.0
|
9/4/2024, 11:27:52 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| true
| true
| 2,538
|
1,316,141
|
B.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface/test75/in/B.java
|
package p;
public class B {
B(int t, A a){
}
}
| 50
|
Java
|
.java
| 5
| 8.4
| 16
| 0.613636
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 50
|
11,284
|
NoArgTestCaseTest.java
|
junit-team_junit4/src/test/java/junit/tests/framework/NoArgTestCaseTest.java
|
package junit.tests.framework;
import junit.framework.TestCase;
public class NoArgTestCaseTest extends TestCase {
public void testNothing() { // If this compiles, the no arg ctor is there
}
}
| 202
|
Java
|
.java
| 6
| 31
| 77
| 0.778351
|
junit-team/junit4
| 8,517
| 3,254
| 125
|
EPL-1.0
|
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 202
|
1,337,640
|
JRangeSlider.java
|
JorenSix_Tarsos/src/be/tarsos/util/JRangeSlider.java
|
/*
* _______
* |__ __|
* | | __ _ _ __ ___ ___ ___
* | |/ _` | '__/ __|/ _ \/ __|
* | | (_| | | \__ \ (_) \__ \
* |_|\__,_|_| |___/\___/|___/
*
* -----------------------------------------------------------
*
* Tarsos is developed by Joren Six at IPEM, University Ghent
*
* -----------------------------------------------------------
*
* Info: http://tarsos.0110.be
* Github: https://github.com/JorenSix/Tarsos
* Releases: http://0110.be/releases/Tarsos/
*
* Tarsos includes some source code by various authors,
* for credits, license and info: see README.
*
*/
package be.tarsos.util;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.BoundedRangeModel;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.JComponent;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* <p>Implements a Swing-based Range slider, which allows the user to enter a
* range (minimum and maximum) value.</p>
*
* @author Ben Bederson
* @author Jesse Grosjean
* @author Jon Meyer
* @author Lance Good
* @author jeffrey heer
* @author Colin Combe
*/
public class JRangeSlider extends JComponent
implements MouseListener, MouseMotionListener, KeyListener
{
/*
* NOTE: This is a modified version of the original class distributed by
* Ben Bederson, Jesse Grosjean, and Jon Meyer as part of an HCIL Tech
* Report. It is modified to allow both vertical and horitonal modes.
* It also fixes a bug with offset on the buttons. Also fixed a bug with
* rendering using (x,y) instead of (0,0) as origin. Also modified to
* render arrows as a series of lines rather than as a GeneralPath.
* Also modified to fix rounding errors on toLocal and toScreen.
*
* With inclusion in prefuse, this class has been further modified to use a
* bounded range model, support keyboard commands and more extensize
* parameterization of rendering/appearance options. Furthermore, a stub
* method has been introduced to allow subclasses to perform custom
* rendering within the slider through.
*/
/**
*
*/
private static final long serialVersionUID = -1706784621756288539L;
final public static int VERTICAL = 0;
final public static int HORIZONTAL = 1;
final public static int LEFTRIGHT_TOPBOTTOM = 0;
final public static int RIGHTLEFT_BOTTOMTOP = 1;
final public static int PREFERRED_BREADTH = 16;
final public static int PREFERRED_LENGTH = 300;
final protected static int ARROW_SZ = 16;
final protected static int ARROW_WIDTH = 8;
final protected static int ARROW_HEIGHT = 4;
protected BoundedRangeModel model;
protected int orientation;
protected int direction;
protected boolean empty;
protected int increment = 1;
protected int minExtent = 0; // min extent, in pixels
protected ArrayList<ChangeListener> listeners = new ArrayList<ChangeListener>();
protected ChangeEvent changeEvent = null;
protected ChangeListener lstnr;
protected Color thumbColor = new Color(150,180,220);
// ------------------------------------------------------------------------
/**
* Create a new range slider.
*
* @param minimum - the minimum value of the range.
* @param maximum - the maximum value of the range.
* @param lowValue - the current low value shown by the range slider's bar.
* @param highValue - the current high value shown by the range slider's bar.
* @param orientation - construct a horizontal or vertical slider?
*/
public JRangeSlider(int minimum, int maximum, int lowValue, int highValue, int orientation) {
this(new DefaultBoundedRangeModel(lowValue, highValue - lowValue, minimum, maximum),
orientation,LEFTRIGHT_TOPBOTTOM);
}
/**
* Create a new range slider.
*
* @param minimum - the minimum value of the range.
* @param maximum - the maximum value of the range.
* @param lowValue - the current low value shown by the range slider's bar.
* @param highValue - the current high value shown by the range slider's bar.
* @param orientation - construct a horizontal or vertical slider?
* @param direction - Is the slider left-to-right/top-to-bottom or right-to-left/bottom-to-top
*/
public JRangeSlider(int minimum, int maximum, int lowValue, int highValue, int orientation, int direction) {
this(new DefaultBoundedRangeModel(lowValue, highValue - lowValue, minimum, maximum),
orientation, direction);
}
/**
* Create a new range slider.
*
* @param model - a BoundedRangeModel specifying the slider's range
* @param orientation - construct a horizontal or vertical slider?
* @param direction - Is the slider left-to-right/top-to-bottom or right-to-left/bottom-to-top
*/
public JRangeSlider(BoundedRangeModel model, int orientation, int direction) {
super.setFocusable(true);
this.model = model;
this.orientation = orientation;
this.direction = direction;
setForeground(Color.LIGHT_GRAY);
this.lstnr = createListener();
model.addChangeListener(lstnr);
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
}
/**
* Create a listener to relay change events from the bounded range model.
* @return a ChangeListener to relay events from the range model
*/
protected ChangeListener createListener() {
return new RangeSliderChangeListener();
}
/**
* Listener that fires a change event when it receives change event from
* the slider list model.
*/
protected class RangeSliderChangeListener implements ChangeListener {
public void stateChanged(ChangeEvent e) {
fireChangeEvent();
}
}
/**
* Returns the current "low" value shown by the range slider's bar. The low
* value meets the constraint minimum <= lowValue <= highValue <= maximum.
* @return The value.
*/
public int getLowValue() {
return model.getValue();
}
/**
* Sets the low value shown by this range slider. This causes the range slider to be
* repainted and a ChangeEvent to be fired.
* @param lowValue the low value to use
*/
public void setLowValue(int lowValue) {
int e = (model.getValue()-lowValue)+model.getExtent();
model.setRangeProperties(lowValue, e,
model.getMinimum(), model.getMaximum(), false);
model.setValue(lowValue);
}
/**
* Returns the current "high" value shown by the range slider's bar. The high
* value meets the constraint minimum <= lowValue <= highValue <= maximum.
* @return The value plus the extent.
*/
public int getHighValue() {
return model.getValue()+model.getExtent();
}
/**
* Sets the high value shown by this range slider. This causes the range slider to be
* repainted and a ChangeEvent to be fired.
* @param highValue the high value to use
*/
public void setHighValue(int highValue) {
model.setExtent(highValue-model.getValue());
}
/**
* Set the slider range span.
* @param lowValue the low value of the slider range
* @param highValue the high value of the slider range
*/
public void setRange(int lowValue, int highValue) {
model.setRangeProperties(lowValue, highValue-lowValue,
model.getMinimum(), model.getMaximum(), false);
}
/**
* Gets the minimum possible value for either the low value or the high value.
* @return the minimum possible range value
*/
public int getMinimum() {
return model.getMinimum();
}
/**
* Sets the minimum possible value for either the low value or the high value.
* @param minimum the minimum possible range value
*/
public void setMinimum(int minimum) {
model.setMinimum(minimum);
}
/**
* Gets the maximum possible value for either the low value or the high value.
* @return the maximum possible range value
*/
public int getMaximum() {
return model.getMaximum();
}
/**
* Sets the maximum possible value for either the low value or the high value.
* @param maximum the maximum possible range value
*/
public void setMaximum(int maximum) {
model.setMaximum(maximum);
}
/**
* Sets the minimum extent (difference between low and high values).
* This method <strong>does not</strong> change the current state of the
* model, but can affect all subsequent interaction.
* @param minExtent the minimum extent allowed in subsequent interaction
*/
public void setMinExtent(int minExtent) {
this.minExtent = minExtent;
}
/**
* Sets whether this slider is empty.
* @param empty true if set to empty, false otherwise
*/
public void setEmpty(boolean empty) {
this.empty = empty;
repaint();
}
/**
* Get the slider thumb color. This is the part of the slider between
* the range resize buttons.
* @return the slider thumb color
*/
public Color getThumbColor() {
return thumbColor;
}
/**
* Set the slider thumb color. This is the part of the slider between
* the range resize buttons.
* @param thumbColor the slider thumb color
*/
public void setThumbColor(Color thumbColor) {
this.thumbColor = thumbColor;
}
/**
* Get the BoundedRangeModel backing this slider.
* @return the slider's range model
*/
public BoundedRangeModel getModel() {
return model;
}
/**
* Set the BoundedRangeModel backing this slider.
* @param brm the slider range model to use
*/
public void setModel(BoundedRangeModel brm) {
model.removeChangeListener(lstnr);
model = brm;
model.addChangeListener(lstnr);
repaint();
}
/**
* Registers a listener for ChangeEvents.
* @param cl the ChangeListener to add
*/
public void addChangeListener(ChangeListener cl) {
if ( !listeners.contains(cl) )
listeners.add(cl);
}
/**
* Removes a listener for ChangeEvents.
* @param cl the ChangeListener to remove
*/
public void removeChangeListener(ChangeListener cl) {
listeners.remove(cl);
}
/**
* Fire a change event to all listeners.
*/
protected void fireChangeEvent() {
repaint();
if ( changeEvent == null )
changeEvent = new ChangeEvent(this);
Iterator<ChangeListener> iter = listeners.iterator();
while ( iter.hasNext() )
((ChangeListener)iter.next()).stateChanged(changeEvent);
}
/**
* @see java.awt.Component#getPreferredSize()
*/
public Dimension getPreferredSize() {
if (orientation == VERTICAL) {
return new Dimension(PREFERRED_BREADTH, PREFERRED_LENGTH);
}
else {
return new Dimension(PREFERRED_LENGTH, PREFERRED_BREADTH);
}
}
// ------------------------------------------------------------------------
// Rendering
/**
* Override this method to perform custom painting of the slider trough.
* @param g a Graphics2D context for rendering
* @param width the width of the slider trough
* @param height the height of the slider trough
*/
protected void customPaint(Graphics2D g, int width, int height) {
// does nothing in this class
// subclasses can override to perform custom painting
}
/**
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
public void paintComponent(Graphics g) {
Rectangle bounds = getBounds();
int width = (int)bounds.getWidth() - 1;
int height = (int)bounds.getHeight() - 1;
int min = toScreen(getLowValue());
int max = toScreen(getHighValue());
// Paint the full slider if the slider is marked as empty
if (empty) {
if (direction == LEFTRIGHT_TOPBOTTOM) {
min = ARROW_SZ;
max = (orientation == VERTICAL) ? height-ARROW_SZ : width-ARROW_SZ;
}
else {
min = (orientation == VERTICAL) ? height-ARROW_SZ : width-ARROW_SZ;
max = ARROW_SZ;
}
}
Graphics2D g2 = (Graphics2D)g;
g2.setColor(getBackground());
g2.fillRect(0, 0, width, height);
g2.setColor(getForeground());
g2.drawRect(0, 0, width, height);
customPaint(g2, width, height);
// Draw arrow and thumb backgrounds
g2.setStroke(new BasicStroke(1));
if (orientation == VERTICAL) {
if (direction == LEFTRIGHT_TOPBOTTOM) {
g2.setColor(getForeground());
g2.fillRect(0, min - ARROW_SZ, width, ARROW_SZ-1);
paint3DRectLighting(g2,0,min-ARROW_SZ,width,ARROW_SZ-1);
if ( thumbColor != null ) {
g2.setColor(thumbColor);
g2.fillRect(0, min, width, max - min-1);
paint3DRectLighting(g2,0,min,width,max-min-1);
}
g2.setColor(getForeground());
g2.fillRect(0, max, width, ARROW_SZ-1);
paint3DRectLighting(g2,0,max,width,ARROW_SZ-1);
// Draw arrows
g2.setColor(Color.black);
paintArrow(g2, (width-ARROW_WIDTH) / 2.0, min - ARROW_SZ + (ARROW_SZ-ARROW_HEIGHT) / 2.0, ARROW_WIDTH, ARROW_HEIGHT, true);
paintArrow(g2, (width-ARROW_WIDTH) / 2.0, max + (ARROW_SZ-ARROW_HEIGHT) / 2.0, ARROW_WIDTH, ARROW_HEIGHT, false);
}
else {
g2.setColor(getForeground());
g2.fillRect(0, min, width, ARROW_SZ-1);
paint3DRectLighting(g2,0,min,width,ARROW_SZ-1);
if ( thumbColor != null ) {
g2.setColor(thumbColor);
g2.fillRect(0, max, width, min-max-1);
paint3DRectLighting(g2,0,max,width,min-max-1);
}
g2.setColor(getForeground());
g2.fillRect(0, max-ARROW_SZ, width, ARROW_SZ-1);
paint3DRectLighting(g2,0,max-ARROW_SZ,width,ARROW_SZ-1);
// Draw arrows
g2.setColor(Color.black);
paintArrow(g2, (width-ARROW_WIDTH) / 2.0, min + (ARROW_SZ-ARROW_HEIGHT) / 2.0, ARROW_WIDTH, ARROW_HEIGHT, false);
paintArrow(g2, (width-ARROW_WIDTH) / 2.0, max - ARROW_SZ + (ARROW_SZ-ARROW_HEIGHT) / 2.0, ARROW_WIDTH, ARROW_HEIGHT, true);
}
}
else {
if (direction == LEFTRIGHT_TOPBOTTOM) {
g2.setColor(getForeground());
g2.fillRect(min - ARROW_SZ, 0, ARROW_SZ-1, height);
paint3DRectLighting(g2,min-ARROW_SZ,0,ARROW_SZ-1,height);
if ( thumbColor != null ) {
g2.setColor(thumbColor);
g2.fillRect(min, 0, max - min - 1, height);
paint3DRectLighting(g2,min,0,max-min-1,height);
}
g2.setColor(getForeground());
g2.fillRect(max, 0, ARROW_SZ-1, height);
paint3DRectLighting(g2,max,0,ARROW_SZ-1,height);
// Draw arrows
g2.setColor(Color.black);
paintArrow(g2, min - ARROW_SZ + (ARROW_SZ-ARROW_HEIGHT) / 2.0, (height-ARROW_WIDTH) / 2.0, ARROW_HEIGHT, ARROW_WIDTH, true);
paintArrow(g2, max + (ARROW_SZ-ARROW_HEIGHT) / 2.0, (height-ARROW_WIDTH) / 2.0, ARROW_HEIGHT, ARROW_WIDTH, false);
}
else {
g2.setColor(getForeground());
g2.fillRect(min, 0, ARROW_SZ - 1, height);
paint3DRectLighting(g2,min,0,ARROW_SZ-1,height);
if ( thumbColor != null ) {
g2.setColor(thumbColor);
g2.fillRect(max, 0, min - max - 1, height);
paint3DRectLighting(g2,max,0,min-max-1,height);
}
g2.setColor(getForeground());
g2.fillRect(max-ARROW_SZ, 0, ARROW_SZ-1, height);
paint3DRectLighting(g2,max-ARROW_SZ,0,ARROW_SZ-1,height);
// Draw arrows
g2.setColor(Color.black);
paintArrow(g2, min + (ARROW_SZ-ARROW_HEIGHT) / 2.0, (height-ARROW_WIDTH) / 2.0, ARROW_HEIGHT, ARROW_WIDTH, true);
paintArrow(g2, max - ARROW_SZ + (ARROW_SZ-ARROW_HEIGHT) / 2.0, (height-ARROW_WIDTH) / 2.0, ARROW_HEIGHT, ARROW_WIDTH, false);
}
}
}
/**
* This draws an arrow as a series of lines within the specified box.
* The last boolean specifies whether the point should be at the
* right/bottom or left/top.
*/
protected void paintArrow(Graphics2D g2, double x, double y, int w, int h,
boolean topDown)
{
int intX = (int)(x+0.5);
int intY = (int)(y+0.5);
if (orientation == VERTICAL) {
if (w % 2 == 0) {
w = w - 1;
}
if (topDown) {
for(int i=0; i<(w/2+1); i++) {
g2.drawLine(intX+i,intY+i,intX+w-i-1,intY+i);
}
}
else {
for(int i=0; i<(w/2+1); i++) {
g2.drawLine(intX+w/2-i,intY+i,intX+w-w/2+i-1,intY+i);
}
}
}
else {
if (h % 2 == 0) {
h = h - 1;
}
if (topDown) {
for(int i=0; i<(h/2+1); i++) {
g2.drawLine(intX+i,intY+i,intX+i,intY+h-i-1);
}
}
else {
for(int i=0; i<(h/2+1); i++) {
g2.drawLine(intX+i,intY+h/2-i,intX+i,intY+h-h/2+i-1);
}
}
}
}
/**
* Adds Windows2K type 3D lighting effects
*/
protected void paint3DRectLighting(Graphics2D g2, int x, int y,
int width, int height)
{
g2.setColor(Color.white);
g2.drawLine(x+1,y+1,x+1,y+height-1);
g2.drawLine(x+1,y+1,x+width-1,y+1);
g2.setColor(Color.gray);
g2.drawLine(x+1,y+height-1,x+width-1,y+height-1);
g2.drawLine(x+width-1,y+1,x+width-1,y+height-1);
g2.setColor(Color.darkGray);
g2.drawLine(x,y+height,x+width,y+height);
g2.drawLine(x+width,y,x+width,y+height);
}
/**
* Converts from screen coordinates to a range value.
*/
protected int toLocal(int xOrY) {
Dimension sz = getSize();
int min = getMinimum();
double scale;
if (orientation == VERTICAL) {
scale = (sz.height - (2 * ARROW_SZ)) / (double) (getMaximum() - min);
}
else {
scale = (sz.width - (2 * ARROW_SZ)) / (double) (getMaximum() - min);
}
if (direction == LEFTRIGHT_TOPBOTTOM) {
return (int) (((xOrY - ARROW_SZ) / scale) + min + 0.5);
}
else {
if (orientation == VERTICAL) {
return (int) ((sz.height - xOrY - ARROW_SZ) / scale + min + 0.5);
}
else {
return (int) ((sz.width - xOrY - ARROW_SZ) / scale + min + 0.5);
}
}
}
/**
* Converts from a range value to screen coordinates.
*/
protected int toScreen(int xOrY) {
Dimension sz = getSize();
int min = getMinimum();
double scale;
if (orientation == VERTICAL) {
scale = (sz.height - (2 * ARROW_SZ)) / (double) (getMaximum() - min);
}
else {
scale = (sz.width - (2 * ARROW_SZ)) / (double) (getMaximum() - min);
}
// If the direction is left/right_top/bottom then we subtract the min and multiply times scale
// Otherwise, we have to invert the number by subtracting the value from the height
if (direction == LEFTRIGHT_TOPBOTTOM) {
return (int)(ARROW_SZ + ((xOrY - min) * scale) + 0.5);
}
else {
if (orientation == VERTICAL) {
return (int)(sz.height-(xOrY - min) * scale - ARROW_SZ + 0.5);
}
else {
return (int)(sz.width-(xOrY - min) * scale - ARROW_SZ + 0.5);
}
}
}
/**
* Converts from a range value to screen coordinates.
*/
protected double toScreenDouble(int xOrY) {
Dimension sz = getSize();
int min = getMinimum();
double scale;
if (orientation == VERTICAL) {
scale = (sz.height - (2 * ARROW_SZ)) / (double) (getMaximum()+1 - min);
}
else {
scale = (sz.width - (2 * ARROW_SZ)) / (double) (getMaximum()+1 - min);
}
// If the direction is left/right_top/bottom then we subtract the min and multiply times scale
// Otherwise, we have to invert the number by subtracting the value from the height
if (direction == LEFTRIGHT_TOPBOTTOM) {
return ARROW_SZ + ((xOrY - min) * scale);
}
else {
if (orientation == VERTICAL) {
return sz.height-(xOrY - min) * scale - ARROW_SZ;
}
else {
return sz.width-(xOrY - min) * scale - ARROW_SZ;
}
}
}
// ------------------------------------------------------------------------
// Event Handling
static final int PICK_NONE = 0;
static final int PICK_LEFT_OR_TOP = 1;
static final int PICK_THUMB = 2;
static final int PICK_RIGHT_OR_BOTTOM = 3;
int pick;
int pickOffsetLow;
int pickOffsetHigh;
int mouse;
private int pickHandle(int xOrY) {
int min = toScreen(getLowValue());
int max = toScreen(getHighValue());
int pick = PICK_NONE;
if (direction == LEFTRIGHT_TOPBOTTOM) {
if ((xOrY > (min - ARROW_SZ)) && (xOrY < min)) {
pick = PICK_LEFT_OR_TOP;
} else if ((xOrY >= min) && (xOrY <= max)) {
pick = PICK_THUMB;
} else if ((xOrY > max) && (xOrY < (max + ARROW_SZ))) {
pick = PICK_RIGHT_OR_BOTTOM;
}
}
else {
if ((xOrY > min) && (xOrY < (min + ARROW_SZ))) {
pick = PICK_LEFT_OR_TOP;
} else if ((xOrY <= min) && (xOrY >= max)) {
pick = PICK_THUMB;
} else if ((xOrY > (max - ARROW_SZ) && (xOrY < max))) {
pick = PICK_RIGHT_OR_BOTTOM;
}
}
return pick;
}
private void offset(int dxOrDy) {
model.setValue(model.getValue()+dxOrDy);
}
/**
* @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
*/
public void mousePressed(MouseEvent e) {
if (orientation == VERTICAL) {
pick = pickHandle(e.getY());
pickOffsetLow = e.getY() - toScreen(getLowValue());
pickOffsetHigh = e.getY() - toScreen(getHighValue());
mouse = e.getY();
}
else {
pick = pickHandle(e.getX());
pickOffsetLow = e.getX() - toScreen(getLowValue());
pickOffsetHigh = e.getX() - toScreen(getHighValue());
mouse = e.getX();
}
repaint();
}
/**
* @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
*/
public void mouseDragged(MouseEvent e) {
requestFocus();
int value = (orientation == VERTICAL) ? e.getY() : e.getX();
int minimum = getMinimum();
int maximum = getMaximum();
int lowValue = getLowValue();
int highValue = getHighValue();
switch (pick) {
case PICK_LEFT_OR_TOP:
int low = toLocal(value-pickOffsetLow);
if (low < minimum) {
low = minimum;
}
if (low > maximum - minExtent) {
low = maximum - minExtent;
}
if (low > highValue-minExtent) {
setRange(low, low + minExtent);
}
else
setLowValue(low);
break;
case PICK_RIGHT_OR_BOTTOM:
int high = toLocal(value-pickOffsetHigh);
if (high < minimum + minExtent) {
high = minimum + minExtent;
}
if (high > maximum) {
high = maximum;
}
if (high < lowValue+minExtent) {
setRange(high - minExtent, high);
}
else
setHighValue(high);
break;
case PICK_THUMB:
int dxOrDy = toLocal(value - pickOffsetLow) - lowValue;
if ((dxOrDy < 0) && ((lowValue + dxOrDy) < minimum)) {
dxOrDy = minimum - lowValue;
}
if ((dxOrDy > 0) && ((highValue + dxOrDy) > maximum)) {
dxOrDy = maximum - highValue;
}
if (dxOrDy != 0) {
offset(dxOrDy);
}
break;
}
}
/**
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
*/
public void mouseReleased(MouseEvent e) {
pick = PICK_NONE;
repaint();
}
/**
* @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
*/
public void mouseMoved(MouseEvent e) {
if (orientation == VERTICAL) {
switch (pickHandle(e.getY())) {
case PICK_LEFT_OR_TOP:
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
break;
case PICK_RIGHT_OR_BOTTOM:
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
break;
case PICK_THUMB:
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
break;
case PICK_NONE :
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
break;
}
}
else {
switch (pickHandle(e.getX())) {
case PICK_LEFT_OR_TOP:
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
break;
case PICK_RIGHT_OR_BOTTOM:
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
break;
case PICK_THUMB:
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
break;
case PICK_NONE :
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
break;
}
}
}
/**
* @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
*/
public void mouseClicked(MouseEvent e) {
}
/**
* @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
*/
public void mouseEntered(MouseEvent e) {
}
/**
* @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
*/
public void mouseExited(MouseEvent e) {
}
private void grow(int increment) {
model.setRangeProperties(model.getValue()-increment,
model.getExtent()+2*increment,
model.getMinimum(), model.getMaximum(), false);
}
/**
* @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
*/
public void keyPressed(KeyEvent e) {
int kc = e.getKeyCode();
boolean v = (orientation == VERTICAL);
boolean d = (kc == KeyEvent.VK_DOWN);
boolean u = (kc == KeyEvent.VK_UP);
boolean l = (kc == KeyEvent.VK_LEFT);
boolean r = (kc == KeyEvent.VK_RIGHT);
int minimum = getMinimum();
int maximum = getMaximum();
int lowValue = getLowValue();
int highValue = getHighValue();
if ( v&&r || !v&&u ) {
if ( lowValue-increment >= minimum &&
highValue+increment <= maximum ) {
grow(increment);
}
} else if ( v&&l || !v&&d ) {
if ( highValue-lowValue >= 2*increment ) {
grow(-1*increment);
}
} else if ( v&&d || !v&&l ) {
if ( lowValue-increment >= minimum ) {
offset(-increment);
}
} else if ( v&&u || !v&&r ) {
if ( highValue+increment <= maximum ) {
offset(increment);
}
}
}
/**
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
*/
public void keyReleased(KeyEvent e) {
}
/**
* @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
*/
public void keyTyped(KeyEvent e) {
}
} // end of class JRangeSlider
| 30,674
|
Java
|
.java
| 781
| 28.81178
| 160
| 0.556394
|
JorenSix/Tarsos
| 24
| 12
| 4
|
GPL-3.0
|
9/4/2024, 7:41:35 PM (Europe/Amsterdam)
| false
| true
| false
| true
| false
| true
| true
| true
| 30,674
|
1,310,043
|
ZPop3DataSource.java
|
zextras_carbonio-mailbox/client/src/main/java/com/zimbra/client/ZPop3DataSource.java
|
// SPDX-FileCopyrightText: 2022 Synacor, Inc.
// SPDX-FileCopyrightText: 2022 Zextras <https://www.zextras.com>
//
// SPDX-License-Identifier: GPL-2.0-only
package com.zimbra.client;
import org.json.JSONException;
import com.zimbra.common.soap.Element;
import com.zimbra.common.soap.MailConstants;
import com.zimbra.common.util.SystemUtil;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.soap.account.type.AccountPop3DataSource;
import com.zimbra.soap.admin.type.DataSourceType;
import com.zimbra.soap.mail.type.DataSourceNameOrId;
import com.zimbra.soap.mail.type.MailPop3DataSource;
import com.zimbra.soap.mail.type.Pop3DataSourceNameOrId;
import com.zimbra.soap.type.DataSource;
import com.zimbra.soap.type.DataSource.ConnectionType;
import com.zimbra.soap.type.DataSources;
import com.zimbra.soap.type.Pop3DataSource;
public class ZPop3DataSource extends ZDataSource implements ToZJSONObject {
public ZPop3DataSource(Pop3DataSource data) {
this.data = DataSources.newPop3DataSource(data);
}
public ZPop3DataSource(String name, boolean enabled, String host, int port,
String username, String password, String folderid,
ConnectionType connectionType, boolean leaveOnServer) {
data = new AccountPop3DataSource();
data.setName(name);
data.setEnabled(enabled);
data.setHost(host);
data.setPort(port);
data.setUsername(username);
data.setPassword(password);
data.setFolderId(folderid);
data.setConnectionType(connectionType);
setLeaveOnServer(leaveOnServer);
}
@Deprecated
public Element toElement(Element parent) {
Element src = parent.addElement(MailConstants.E_DS_POP3);
src.addAttribute(MailConstants.A_ID, data.getId());
src.addAttribute(MailConstants.A_NAME, data.getName());
src.addAttribute(MailConstants.A_DS_IS_ENABLED, data.isEnabled());
src.addAttribute(MailConstants.A_DS_HOST, data.getHost());
src.addAttribute(MailConstants.A_DS_PORT, data.getPort());
src.addAttribute(MailConstants.A_DS_USERNAME, data.getUsername());
src.addAttribute(MailConstants.A_DS_PASSWORD, data.getPassword());
src.addAttribute(MailConstants.A_FOLDER, data.getFolderId());
src.addAttribute(MailConstants.A_DS_CONNECTION_TYPE, data.getConnectionType().name());
src.addAttribute(MailConstants.A_DS_LEAVE_ON_SERVER, leaveOnServer());
ZimbraLog.test.info("XXX bburtin: " + src.prettyPrint());
return src;
}
@Deprecated
public Element toIdElement(Element parent) {
Element src = parent.addElement(MailConstants.E_DS_POP3);
src.addAttribute(MailConstants.A_ID, getId());
return src;
}
@Override
public DataSource toJaxb() {
MailPop3DataSource jaxbObject = new MailPop3DataSource();
jaxbObject.setId(data.getId());
jaxbObject.setName(data.getName());
jaxbObject.setHost(data.getHost());
jaxbObject.setPort(data.getPort());
jaxbObject.setUsername(data.getUsername());
jaxbObject.setPassword(data.getPassword());
jaxbObject.setFolderId(data.getFolderId());
jaxbObject.setConnectionType(data.getConnectionType());
jaxbObject.setLeaveOnServer(leaveOnServer());
jaxbObject.setEnabled(data.isEnabled());
return jaxbObject;
}
@Override
public DataSourceNameOrId toJaxbNameOrId() {
Pop3DataSourceNameOrId jaxbObject = Pop3DataSourceNameOrId.createForId(data.getId());
return jaxbObject;
}
private Pop3DataSource getData() {
return ((Pop3DataSource)data);
}
@Override
public DataSourceType getType() { return DataSourceType.pop3; }
public String getHost() { return data.getHost(); }
public void setHost(String host) { data.setHost(host); }
public int getPort() { return SystemUtil.coalesce(data.getPort(), -1); }
public void setPort(int port) { data.setPort(port); }
public String getUsername() { return data.getUsername(); }
public void setUsername(String username) { data.setUsername(username); }
public String getFolderId() { return data.getFolderId(); }
public void setFolderId(String folderid) { data.setFolderId(folderid); }
public ConnectionType getConnectionType() {
ConnectionType ct = data.getConnectionType();
return (ct == null ? ConnectionType.cleartext : ct);
}
public void setConnectionType(ConnectionType connectionType) {
data.setConnectionType(connectionType);
}
public boolean leaveOnServer() {
Boolean val = getData().isLeaveOnServer();
return (val == null ? true : val);
}
public void setLeaveOnServer(boolean leaveOnServer) { getData().setLeaveOnServer(leaveOnServer); }
public ZJSONObject toZJSONObject() throws JSONException {
ZJSONObject zjo = new ZJSONObject();
zjo.put("id", data.getId());
zjo.put("name", data.getName());
zjo.put("enabled", data.isEnabled());
zjo.put("host", data.getHost());
zjo.put("port", data.getPort());
zjo.put("username", data.getUsername());
zjo.put("folderId", data.getFolderId());
zjo.put("connectionType", data.getConnectionType().toString());
zjo.put("leaveOnServer", leaveOnServer());
return zjo;
}
public String toString() {
return String.format("[ZPop3DataSource %s]", getName());
}
public String dump() {
return ZJSONObject.toString(this);
}
}
| 5,624
|
Java
|
.java
| 124
| 38.419355
| 102
| 0.705107
|
zextras/carbonio-mailbox
| 32
| 6
| 6
|
GPL-2.0
|
9/4/2024, 7:33:43 PM (Europe/Amsterdam)
| false
| true
| false
| true
| true
| true
| true
| true
| 5,624
|
1,118,773
|
SimpleNamedDestination.java
|
SemanticBeeng_jpdfbookmarks/iText-2.1.7-patched/src/core/com/lowagie/text/pdf/SimpleNamedDestination.java
|
/*
* Copyright 2004 by Paulo Soares.
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library 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 Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
package com.lowagie.text.pdf;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import com.lowagie.text.xml.simpleparser.IanaEncodings;
import com.lowagie.text.xml.simpleparser.SimpleXMLDocHandler;
import com.lowagie.text.xml.simpleparser.SimpleXMLParser;
/**
*
* @author Paulo Soares ([email protected])
*/
public final class SimpleNamedDestination implements SimpleXMLDocHandler {
private HashMap xmlNames;
private HashMap xmlLast;
private SimpleNamedDestination() {
}
public static HashMap getNamedDestination(PdfReader reader, boolean fromNames) {
IntHashtable pages = new IntHashtable();
int numPages = reader.getNumberOfPages();
for (int k = 1; k <= numPages; ++k)
pages.put(reader.getPageOrigRef(k).getNumber(), k);
HashMap names = fromNames ? reader.getNamedDestinationFromNames() : reader.getNamedDestinationFromStrings();
for (Iterator it = names.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
PdfArray arr = (PdfArray)entry.getValue();
StringBuffer s = new StringBuffer();
try {
s.append(pages.get(arr.getAsIndirectObject(0).getNumber()));
s.append(' ').append(arr.getPdfObject(1).toString().substring(1));
for (int k = 2; k < arr.size(); ++k)
s.append(' ').append(arr.getPdfObject(k).toString());
entry.setValue(s.toString());
}
catch (Exception e) {
it.remove();
}
}
return names;
}
/**
* Exports the destinations to XML. The DTD for this XML is:
* <p>
* <pre>
* <?xml version='1.0' encoding='UTF-8'?>
* <!ELEMENT Name (#PCDATA)>
* <!ATTLIST Name
* Page CDATA #IMPLIED
* >
* <!ELEMENT Destination (Name)*>
* </pre>
* @param names the names
* @param out the export destination. The stream is not closed
* @param encoding the encoding according to IANA conventions
* @param onlyASCII codes above 127 will always be escaped with &#nn; if <CODE>true</CODE>,
* whatever the encoding
* @throws IOException on error
*/
public static void exportToXML(HashMap names, OutputStream out, String encoding, boolean onlyASCII) throws IOException {
String jenc = IanaEncodings.getJavaEncoding(encoding);
Writer wrt = new BufferedWriter(new OutputStreamWriter(out, jenc));
exportToXML(names, wrt, encoding, onlyASCII);
}
/**
* Exports the destinations to XML.
* @param names the names
* @param wrt the export destination. The writer is not closed
* @param encoding the encoding according to IANA conventions
* @param onlyASCII codes above 127 will always be escaped with &#nn; if <CODE>true</CODE>,
* whatever the encoding
* @throws IOException on error
*/
public static void exportToXML(HashMap names, Writer wrt, String encoding, boolean onlyASCII) throws IOException {
wrt.write("<?xml version=\"1.0\" encoding=\"");
wrt.write(SimpleXMLParser.escapeXML(encoding, onlyASCII));
wrt.write("\"?>\n<Destination>\n");
for (Iterator it = names.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
String key = (String)entry.getKey();
String value = (String)entry.getValue();
wrt.write(" <Name Page=\"");
wrt.write(SimpleXMLParser.escapeXML(value, onlyASCII));
wrt.write("\">");
wrt.write(SimpleXMLParser.escapeXML(escapeBinaryString(key), onlyASCII));
wrt.write("</Name>\n");
}
wrt.write("</Destination>\n");
wrt.flush();
}
/**
* Import the names from XML.
* @param in the XML source. The stream is not closed
* @throws IOException on error
* @return the names
*/
public static HashMap importFromXML(InputStream in) throws IOException {
SimpleNamedDestination names = new SimpleNamedDestination();
SimpleXMLParser.parse(names, in);
return names.xmlNames;
}
/**
* Import the names from XML.
* @param in the XML source. The reader is not closed
* @throws IOException on error
* @return the names
*/
public static HashMap importFromXML(Reader in) throws IOException {
SimpleNamedDestination names = new SimpleNamedDestination();
SimpleXMLParser.parse(names, in);
return names.xmlNames;
}
static PdfArray createDestinationArray(String value, PdfWriter writer) {
PdfArray ar = new PdfArray();
StringTokenizer tk = new StringTokenizer(value);
int n = Integer.parseInt(tk.nextToken());
ar.add(writer.getPageReference(n));
if (!tk.hasMoreTokens()) {
ar.add(PdfName.XYZ);
ar.add(new float[]{0, 10000, 0});
}
else {
String fn = tk.nextToken();
if (fn.startsWith("/"))
fn = fn.substring(1);
ar.add(new PdfName(fn));
for (int k = 0; k < 4 && tk.hasMoreTokens(); ++k) {
fn = tk.nextToken();
if (fn.equals("null"))
ar.add(PdfNull.PDFNULL);
else
ar.add(new PdfNumber(fn));
}
}
return ar;
}
public static PdfDictionary outputNamedDestinationAsNames(HashMap names, PdfWriter writer) {
PdfDictionary dic = new PdfDictionary();
for (Iterator it = names.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
try {
String key = (String)entry.getKey();
String value = (String)entry.getValue();
PdfArray ar = createDestinationArray(value, writer);
PdfName kn = new PdfName(key);
dic.put(kn, ar);
}
catch (Exception e) {
// empty on purpose
}
}
return dic;
}
public static PdfDictionary outputNamedDestinationAsStrings(HashMap names, PdfWriter writer) throws IOException {
HashMap n2 = new HashMap(names);
for (Iterator it = n2.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
try {
String value = (String)entry.getValue();
PdfArray ar = createDestinationArray(value, writer);
entry.setValue(writer.addToBody(ar).getIndirectReference());
}
catch (Exception e) {
it.remove();
}
}
return PdfNameTree.writeTree(n2, writer);
}
public static String escapeBinaryString(String s) {
StringBuffer buf = new StringBuffer();
char cc[] = s.toCharArray();
int len = cc.length;
for (int k = 0; k < len; ++k) {
char c = cc[k];
if (c < ' ') {
buf.append('\\');
String octal = "00" + Integer.toOctalString(c);
buf.append(octal.substring(octal.length() - 3));
}
else if (c == '\\')
buf.append("\\\\");
else
buf.append(c);
}
return buf.toString();
}
public static String unEscapeBinaryString(String s) {
StringBuffer buf = new StringBuffer();
char cc[] = s.toCharArray();
int len = cc.length;
for (int k = 0; k < len; ++k) {
char c = cc[k];
if (c == '\\') {
if (++k >= len) {
buf.append('\\');
break;
}
c = cc[k];
if (c >= '0' && c <= '7') {
int n = c - '0';
++k;
for (int j = 0; j < 2 && k < len; ++j) {
c = cc[k];
if (c >= '0' && c <= '7') {
++k;
n = n * 8 + c - '0';
}
else {
break;
}
}
--k;
buf.append((char)n);
}
else
buf.append(c);
}
else
buf.append(c);
}
return buf.toString();
}
public void endDocument() {
}
public void endElement(String tag) {
if (tag.equals("Destination")) {
if (xmlLast == null && xmlNames != null)
return;
else
throw new RuntimeException("Destination end tag out of place.");
}
if (!tag.equals("Name"))
throw new RuntimeException("Invalid end tag - " + tag);
if (xmlLast == null || xmlNames == null)
throw new RuntimeException("Name end tag out of place.");
if (!xmlLast.containsKey("Page"))
throw new RuntimeException("Page attribute missing.");
xmlNames.put(unEscapeBinaryString((String)xmlLast.get("Name")), xmlLast.get("Page"));
xmlLast = null;
}
public void startDocument() {
}
public void startElement(String tag, HashMap h) {
if (xmlNames == null) {
if (tag.equals("Destination")) {
xmlNames = new HashMap();
return;
}
else
throw new RuntimeException("Root element is not Destination.");
}
if (!tag.equals("Name"))
throw new RuntimeException("Tag " + tag + " not allowed.");
if (xmlLast != null)
throw new RuntimeException("Nested tags are not allowed.");
xmlLast = new HashMap(h);
xmlLast.put("Name", "");
}
public void text(String str) {
if (xmlLast == null)
return;
String name = (String)xmlLast.get("Name");
name += str;
xmlLast.put("Name", name);
}
}
| 12,926
|
Java
|
.java
| 318
| 31.226415
| 124
| 0.593902
|
SemanticBeeng/jpdfbookmarks
| 41
| 5
| 2
|
GPL-3.0
|
9/4/2024, 7:11:02 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 12,926
|
1,895,966
|
SWGResourceList.java
|
twistedatrocity_SWGAide-NGE/src/main/java/swg/crafting/resources/SWGResourceList.java
|
package swg.crafting.resources;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import swg.model.SWGCGalaxy;
import swg.tools.ZString;
/**
* This type is a light-weight convenience container for any kind of resource
* objects. This type implements {@link List} and it can contain instances of
* {@link SWGKnownResource} and {@link SWGMutableResource}, or a mix of the two.
* Utility methods are provided that allow for manipulation of a list of this
* type, making it simpler to locate the desired resource(s), etc. See section
* named <I>Limitations</I>.
* <P>
* This type provides thread safe methods implemented with the least intrusive
* synchronization. Methods that are non-intrusive (such as {@link #size()}), or
* methods that test a condition and return a {@code boolean} (such as
* {@link #contains(Object)}), or the methods getXX and sublistXX, are not
* thread safe. However, there is no guarantee that return values from such
* methods are valid in the case concurrent threads change the content.
* <P>
* A list of this type <B>must never be stored</B> persistently. See
* {@link SWGResource} for a complete discussion on resources and the very
* strict rules for handling resource objects. For storage, rather use
* {@link SWGResourceSet}.
* <P>
* <B>LIMITATIONS</B>
* <P>
* This implementation does not implement all methods for {@link List}, these
* methods are clearly documented.
* <P>
* This type does not robustly guard against doubles but executes some plain
* checks. More specifically, equality is just determined by reference identity.
* Only adder methods also checks the SWGCraft ID. However, see
* {@link #indexOf(SWGResource, Comparator)}.
* <P>
* As mentioned, this implementation provides a limited synchronization, there
* is no guarantee against concurrent changes, between consecutive calls. This
* should not cause a problem since this type is thought to be used in very
* narrow, controlled scopes.
*
* @author <a href="mailto:[email protected]">Simon Gronlund</a> aka
* Chimaera.Zimoon
*/
public final class SWGResourceList implements List<SWGResource> {
/**
* An immutable constant for an empty list, {@link Collections#emptyList()}.
*/
public static final SWGResourceList EMPTY = new SWGResourceList(0);
static {
EMPTY.storage = Collections.emptyList();
}
/**
* The internal storage for resources.
*/
private List<SWGResource> storage;
/**
* Creates an empty list for resources, with an initial capacity of 10.
*/
public SWGResourceList() {
this(10);
}
/**
* Creates a list containing the resource objects in the provided
* collection. No duplicates nor {@code null} elements are added to this
* instance but are silently ignored.
*
* @param resources
* the collection of resources to add to this instance. Elements
* that are {@code null} or duplicates are ignored.
* @throws IllegalArgumentException
* if some property of an element prevents it from being added
* to this list
*/
public SWGResourceList(Collection<SWGResource> resources) {
this((int) (resources.size() * 1.2));
addAll(resources);
}
/**
* Creates an empty list for resources with the specified initial capacity.
*
* @param initialCapacity
* the initial capacity of the list
* @throws IllegalArgumentException
* if the specified initial capacity is negative
*/
public SWGResourceList(int initialCapacity) {
storage = new ArrayList<SWGResource>(initialCapacity);
}
/**
* Unimplemented.
*
* @throws UnsupportedOperationException
* if this method is called
*/
public void add(int index, SWGResource element) {
throw new UnsupportedOperationException();
}
/**
* Adds an element to this instance. If the element is {@code null}, or if
* the element has its SWGCraft ID set and itself or another object with
* that ID already exists in this instance, it is ignored and {@code false}
* is returned. For further documentation...
*
* @see java.util.List#add(java.lang.Object)
*/
public boolean add(SWGResource e) {
if (e == null || (e.id() > 0 && getByID(e.id()) != null))
return false;
synchronized (storage) {
if (!storage.contains(e))
return storage.add(e);
}
return false;
}
/**
* Adds all elements in the specified collection to this instance. If an
* element is {@code null}, or if the element has its SWGCraft ID set and
* itself or another object with that ID already exists in this instance, it
* is silently ignored. For further documentation...
*
* @see java.util.List#addAll(java.util.Collection)
*/
public boolean addAll(Collection<? extends SWGResource> c) {
boolean ret = false;
synchronized (storage) {
for (SWGResource resource : c) {
ret |= add(resource);
}
}
return ret;
}
/**
* Unimplemented.
*
* @throws UnsupportedOperationException
* if this method is called
*/
public boolean addAll(int index, Collection<? extends SWGResource> c) {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
* @see java.util.List#clear()
*/
public void clear() {
synchronized (storage) {
storage.clear();
}
}
/*
* (non-Javadoc)
* @see java.util.List#contains(java.lang.Object)
*/
public boolean contains(Object o) {
return storage.contains(o);
}
/**
* Unimplemented.
*
* @throws UnsupportedOperationException
* if this method is called
*/
public boolean containsAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
* @see java.util.List#get(int)
*/
public SWGResource get(int index) {
return storage.get(index);
}
/**
* Returns an instance of a resource identified by {@code swgcraftID}. The
* argument is a unique SWGCraft resource ID. If the requested instance is
* not contained in this list {@code null} is returned.
*
* @param swgcraftID
* a unique SWGCraft resource ID identifying the resource
* @return an instance of a resource, {@code null} if none is found
* @throws IllegalArgumentException
* if {@literal swgcraftID <= 0}
*/
public SWGResource getByID(long swgcraftID) {
if (swgcraftID <= 0)
throw new IllegalArgumentException("Invalid ID: " + swgcraftID);
for (SWGResource r : storage)
if (r.id() == swgcraftID)
return r;
return null;
}
/**
* Returns an instance of a resource identified by {@code name}
* <I>and </I> {@code galaxy}. A resource name is unique for its
* galaxy. The name must be a properly capitalized. If the requested
* instance is not contained in this list {@code null} is returned.
* <P>
* <B>Note: </B>If {@link SWGResource#id()} is known
* {@link #getByID(long)} is more efficient.
*
* @param name
* a proper, capitalized resource name
* @param galaxy
* a galaxy constant
* @return an instance of a resource identified by its name and galaxy,
* {@code null} if none is found
* @throws IllegalArgumentException
* if name is invalid
* @throws NullPointerException
* if an argument is {@code null}
*/
public SWGResource getByNameAndGalaxy(String name, SWGCGalaxy galaxy) {
if (galaxy == null || name == null)
throw new IllegalArgumentException("An argument is null");
if (name.length() < 3)
throw new IllegalArgumentException("Invalid name: " + name + ':'
+ galaxy);
for (SWGResource r : storage)
if (r.galaxy().equals(galaxy) && r.getName().equals(name))
return r;
return null;
}
/**
* Returns an instance of a resource identified by {@code name}
* <I>and </I> {@code type}. The risk for a doubled combination at
* another galaxy is negligible. The arguments must be a proper, capitalized
* resource name and a spawnable resource class. If the requested instance
* is not contained in this list {@code null} is returned.
* <P>
* <B>Note: </B>If {@link SWGResource#id()} is known
* {@link #getByID(long)} is more efficient. If galaxy is known it is a tad
* safer to use {@link #getByNameAndGalaxy(String, SWGCGalaxy)}.
*
* @param name
* a proper, capitalized resource name
* @param type
* a spawnable resource class
* @return an instance of a resource identified by its name and resource
* class, {@code null} if none is found
* @throws IllegalArgumentException
* if any of the arguments is invalid
* @throws NullPointerException
* if any of the arguments is {@code null}
*/
public SWGResource getByNameAndType(String name, SWGResourceClass type) {
if (name.length() < 3)
throw new IllegalArgumentException("Invalid name: " + name + ':'
+ type);
if (!type.isSpawnable() && !type.isSpaceOrRecycled())
throw new IllegalArgumentException("Not spawnable: " + type + ':'
+ name);
for (SWGResource r : storage)
if (r.rc() == type && r.getName().equals(name))
return r;
return null;
}
/*
* (non-Javadoc)
* @see java.util.List#indexOf(java.lang.Object)
*/
public int indexOf(Object o) {
if (o instanceof SWGResource) {
return storage.indexOf(o);
}
return -1;
}
/**
* Returns the index of the first occurrence of the specified resource in
* this list using the specified {@link Comparator} to determine equality.
* If this list does not contain the element -1 is returned.
*
* @param o
* the resource object to find the index for
* @param comp
* the comparator with which to establish identity
* @return the index of the specified resource in this list, or -1
* @throws NullPointerException
* if an argument is {@code null}
*/
public int indexOf(SWGResource o, Comparator<SWGResource> comp) {
for (int i = 0; i < storage.size(); ++i) {
SWGResource r = storage.get(i);
if (r == o || comp.compare(r, o) == 0)
return i;
}
return -1;
}
/*
* (non-Javadoc)
* @see java.util.List#isEmpty()
*/
public boolean isEmpty() {
return storage.isEmpty();
}
/*
* (non-Javadoc)
* @see java.util.List#iterator()
*/
public Iterator<SWGResource> iterator() {
return storage.iterator();
}
/**
* Unimplemented.
*
* @throws UnsupportedOperationException
* if this method is called
*/
public int lastIndexOf(Object o) {
throw new UnsupportedOperationException();
}
/**
* Unimplemented.
*
* @throws UnsupportedOperationException
* if this method is called
*/
public ListIterator<SWGResource> listIterator() {
throw new UnsupportedOperationException();
}
/**
* Unimplemented.
*
* @throws UnsupportedOperationException
* if this method is called
*/
public ListIterator<SWGResource> listIterator(int index) {
throw new UnsupportedOperationException();
}
/**
* Prohibits deserialization.
*
* @param ois
* the object stream
* @throws NotSerializableException
* if anybody tries to deserialize this object
*/
private void readObject(ObjectInputStream ois)
throws NotSerializableException {
// It should be impossible to get here since this class does not
// implement the Serializable interface, but ...
throw new NotSerializableException("This container is not for storage");
}
/*
* (non-Javadoc)
* @see java.util.List#remove(int)
*/
public SWGResource remove(int index) {
synchronized (storage) {
return storage.remove(index);
}
}
/*
* (non-Javadoc)
* @see java.util.List#remove(java.lang.Object)
*/
public boolean remove(Object o) {
synchronized (storage) {
return storage.remove(o);
}
}
/*
* (non-Javadoc)
* @see java.util.List#removeAll(java.util.Collection)
*/
public boolean removeAll(Collection<?> c) {
synchronized (storage) {
return storage.removeAll(c);
}
}
/*
* (non-Javadoc)
* @see java.util.List#retainAll(java.util.Collection)
*/
public boolean retainAll(Collection<?> c) {
synchronized (storage) {
return storage.retainAll(c);
}
}
/*
* (non-Javadoc)
* @see java.util.List#set(int, java.lang.Object)
*/
public SWGResource set(int index, SWGResource element) {
if (element == null)
throw new NullPointerException("Null elements are not allowed");
synchronized (storage) {
return storage.set(index, element);
}
}
/*
* (non-Javadoc)
* @see java.util.List#size()
*/
public int size() {
return storage.size();
}
/**
* Unimplemented.
*
* @throws UnsupportedOperationException
* if this method is called
*/
public List<SWGResource> subList(int fromIndex, int toIndex) {
throw new UnsupportedOperationException();
}
/**
* Returns from this list a sublist of resources that are subclasses of the
* argument. More formally, the elements contained in the returned list are
* resources of which each instance's type field equals or is a subclass of
* the argument.
* <P>
* The argument can be obtained from {@link SWGResourceClass} by ID, name,
* or token.
*
* @param type
* the resources class to filter through
* @return a list of resources which type is determined by the argument, or
* an empty list
* @throws NullPointerException
* if the argument is {@code null}
*/
public SWGResourceList sublistByResourceClass(SWGResourceClass type) {
Class<? extends SWGResourceClass> typeCls = type.getClass();
SWGResourceList result = new SWGResourceList(size());
for (SWGResource r : storage) {
if (typeCls.isAssignableFrom(r.rc().getClass()))
result.storage.add(r); // surpass our checkpoints
}
if (result.storage.isEmpty())
return EMPTY;
return result;
}
/*
* (non-Javadoc)
* @see java.util.List#toArray()
*/
public Object[] toArray() {
return storage.toArray();
}
/*
* (non-Javadoc)
* @see java.util.List#toArray(T[])
*/
public <T> T[] toArray(T[] a) {
return storage.toArray(a);
}
/**
* Convenience method that returns this instance unless it is empty. If this
* instance is empty {@link #EMPTY} is returned.
*
* @return this instance or {@link #EMPTY}
*/
public SWGResourceList toReturn() {
return this.isEmpty()
? EMPTY
: this;
}
@Override
public String toString() {
ZString z = new ZString(getClass().getSimpleName());
return z.app(storage.toString()).toString();
}
/**
* Prohibits serialization.
*
* @param ois
* the object stream
* @throws NotSerializableException
* if anybody tries to serialize this object
*/
private void writeObject(ObjectOutputStream ois)
throws NotSerializableException {
// It should be impossible to get here since this class does not
// implement the Serializable interface, but ...
throw new NotSerializableException("This container is not for storage");
}
}
| 16,976
|
Java
|
.java
| 485
| 28.496907
| 80
| 0.624901
|
twistedatrocity/SWGAide-NGE
| 11
| 6
| 8
|
GPL-2.0
|
9/4/2024, 8:22:18 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 16,976
|
4,212,327
|
InvalidLogLevelException.java
|
michele-loreti_jResp/core/org.cmg.jresp.pastry/pastry-2.1/src/rice/environment/logging/InvalidLogLevelException.java
|
/*******************************************************************************
"FreePastry" Peer-to-Peer Application Development Substrate
Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute
for Software Systems. 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 Rice University (RICE), Max Planck Institute for Software
Systems (MPI-SWS) 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 RICE, MPI-SWS and the contributors on an "as is"
basis, without any representations or warranties of any kind, express or implied
including, but not limited to, representations or warranties of
non-infringement, merchantability or fitness for a particular purpose. In no
event shall RICE, MPI-SWS 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.
*******************************************************************************/
/*
* Created on Jun 6, 2005
*/
package rice.environment.logging;
/**
* @author Jeff Hoye
*/
public class InvalidLogLevelException extends RuntimeException {
/**
* @param arg0
*/
public InvalidLogLevelException(String key, String val) {
super(val+" is not an apropriate value for "+key+". Must be an integer or ALL,OFF,SEVERE,WARNING,INFO,CONFIG,FINE,FINER,FINEST");
}
}
| 2,283
|
Java
|
.java
| 43
| 51.069767
| 133
| 0.747085
|
michele-loreti/jResp
| 2
| 0
| 5
|
EPL-1.0
|
9/5/2024, 12:05:57 AM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 2,283
|
1,820,575
|
FMarca.java
|
cams7_erp/freedom/src/main/java/org/freedom/modulos/std/view/frame/crud/plain/FMarca.java
|
/**
* @version 11/02/2002 <BR>
* @author Setpoint Informática Ltda./Fernando Oliveira da Silva <BR>
*
* Projeto: Freedom <BR>
*
* Pacote: org.freedom.modulos.std <BR>
* Classe: @(#)FMarca.java <BR>
*
* Este arquivo é parte do sistema Freedom-ERP, o Freedom-ERP é um software livre; você pode redistribui-lo e/ou <BR>
* modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação do Software Livre (FSF); <BR>
* na versão 2 da Licença, ou (na sua opnião) qualquer versão. <BR>
* Este programa é distribuido na esperança que possa ser util, mas SEM NENHUMA GARANTIA; <BR>
* sem uma garantia implicita de ADEQUAÇÂO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. <BR>
* Veja a Licença Pública Geral GNU para maiores detalhes. <BR>
* Você deve ter recebido uma cópia da Licença Pública Geral GNU junto com este programa, se não, <BR>
* escreva para a Fundação do Software Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA <BR>
* <BR>
*
* Comentários sobre a classe...
*
*/
package org.freedom.modulos.std.view.frame.crud.plain;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.freedom.infra.functions.StringFunctions;
import org.freedom.library.component.ImprimeOS;
import org.freedom.library.functions.Funcoes;
import org.freedom.library.persistence.ListaCampos;
import org.freedom.library.swing.component.JTextFieldPad;
import org.freedom.library.swing.frame.FDados;
import org.freedom.library.type.TYPE_PRINT;
import org.freedom.modulos.std.view.dialog.report.DLRMarca;
public class FMarca extends FDados implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextFieldPad txtCodMarca = new JTextFieldPad( JTextFieldPad.TP_STRING, 6, 0 );
private JTextFieldPad txtDescMarca = new JTextFieldPad( JTextFieldPad.TP_STRING, 40, 0 );
private JTextFieldPad txtSiglaMarca = new JTextFieldPad( JTextFieldPad.TP_STRING, 20, 0 );
public FMarca() {
super();
setTitulo( "Cadastro de marcas de produtos" );
setAtribos( 50, 50, 370, 125 );
adicCampo( txtCodMarca, 7, 20, 70, 20, "CodMarca", "Cód.marca", ListaCampos.DB_PK, true );
adicCampo( txtDescMarca, 80, 20, 190, 20, "DescMarca", "Descrição da marca", ListaCampos.DB_SI, true );
adicCampo( txtSiglaMarca, 273, 20, 70, 20, "SiglaMarca", "Sigla", ListaCampos.DB_SI, false );
setListaCampos( false, "MARCA", "EQ" );
btImp.addActionListener( this );
btPrevimp.addActionListener( this );
lcCampos.setQueryInsert( false );
setImprimir( true );
}
public void actionPerformed( ActionEvent evt ) {
if ( evt.getSource() == btPrevimp ) {
imprimir( TYPE_PRINT.VIEW );
}
else if ( evt.getSource() == btImp )
imprimir( TYPE_PRINT.PRINT);
super.actionPerformed( evt );
}
private void imprimir( TYPE_PRINT bVisualizar ) {
ImprimeOS imp = new ImprimeOS( "", con );
int linPag = imp.verifLinPag() - 1;
imp.montaCab();
imp.setTitulo( "Relatório de marcas" );
DLRMarca dl = new DLRMarca();
dl.setVisible( true );
if ( dl.OK == false ) {
dl.dispose();
return;
}
String sSQL = "SELECT CODMARCA,DESCMARCA,SIGLAMARCA FROM EQMARCA ORDER BY " + dl.getValor();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement( sSQL );
rs = ps.executeQuery();
imp.limpaPags();
while ( rs.next() ) {
if ( imp.pRow() == 0 ) {
imp.impCab( 80, false );
imp.say( imp.pRow() + 0, 0, "" + imp.normal() );
imp.say( imp.pRow() + 0, 0, "" );
imp.say( imp.pRow() + 0, 2, "Cód.marca" );
imp.say( imp.pRow() + 0, 20, "Descrição da marca" );
imp.say( imp.pRow() + 0, 60, "Sigla" );
imp.say( imp.pRow() + 1, 0, "" + imp.normal() );
imp.say( imp.pRow() + 0, 0, StringFunctions.replicate( "-", 79 ) );
}
imp.say( imp.pRow() + 1, 0, "" + imp.normal() );
imp.say( imp.pRow() + 0, 2, rs.getString( "CodMarca" ) );
imp.say( imp.pRow() + 0, 20, rs.getString( "DescMarca" ) );
imp.say( imp.pRow() + 0, 60, rs.getString( "SiglaMarca" ) != null ? rs.getString( "SiglaMarca" ) : "" );
if ( imp.pRow() >= linPag ) {
imp.say( imp.pRow() + 1, 0, "" + imp.normal() );
imp.say( imp.pRow() + 0, 0, StringFunctions.replicate( "=", 79 ) );
imp.incPags();
imp.eject();
}
}
imp.say( imp.pRow() + 1, 0, "" + imp.normal() );
imp.say( imp.pRow() + 0, 0, StringFunctions.replicate( "=", 79 ) );
imp.eject();
imp.fechaGravacao();
// rs.close();
// ps.close();
con.commit();
dl.dispose();
} catch ( SQLException err ) {
Funcoes.mensagemErro( this, "Erro consulta tabela de marcas!\n" + err.getMessage(), true, con, err );
}
if ( bVisualizar==TYPE_PRINT.VIEW ) {
imp.preview( this );
}
else {
imp.print();
}
}
}
| 5,009
|
Java
|
.java
| 121
| 37.859504
| 128
| 0.667632
|
cams7/erp
| 12
| 13
| 0
|
GPL-3.0
|
9/4/2024, 8:19:45 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 4,974
|
1,320,199
|
A.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/InferTypeArguments/testCuNestedCells1/in/A.java
|
package p;
class A {
void m() {
Cell c= new Cell();
c.put("X");
Cell nested= new Cell();
nested.put(c);
}
}
| 119
|
Java
|
.java
| 9
| 11
| 26
| 0.577982
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 119
|
1,247,605
|
WorkerThread.java
|
Cloudslab_FogBus/Android-app/New-BLE/Java-src/android/support/annotation/WorkerThread.java
|
package android.support.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE})
@Retention(RetentionPolicy.CLASS)
public @interface WorkerThread {
}
| 341
|
Java
|
.java
| 9
| 36.666667
| 72
| 0.860606
|
Cloudslab/FogBus
| 39
| 17
| 0
|
GPL-2.0
|
9/4/2024, 7:28:16 PM (Europe/Amsterdam)
| false
| true
| false
| true
| false
| true
| true
| true
| 341
|
1,312,745
|
ShowActionGroup.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/ShowActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.actions;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.part.Page;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart;
/**
* Action group that adds the show actions to a context menu and the action bar's navigate menu.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*
* @noextend This class is not intended to be subclassed by clients.
* @deprecated As of 3.5, got replaced by generic Navigate > Show In >
*/
@Deprecated
public class ShowActionGroup extends ActionGroup {
private boolean fIsPackageExplorer;
private IWorkbenchSite fSite;
private ShowInPackageViewAction fShowInPackagesViewAction;
/**
* Creates a new <code>ShowActionGroup</code>. The action requires
* that the selection provided by the page's selection provider is of type
* <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param page the page that owns this action group
*/
public ShowActionGroup(Page page) {
this(page.getSite());
}
/**
* Creates a new <code>ShowActionGroup</code>. The action requires
* that the selection provided by the part's selection provider is of type
* <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param part the view part that owns this action group
*/
public ShowActionGroup(IViewPart part) {
this(part.getSite());
fIsPackageExplorer= part instanceof PackageExplorerPart;
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
* @param part the Java editor
*
* @noreference This constructor is not intended to be referenced by clients.
*/
public ShowActionGroup(JavaEditor part) {
fShowInPackagesViewAction= new ShowInPackageViewAction(part);
fShowInPackagesViewAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_IN_PACKAGE_VIEW);
part.setAction("ShowInPackageView", fShowInPackagesViewAction); //$NON-NLS-1$
initialize(part.getSite(), true);
}
private ShowActionGroup(IWorkbenchSite site) {
fShowInPackagesViewAction= new ShowInPackageViewAction(site);
fShowInPackagesViewAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_IN_PACKAGE_VIEW);
initialize(site , false);
}
private void initialize(IWorkbenchSite site, boolean isJavaEditor) {
fSite= site;
ISelectionProvider provider= fSite.getSelectionProvider();
ISelection selection= provider.getSelection();
fShowInPackagesViewAction.update(selection);
if (!isJavaEditor) {
provider.addSelectionChangedListener(fShowInPackagesViewAction);
}
}
@Override
public void fillActionBars(IActionBars actionBar) {
super.fillActionBars(actionBar);
setGlobalActionHandlers(actionBar);
}
@Override
public void fillContextMenu(IMenuManager menu) {
super.fillContextMenu(menu);
if (!fIsPackageExplorer) {
appendToGroup(menu, fShowInPackagesViewAction);
}
}
/*
* @see ActionGroup#dispose()
*/
@Override
public void dispose() {
ISelectionProvider provider= fSite.getSelectionProvider();
provider.removeSelectionChangedListener(fShowInPackagesViewAction);
super.dispose();
}
private void setGlobalActionHandlers(IActionBars actionBar) {
if (!fIsPackageExplorer)
actionBar.setGlobalActionHandler(JdtActionConstants.SHOW_IN_PACKAGE_VIEW, fShowInPackagesViewAction);
}
private void appendToGroup(IMenuManager menu, IAction action) {
if (action.isEnabled())
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, action);
}
}
| 4,500
|
Java
|
.java
| 120
| 35.05
| 104
| 0.767714
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 4,500
|
1,748,823
|
ResourcesPanel.java
|
herbiehp_unicenta/src-pos/com/openbravo/pos/admin/ResourcesPanel.java
|
// uniCenta oPOS - Touch Friendly Point Of Sale
// Copyright (c) 2009-2014 uniCenta & previous Openbravo POS works
// http://www.unicenta.com
//
// This file is part of uniCenta oPOS
//
// uniCenta oPOS 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.
//
// uniCenta oPOS is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with uniCenta oPOS. If not, see <http://www.gnu.org/licenses/>.
package com.openbravo.pos.admin;
import com.openbravo.data.gui.ListCellRendererBasic;
import com.openbravo.data.loader.ComparatorCreator;
import com.openbravo.data.loader.TableDefinition;
import com.openbravo.data.loader.Vectorer;
import com.openbravo.data.user.EditorRecord;
import com.openbravo.data.user.ListProvider;
import com.openbravo.data.user.ListProviderCreator;
import com.openbravo.data.user.SaveProvider;
import com.openbravo.pos.forms.AppLocal;
import com.openbravo.pos.forms.DataLogicSystem;
import com.openbravo.pos.panels.JPanelTable;
import javax.swing.ListCellRenderer;
/**
*
* @author adrianromero
*/
public class ResourcesPanel extends JPanelTable {
private TableDefinition tresources;
private ResourcesView jeditor;
/** Creates a new instance of JPanelResources */
public ResourcesPanel() {
}
/**
*
*/
protected void init() {
DataLogicAdmin dlAdmin = (DataLogicAdmin) app.getBean("com.openbravo.pos.admin.DataLogicAdmin");
tresources = dlAdmin.getTableResources();
jeditor = new ResourcesView(dirty);
}
/**
*
* @return
*/
@Override
public boolean deactivate() {
if (super.deactivate()) {
DataLogicSystem dlSystem = (DataLogicSystem) app.getBean("com.openbravo.pos.forms.DataLogicSystem");
dlSystem.resetResourcesCache();
return true;
} else {
return false;
}
}
/**
*
* @return
*/
public ListProvider getListProvider() {
return new ListProviderCreator(tresources);
}
/**
*
* @return
*/
public SaveProvider getSaveProvider() {
return new SaveProvider(tresources);
}
/**
*
* @return
*/
@Override
public Vectorer getVectorer() {
return tresources.getVectorerBasic(new int[] {1});
}
/**
*
* @return
*/
@Override
public ComparatorCreator getComparatorCreator() {
return tresources.getComparatorCreator(new int[] {1, 2});
}
/**
*
* @return
*/
@Override
public ListCellRenderer getListCellRenderer() {
return new ListCellRendererBasic(tresources.getRenderStringBasic(new int[] {1}));
}
/**
*
* @return
*/
public EditorRecord getEditor() {
return jeditor;
}
/**
*
* @return
*/
public String getTitle() {
return AppLocal.getIntString("Menu.Resources");
}
}
| 3,478
|
Java
|
.java
| 116
| 24.396552
| 124
| 0.665761
|
herbiehp/unicenta
| 17
| 13
| 0
|
GPL-3.0
|
9/4/2024, 8:17:22 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 3,478
|
2,687,180
|
StorageProfileFilter.java
|
kaltura_KalturaGeneratedAPIClientsJava/src/main/java/com/kaltura/client/types/StorageProfileFilter.java
|
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2023 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.types;
import com.google.gson.JsonObject;
import com.kaltura.client.Params;
import com.kaltura.client.utils.request.MultiRequestBuilder;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
@MultiRequestBuilder.Tokenizer(StorageProfileFilter.Tokenizer.class)
public class StorageProfileFilter extends StorageProfileBaseFilter {
public interface Tokenizer extends StorageProfileBaseFilter.Tokenizer {
}
public StorageProfileFilter() {
super();
}
public StorageProfileFilter(JsonObject jsonObject) throws APIException {
super(jsonObject);
}
public Params toParams() {
Params kparams = super.toParams();
kparams.add("objectType", "KalturaStorageProfileFilter");
return kparams;
}
}
| 2,202
|
Java
|
.java
| 54
| 39.111111
| 102
| 0.631086
|
kaltura/KalturaGeneratedAPIClientsJava
| 6
| 11
| 1
|
AGPL-3.0
|
9/4/2024, 10:06:24 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 2,202
|
2,336,836
|
MusicShopOntology.java
|
mihaimaruseac_JADE-ARIA/src/examples/content/mso/MusicShopOntology.java
|
/**
* ***************************************************************
* JADE - Java Agent DEvelopment Framework is a framework to develop
* multi-agent systems in compliance with the FIPA specifications.
* Copyright (C) 2000 CSELT S.p.A.
*
* GNU Lesser General Public License
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation,
* version 2.1 of the License.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
* **************************************************************
*/
package examples.content.mso;
import jade.content.onto.OntologyUtils;
import jade.content.onto.BeanOntology;
import jade.content.onto.BeanOntologyException;
import jade.content.onto.Ontology;
import examples.content.eco.ECommerceOntology;
import examples.content.mso.elements.CD;
import examples.content.mso.elements.Single;
import examples.content.mso.elements.Track;
/**
* Ontology containing music related concepts.
*
* @author Giovanni Caire - TILAB
*/
public class MusicShopOntology extends BeanOntology {
private static final long serialVersionUID = 1L;
// NAME
public static final String ONTOLOGY_NAME = "Music-shop-ontology";
// The singleton instance of this ontology
private static Ontology INSTANCE;
public synchronized final static Ontology getInstance() throws BeanOntologyException {
if (INSTANCE == null) {
INSTANCE = new MusicShopOntology();
}
return INSTANCE;
}
/**
* Constructor
*
* @throws BeanOntologyException
*/
private MusicShopOntology() throws BeanOntologyException {
super(ONTOLOGY_NAME, ECommerceOntology.getInstance());
add(Track.class);
add(CD.class);
add(Single.class);
}
public static void main(String[] args) throws Exception {
Ontology onto = getInstance();
OntologyUtils.exploreOntology(onto);
onto = ECommerceOntology.getInstance();
OntologyUtils.exploreOntology(onto);
}
}
| 2,498
|
Java
|
.java
| 68
| 33.352941
| 88
| 0.715824
|
mihaimaruseac/JADE-ARIA
| 8
| 16
| 0
|
LGPL-2.1
|
9/4/2024, 9:07:58 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 2,498
|
1,940,601
|
LeafPattern.java
|
BitCurator_bitcurator-redact-pdf/src/main/java/org/docopt/LeafPattern.java
|
package org.docopt;
import static org.docopt.Python.bool;
import static org.docopt.Python.in;
import static org.docopt.Python.list;
import static org.docopt.Python.plus;
import static org.docopt.Python.repr;
import java.util.List;
/**
* Leaf/terminal node of a pattern tree.
*/
abstract class LeafPattern extends Pattern {
static class SingleMatchResult {
private final Integer position;
private final LeafPattern match;
public SingleMatchResult(final Integer position, final LeafPattern match) {
this.position = position;
this.match = match;
}
public Integer getPosition() {
return position;
}
public LeafPattern getMatch() {
return match;
}
@Override
public String toString() {
return String.format("%s(%d, %s)", getClass().getSimpleName(),
position, match);
}
}
private final String name;
private Object value;
public LeafPattern(final String name, final Object value) {
this.name = name;
this.value = value;
}
public LeafPattern(final String name) {
this(name, null);
}
@Override
public String toString() {
return String.format("%s(%s, %s)", getClass().getSimpleName(),
repr(name), repr(value));
}
@Override
protected final List<Pattern> flat(final Class<?>... types) {
// >>> [self] if not types or type(self) in types else []
{
if (!bool(types) || in(getClass(), types)) {
return list((Pattern) this);
}
return list();
}
}
@Override
protected MatchResult match(final List<LeafPattern> left,
List<LeafPattern> collected) {
// >>> collected = [] if collected is None else collected
if (collected == null) {
collected = list();
}
Integer pos;
LeafPattern match;
// >>> pos, match = self.single_match(left)
{
final SingleMatchResult m = singleMatch(left);
pos = m.getPosition();
match = m.getMatch();
}
if (match == null) {
return new MatchResult(false, left, collected);
}
List<LeafPattern> left_;
// >>> left_ = left[:pos] + left[pos + 1:]
{
left_ = list();
left_.addAll(left.subList(0, pos));
if ((pos + 1) < left.size()) {
left_.addAll(left.subList(pos + 1, left.size()));
}
}
List<LeafPattern> sameName;
// >>> same_name = [a for a in collected if a.name == self.name]
{
sameName = list();
for (final LeafPattern a : collected) {
if (name.equals(a.getName())) {
sameName.add(a);
}
}
}
Object increment;
if ((value instanceof Integer) || (value instanceof List)) {
if (value instanceof Integer) {
increment = 1;
}
else {
final Object v = match.getValue();
increment = (v instanceof String) ? list(v) : v;
}
if (sameName.isEmpty()) {
match.setValue(increment);
return new MatchResult(true, left_,
plus(collected, list(match)));
}
// >>> same_name[0].value += increment
{
final LeafPattern p = sameName.get(0);
final Object v = p.getValue();
if (v instanceof Integer) {
final Integer a = (Integer) v;
final Integer b = (Integer) increment;
p.setValue(a + b);
}
else if (v instanceof List) {
@SuppressWarnings("unchecked")
final List<LeafPattern> a = (List<LeafPattern>) v;
@SuppressWarnings("unchecked")
final List<LeafPattern> b = (List<LeafPattern>) increment;
a.addAll(b);
}
}
// TODO: Should collected be copied to a new list?
return new MatchResult(true, left_, collected);
}
return new MatchResult(true, left_, plus(collected, list(match)));
}
protected abstract SingleMatchResult singleMatch(List<LeafPattern> left);
public String getName() {
return name;
}
public Object getValue() {
return value;
}
public void setValue(final Object value) {
this.value = value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (getClass() != obj.getClass()) {
return false;
}
final LeafPattern other = (LeafPattern) obj;
if (name == null) {
if (other.name != null) {
return false;
}
}
else if (!name.equals(other.name)) {
return false;
}
if (value == null) {
if (other.value != null) {
return false;
}
}
else if (!value.equals(other.value)) {
return false;
}
return true;
}
}
| 4,496
|
Java
|
.java
| 173
| 22.427746
| 77
| 0.663399
|
BitCurator/bitcurator-redact-pdf
| 14
| 1
| 0
|
GPL-3.0
|
9/4/2024, 8:24:04 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 4,496
|
1,096,133
|
UnaryComparisonOperatorNode.java
|
brunoribeiro_sql-parser/src/main/java/com/akiban/sql/parser/UnaryComparisonOperatorNode.java
|
/**
* Copyright © 2012 Akiban Technologies, Inc. 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
*
* This program may also be available under different license terms.
* For more information, see www.akiban.com or contact
* [email protected].
*
* Contributors:
* Akiban Technologies, Inc.
*/
/* The original from which this derives bore the following: */
/*
Derby - Class org.apache.derby.impl.sql.compile.UnaryComparisonOperatorNode
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.akiban.sql.parser;
/**
* This node is the superclass for all unary comparison operators, such as is null
* and is not null.
*
*/
public abstract class UnaryComparisonOperatorNode extends UnaryOperatorNode
{
}
| 1,682
|
Java
|
.java
| 41
| 38.268293
| 83
| 0.776211
|
brunoribeiro/sql-parser
| 43
| 158
| 2
|
EPL-1.0
|
9/4/2024, 7:11:02 PM (Europe/Amsterdam)
| true
| true
| true
| true
| false
| true
| true
| true
| 1,682
|
4,421,907
|
PivotBySplit.java
|
tue-alga_UncertaintyTreemaps/code/StableTreemap/src/TreeMapGenerator/Pivot/PivotBySplit.java
|
package TreeMapGenerator.Pivot;
import java.util.List;
import treemap.dataStructure.DataMap;
/**
*
* @author max
*/
public class PivotBySplit extends Pivot {
@Override
public int findPivotNode(List<DataMap> dataMapList) {
double totalSize = getSize(dataMapList);
double bestDifference = Double.MAX_VALUE;
int bestIndex = 0;
for (int i = 0; i < dataMapList.size(); i++) {
double leftSide = getSize(dataMapList.subList(0, i));
double difference = totalSize/2 - leftSide;
if (Math.abs(difference) < Math.abs(bestDifference)) {
bestIndex = i;
bestDifference = difference;
}
}
return bestIndex;
}
@Override
public String getParamaterDescription() {
return "";
}
}
| 830
|
Java
|
.java
| 28
| 22.535714
| 66
| 0.620907
|
tue-alga/UncertaintyTreemaps
| 2
| 0
| 0
|
GPL-3.0
|
9/5/2024, 12:12:40 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 830
|
1,165,421
|
LocationCheck.java
|
netizen539_civcraft/civcraft/src/com/avrgaming/civcraft/randomevents/components/LocationCheck.java
|
package com.avrgaming.civcraft.randomevents.components;
import java.util.List;
import com.avrgaming.civcraft.cache.PlayerLocationCache;
import com.avrgaming.civcraft.main.CivGlobal;
import com.avrgaming.civcraft.main.CivLog;
import com.avrgaming.civcraft.object.Resident;
import com.avrgaming.civcraft.randomevents.RandomEventComponent;
import com.avrgaming.civcraft.util.BlockCoord;
public class LocationCheck extends RandomEventComponent {
@Override
public void process() {
}
public boolean onCheck() {
String varname = this.getString("varname");
String locString = this.getParent().componentVars.get(varname);
if (locString == null) {
CivLog.warning("Couldn't get var name:"+varname+" for location check component.");
return false;
}
BlockCoord bcoord = new BlockCoord(locString);
double radiusSquared = 2500.0; /* 50 block radius */
List<PlayerLocationCache> cache = PlayerLocationCache.getNearbyPlayers(bcoord, radiusSquared);
for (PlayerLocationCache pc : cache) {
Resident resident = CivGlobal.getResident(pc.getName());
if (resident.getTown() == this.getParentTown()) {
return true;
}
}
return false;
}
}
| 1,184
|
Java
|
.java
| 31
| 34.903226
| 96
| 0.783688
|
netizen539/civcraft
| 35
| 62
| 7
|
GPL-2.0
|
9/4/2024, 7:20:46 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 1,184
|
1,315,433
|
A_testLambda3_out.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda3_out.java
|
package p;
public interface A {
public abstract void newName(String s);
}
class AImpl {
A i1 = (String s) -> System.out.println();
A i2 = (s) -> {
System.out.println();
};
A i3 = new A() {
@Override
public void newName(String s) {
System.out.println();
}
};
private void foo() {
A i4 = s -> {
System.out.println();
};
}
}
| 354
|
Java
|
.java
| 21
| 14.333333
| 43
| 0.614679
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 354
|
400,945
|
BankSearchResource.java
|
adorsys_open-banking-gateway/fintech-examples/fintech-api/src/main/java/de/adorsys/opba/fintech/api/resource/BankSearchResource.java
|
package de.adorsys.opba.fintech.api.resource;
import de.adorsys.opba.fintech.api.resource.generated.FinTechBankSearchApi;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BankSearchResource implements FinTechBankSearchApi {
}
| 271
|
Java
|
.java
| 6
| 43.833333
| 75
| 0.882129
|
adorsys/open-banking-gateway
| 246
| 93
| 132
|
AGPL-3.0
|
9/4/2024, 7:07:11 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 271
|
2,988,831
|
HomepageEditor.java
|
mgks_Chromium-Alt/app/src/main/java/org/chromium/chrome/browser/preferences/HomepageEditor.java
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.preferences;
import android.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.partnercustomizations.HomepageManager;
import org.chromium.chrome.browser.util.FeatureUtilities;
import org.chromium.components.url_formatter.UrlFormatter;
/**
* Provides the Java-UI for editing the homepage preference.
*/
public class HomepageEditor extends Fragment implements TextWatcher {
private HomepageManager mHomepageManager;
private EditText mHomepageUrlEdit;
private Button mSaveButton;
private Button mResetButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHomepageManager = HomepageManager.getInstance();
if (FeatureUtilities.isNewTabPageButtonEnabled()) {
getActivity().setTitle(R.string.options_startup_page_edit_title);
} else {
getActivity().setTitle(R.string.options_homepage_edit_title);
}
View v = inflater.inflate(R.layout.homepage_editor, container, false);
View scrollView = v.findViewById(R.id.scroll_view);
scrollView.getViewTreeObserver().addOnScrollChangedListener(
PreferenceUtils.getShowShadowOnScrollListener(v, v.findViewById(R.id.shadow)));
mHomepageUrlEdit = (EditText) v.findViewById(R.id.homepage_url_edit);
mHomepageUrlEdit.setText(HomepageManager.getHomepageUri());
mHomepageUrlEdit.addTextChangedListener(this);
mHomepageUrlEdit.requestFocus();
initializeSaveCancelResetButtons(v);
return v;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mSaveButton.setEnabled(true);
mResetButton.setEnabled(true);
}
@Override
public void afterTextChanged(Editable s) {
}
private void initializeSaveCancelResetButtons(View v) {
mResetButton = (Button) v.findViewById(R.id.homepage_reset);
mResetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHomepageManager.setPrefHomepageUseDefaultUri(true);
getActivity().finish();
}
});
if (mHomepageManager.getPrefHomepageUseDefaultUri()) {
mResetButton.setEnabled(false);
}
mSaveButton = (Button) v.findViewById(R.id.homepage_save);
mSaveButton.setEnabled(false);
mSaveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHomepageManager.setPrefHomepageCustomUri(
UrlFormatter.fixupUrl(mHomepageUrlEdit.getText().toString()));
mHomepageManager.setPrefHomepageUseDefaultUri(false);
getActivity().finish();
}
});
Button button = (Button) v.findViewById(R.id.homepage_cancel);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().finish();
}
});
}
}
| 3,752
|
Java
|
.java
| 89
| 34.393258
| 95
| 0.702273
|
mgks/Chromium-Alt
| 5
| 2
| 0
|
GPL-3.0
|
9/4/2024, 10:40:43 PM (Europe/Amsterdam)
| false
| true
| false
| true
| true
| true
| true
| true
| 3,752
|
214,581
|
LbMethod.java
|
CloudExplorer-Dev_CloudExplorer-Lite/framework/provider/lib/openstack/core/src/main/java/org/openstack4j/model/octavia/LbMethod.java
|
package org.openstack4j.model.octavia;
import com.fasterxml.jackson.annotation.JsonCreator;
/**
* Load Balancer Algorithm
*
* @author wei
*/
public enum LbMethod {
ROUND_ROBIN,
LEAST_CONNECTIONS,
SOURCE_IP;
@JsonCreator
public static LbMethod forValue(String value) {
if (value != null) {
for (LbMethod s : LbMethod.values()) {
if (s.name().equalsIgnoreCase(value)) {
return s;
}
}
}
return LbMethod.ROUND_ROBIN;
}
}
| 548
|
Java
|
.java
| 23
| 17.130435
| 55
| 0.588123
|
CloudExplorer-Dev/CloudExplorer-Lite
| 635
| 87
| 8
|
GPL-3.0
|
9/4/2024, 7:05:42 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 548
|
1,370,193
|
RecordComparator.java
|
BombusMod_BombusMod/src/main/java/javax/microedition/rms/RecordComparator.java
|
/*
* MicroEmulator
* Copyright (C) 2001 Bartek Teodorczyk <[email protected]>
*
* It is licensed under the following two licenses as alternatives:
* 1. GNU Lesser General Public License (the "LGPL") version 2.1 or any newer version
* 2. Apache License (the "AL") Version 2.0
*
* You may not use this file except in compliance with at least one of
* the above two licenses.
*
* You may obtain a copy of the LGPL at
* http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
*
* You may obtain a copy of the AL 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 LGPL or the AL for the specific language governing permissions and
* limitations.
*/
package javax.microedition.rms;
public interface RecordComparator
{
static final int EQUIVALENT = 0;
static final int FOLLOWS = 1;
static final int PRECEDES = -1;
int compare(byte[] rec1, byte[] rec2);
}
| 1,136
|
Java
|
.java
| 31
| 34.354839
| 88
| 0.72968
|
BombusMod/BombusMod
| 26
| 15
| 0
|
GPL-2.0
|
9/4/2024, 7:46:38 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 1,136
|
4,949,401
|
Loader.java
|
Dewep_IntranetEpitechV2/Android/android.support.v4/src/java/android/support/v4/content/Loader.java
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.content;
import android.content.Context;
import android.database.ContentObserver;
import android.os.Handler;
import android.support.v4.util.DebugUtils;
import java.io.FileDescriptor;
import java.io.PrintWriter;
/**
* Static library support version of the framework's {@link android.content.Loader}.
* Used to write apps that run on platforms prior to Android 3.0. When running
* on Android 3.0 or above, this implementation is still used; it does not try
* to switch to the framework's implementation. See the framework SDK
* documentation for a class overview.
*/
public class Loader<D> {
int mId;
OnLoadCompleteListener<D> mListener;
Context mContext;
boolean mStarted = false;
boolean mAbandoned = false;
boolean mReset = true;
boolean mContentChanged = false;
boolean mProcessingChange = false;
/**
* An implementation of a ContentObserver that takes care of connecting
* it to the Loader to have the loader re-load its data when the observer
* is told it has changed. You do not normally need to use this yourself;
* it is used for you by {@link android.support.v4.content.CursorLoader}
* to take care of executing an update when the cursor's backing data changes.
*/
public final class ForceLoadContentObserver extends ContentObserver {
public ForceLoadContentObserver() {
super(new Handler());
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
onContentChanged();
}
}
/**
* Interface that is implemented to discover when a Loader has finished
* loading its data. You do not normally need to implement this yourself;
* it is used in the implementation of {@link android.support.v4.app.LoaderManager}
* to find out when a Loader it is managing has completed so that this can
* be reported to its client. This interface should only be used if a
* Loader is not being used in conjunction with LoaderManager.
*/
public interface OnLoadCompleteListener<D> {
/**
* Called on the thread that created the Loader when the load is complete.
*
* @param loader the loader that completed the load
* @param data the result of the load
*/
public void onLoadComplete(Loader<D> loader, D data);
}
/**
* Stores away the application context associated with context. Since Loaders can be used
* across multiple activities it's dangerous to store the context directly.
*
* @param context used to retrieve the application context.
*/
public Loader(Context context) {
mContext = context.getApplicationContext();
}
/**
* Sends the result of the load to the registered listener. Should only be called by subclasses.
*
* Must be called from the process's main thread.
*
* @param data the result of the load
*/
public void deliverResult(D data) {
if (mListener != null) {
mListener.onLoadComplete(this, data);
}
}
/**
* @return an application context retrieved from the Context passed to the constructor.
*/
public Context getContext() {
return mContext;
}
/**
* @return the ID of this loader
*/
public int getId() {
return mId;
}
/**
* Registers a class that will receive callbacks when a load is complete.
* The callback will be called on the process's main thread so it's safe to
* pass the results to widgets.
*
* <p>Must be called from the process's main thread.
*/
public void registerListener(int id, OnLoadCompleteListener<D> listener) {
if (mListener != null) {
throw new IllegalStateException("There is already a listener registered");
}
mListener = listener;
mId = id;
}
/**
* Remove a listener that was previously added with {@link #registerListener}.
*
* Must be called from the process's main thread.
*/
public void unregisterListener(OnLoadCompleteListener<D> listener) {
if (mListener == null) {
throw new IllegalStateException("No listener register");
}
if (mListener != listener) {
throw new IllegalArgumentException("Attempting to unregister the wrong listener");
}
mListener = null;
}
/**
* Return whether this load has been started. That is, its {@link #startLoading()}
* has been called and no calls to {@link #stopLoading()} or
* {@link #reset()} have yet been made.
*/
public boolean isStarted() {
return mStarted;
}
/**
* Return whether this loader has been abandoned. In this state, the
* loader <em>must not</em> report any new data, and <em>must</em> keep
* its last reported data valid until it is finally reset.
*/
public boolean isAbandoned() {
return mAbandoned;
}
/**
* Return whether this load has been reset. That is, either the loader
* has not yet been started for the first time, or its {@link #reset()}
* has been called.
*/
public boolean isReset() {
return mReset;
}
/**
* Starts an asynchronous load of the Loader's data. When the result
* is ready the callbacks will be called on the process's main thread.
* If a previous load has been completed and is still valid
* the result may be passed to the callbacks immediately.
* The loader will monitor the source of
* the data set and may deliver future callbacks if the source changes.
* Calling {@link #stopLoading} will stop the delivery of callbacks.
*
* <p>This updates the Loader's internal state so that
* {@link #isStarted()} and {@link #isReset()} will return the correct
* values, and then calls the implementation's {@link #onStartLoading()}.
*
* <p>Must be called from the process's main thread.
*/
public final void startLoading() {
mStarted = true;
mReset = false;
mAbandoned = false;
onStartLoading();
}
/**
* Subclasses must implement this to take care of loading their data,
* as per {@link #startLoading()}. This is not called by clients directly,
* but as a result of a call to {@link #startLoading()}.
*/
protected void onStartLoading() {
}
/**
* Force an asynchronous load. Unlike {@link #startLoading()} this will ignore a previously
* loaded data set and load a new one. This simply calls through to the
* implementation's {@link #onForceLoad()}. You generally should only call this
* when the loader is started -- that is, {@link #isStarted()} returns true.
*
* <p>Must be called from the process's main thread.
*/
public void forceLoad() {
onForceLoad();
}
/**
* Subclasses must implement this to take care of requests to {@link #forceLoad()}.
* This will always be called from the process's main thread.
*/
protected void onForceLoad() {
}
/**
* Stops delivery of updates until the next time {@link #startLoading()} is called.
* Implementations should <em>not</em> invalidate their data at this point --
* clients are still free to use the last data the loader reported. They will,
* however, typically stop reporting new data if the data changes; they can
* still monitor for changes, but must not report them to the client until and
* if {@link #startLoading()} is later called.
*
* <p>This updates the Loader's internal state so that
* {@link #isStarted()} will return the correct
* value, and then calls the implementation's {@link #onStopLoading()}.
*
* <p>Must be called from the process's main thread.
*/
public void stopLoading() {
mStarted = false;
onStopLoading();
}
/**
* Subclasses must implement this to take care of stopping their loader,
* as per {@link #stopLoading()}. This is not called by clients directly,
* but as a result of a call to {@link #stopLoading()}.
* This will always be called from the process's main thread.
*/
protected void onStopLoading() {
}
/**
* Tell the Loader that it is being abandoned. This is called prior
* to {@link #reset} to have it retain its current data but not report
* any new data.
*/
public void abandon() {
mAbandoned = true;
onAbandon();
}
/**
* Subclasses implement this to take care of being abandoned. This is
* an optional intermediate state prior to {@link #onReset()} -- it means that
* the client is no longer interested in any new data from the loader,
* so the loader must not report any further updates. However, the
* loader <em>must</em> keep its last reported data valid until the final
* {@link #onReset()} happens. You can retrieve the current abandoned
* state with {@link #isAbandoned}.
*/
protected void onAbandon() {
}
/**
* Resets the state of the Loader. The Loader should at this point free
* all of its resources, since it may never be called again; however, its
* {@link #startLoading()} may later be called at which point it must be
* able to start running again.
*
* <p>This updates the Loader's internal state so that
* {@link #isStarted()} and {@link #isReset()} will return the correct
* values, and then calls the implementation's {@link #onReset()}.
*
* <p>Must be called from the process's main thread.
*/
public void reset() {
onReset();
mReset = true;
mStarted = false;
mAbandoned = false;
mContentChanged = false;
mProcessingChange = false;
}
/**
* Subclasses must implement this to take care of resetting their loader,
* as per {@link #reset()}. This is not called by clients directly,
* but as a result of a call to {@link #reset()}.
* This will always be called from the process's main thread.
*/
protected void onReset() {
}
/**
* Take the current flag indicating whether the loader's content had
* changed while it was stopped. If it had, true is returned and the
* flag is cleared.
*/
public boolean takeContentChanged() {
boolean res = mContentChanged;
mContentChanged = false;
mProcessingChange |= res;
return res;
}
/**
* Commit that you have actually fully processed a content change that
* was returned by {@link #takeContentChanged}. This is for use with
* {@link #rollbackContentChanged()} to handle situations where a load
* is cancelled. Call this when you have completely processed a load
* without it being cancelled.
*/
public void commitContentChanged() {
mProcessingChange = false;
}
/**
* Report that you have abandoned the processing of a content change that
* was returned by {@link #takeContentChanged()} and would like to rollback
* to the state where there is again a pending content change. This is
* to handle the case where a data load due to a content change has been
* canceled before its data was delivered back to the loader.
*/
public void rollbackContentChanged() {
if (mProcessingChange) {
mContentChanged = true;
}
}
/**
* Called when {@link ForceLoadContentObserver} detects a change. The
* default implementation checks to see if the loader is currently started;
* if so, it simply calls {@link #forceLoad()}; otherwise, it sets a flag
* so that {@link #takeContentChanged()} returns true.
*
* <p>Must be called from the process's main thread.
*/
public void onContentChanged() {
if (mStarted) {
forceLoad();
} else {
// This loader has been stopped, so we don't want to load
// new data right now... but keep track of it changing to
// refresh later if we start again.
mContentChanged = true;
}
}
/**
* For debugging, converts an instance of the Loader's data class to
* a string that can be printed. Must handle a null data.
*/
public String dataToString(D data) {
StringBuilder sb = new StringBuilder(64);
DebugUtils.buildShortClassTag(data, sb);
sb.append("}");
return sb.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(64);
DebugUtils.buildShortClassTag(this, sb);
sb.append(" id=");
sb.append(mId);
sb.append("}");
return sb.toString();
}
/**
* Print the Loader's state into the given stream.
*
* @param prefix Text to print at the front of each line.
* @param fd The raw file descriptor that the dump is being sent to.
* @param writer A PrintWriter to which the dump is to be set.
* @param args Additional arguments to the dump request.
*/
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
writer.print(prefix); writer.print("mId="); writer.print(mId);
writer.print(" mListener="); writer.println(mListener);
if (mStarted || mContentChanged || mProcessingChange) {
writer.print(prefix); writer.print("mStarted="); writer.print(mStarted);
writer.print(" mContentChanged="); writer.print(mContentChanged);
writer.print(" mProcessingChange="); writer.println(mProcessingChange);
}
if (mAbandoned || mReset) {
writer.print(prefix); writer.print("mAbandoned="); writer.print(mAbandoned);
writer.print(" mReset="); writer.println(mReset);
}
}
}
| 14,743
|
Java
|
.java
| 371
| 33.188679
| 100
| 0.656549
|
Dewep/IntranetEpitechV2
| 1
| 0
| 0
|
GPL-3.0
|
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 14,743
|
2,400,376
|
PowerUtilizationHistoryEntry.java
|
etri_DFaaSCloud/src/org/cloudbus/cloudsim/sdn/power/PowerUtilizationHistoryEntry.java
|
/*
* Title: CloudSimSDN
* Description: SDN extension for CloudSim
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2015, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.sdn.power;
/**
* To log utilization history, this class holds power utilization information
*
* @author Jungmin Son
* @since CloudSimSDN 1.0
*/
public class PowerUtilizationHistoryEntry {
public double startTime;
public double usedMips;
public PowerUtilizationHistoryEntry(double t, double m) { startTime=t; usedMips=m;}
}
| 570
|
Java
|
.java
| 19
| 28.105263
| 84
| 0.754098
|
etri/DFaaSCloud
| 8
| 1
| 4
|
GPL-3.0
|
9/4/2024, 9:20:24 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 570
|
4,421,871
|
SpiralTreeMapLookAhead.java
|
tue-alga_UncertaintyTreemaps/code/StableTreemap/src/TreeMapGenerator/SpiralTreeMapLookAhead.java
|
package TreeMapGenerator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import treemap.dataStructure.DataMap;
import treemap.dataStructure.Rectangle;
/**
*
* @author max
*/
public class SpiralTreeMapLookAhead extends SpiralTreeMap {
@Override
public Map<DataMap, Rectangle> generateLevel(List<DataMap> children, Rectangle treeMapRectangle, Orientation orientation) {
Map<DataMap, Rectangle> rectangleMapping = new HashMap<>();
//factor which we need to scale the areas for each rectangle
double scaleFactor = getScaleFactor(children, treeMapRectangle);
//holds the area we still have to fill
Rectangle remainingRectangle = treeMapRectangle;
//holds the datamaps that still need to be layed out
List<DataMap> remainingDataMaps = new LinkedList();
remainingDataMaps.addAll(children);
//holds the previous strip
List<DataMap> prevStrip = null;
//holds whether the previous strip had a horizontal layout
Orientation prevOrientation = orientation;
//layout strips untill there are no more datamaps
while (!remainingDataMaps.isEmpty()) {
//gets the newbest strip
List<DataMap> newStrip = getBestStrip(remainingDataMaps, remainingRectangle, scaleFactor, orientation);
//remove the datamaps in the strip from the remainingDataMaps
remainingDataMaps.removeAll(newStrip);
//If it was the first strip just store it
if (prevStrip != null) {
//Get the optimal strip distribution and store the orientation
optimizeStrips(prevStrip, prevOrientation, newStrip, remainingRectangle, scaleFactor);
if (!newStrip.isEmpty()) //we now have completed work with prevStrip so we can layout it out in the treemap
{
//update the rectanglemapping according to the strip
Map<DataMap, Rectangle> rectanglesFromStrip = getRectanglesFromStrip(prevStrip, scaleFactor, remainingRectangle, prevOrientation);
rectangleMapping.putAll(rectanglesFromStrip);
//update the rectangle that we still need to fill
//we first get one of the rectangles(strip is filled and they all have the same width/height)
Rectangle[] stripRectangles = rectanglesFromStrip.values().toArray(new Rectangle[0]);
//calculate the new remaining rectangle based on the current remaining rectangle and the rectangles just created
remainingRectangle = getRemainingRectangle(remainingRectangle, stripRectangles, prevOrientation);
}
}
if (!newStrip.isEmpty()) {
prevStrip = newStrip;
prevOrientation = orientation;
orientation = orientation.nextOrientation();
if (remainingDataMaps.isEmpty()) {
//this was the last strip, so also layout the newStrip
Map<DataMap, Rectangle> rectanglesFromStrip = getRectanglesFromStrip(newStrip, scaleFactor, remainingRectangle, orientation);
rectangleMapping.putAll(rectanglesFromStrip);
}
} else {
if (remainingDataMaps.isEmpty()) {
//this was the last strip, so also layout the newStrip
Map<DataMap, Rectangle> rectanglesFromStrip = getRectanglesFromStrip(prevStrip, scaleFactor, remainingRectangle, prevOrientation);
rectangleMapping.putAll(rectanglesFromStrip);
}
}
}
//layout the last strip
//generate the strips and re
return rectangleMapping;
}
/**
* Checks if items in the newStrip can be better put in previous strip to
* improve the maximum aspect ratio. Makes changes towards both prevStrip
* and nextStrip
*
* Assumes that the treemapRectangle is from the previous one
*
* @param prevStrip
* @param nextStrip
*/
public void optimizeStrips(List<DataMap> prevStrip, Orientation prevOrientation, List<DataMap> nextStrip, Rectangle remainingRectangle, double scaleFactor) {
List<DataMap> prevStripCopy = new LinkedList();
prevStripCopy.addAll(prevStrip);
List<DataMap> nextStripCopy = new LinkedList();
nextStripCopy.addAll(nextStrip);
Orientation newOrientation = prevOrientation.nextOrientation();
//Get the rectangle as it would be after the first strip is layef out
Map<DataMap, Rectangle> rectanglesFromStrip = getRectanglesFromStrip(prevStripCopy, scaleFactor, remainingRectangle, prevOrientation);
Rectangle remainingRectangleAfter = getRemainingRectangle(remainingRectangle, rectanglesFromStrip.values().toArray(new Rectangle[0]), newOrientation);
//calculate the maximum aspect ratio and store it
double bestRatio = Math.max(getStripAspectRatio(prevStripCopy, remainingRectangle, scaleFactor, prevOrientation),
getStripAspectRatio(nextStripCopy, remainingRectangleAfter, scaleFactor, newOrientation));
//holds the index of the best split
int bestIndex = -1;
//Find the best distribution
for (int index = 0; index < nextStrip.size(); index++) {
DataMap dm = nextStrip.get(index);
prevStripCopy.add(dm);
nextStripCopy.remove(dm);
//Get the rectangle as it would we after the first strip is layout
rectanglesFromStrip = getRectanglesFromStrip(prevStripCopy, scaleFactor, remainingRectangle, prevOrientation);
remainingRectangleAfter = getRemainingRectangle(remainingRectangle, rectanglesFromStrip.values().toArray(new Rectangle[0]), newOrientation);
double ratio;
if (nextStripCopy.isEmpty()) {
ratio = getStripAspectRatio(prevStripCopy, remainingRectangle, scaleFactor, prevOrientation);
} else {
ratio = Math.max(getStripAspectRatio(prevStripCopy, remainingRectangle, scaleFactor, prevOrientation),
getStripAspectRatio(nextStripCopy, remainingRectangleAfter, scaleFactor, newOrientation));
}
if (ratio < bestRatio) {
bestIndex = index;
bestRatio = ratio;
}
}
//adhere to the distribution
if (bestIndex != -1) {
for (int index = 0; index < bestIndex + 1; index++) {
DataMap dm = nextStrip.get(0);
prevStrip.add(dm);
nextStrip.remove(dm);
}
}
}
private double getScaleFactor(List<DataMap> dataMapsInRectangle, Rectangle treeMapRectangle) {
double totalSize = DataMap.getTotalSize(dataMapsInRectangle);
double totalArea = treeMapRectangle.getWidth() * treeMapRectangle.getHeight();
return totalArea / totalSize;
}
}
| 7,070
|
Java
|
.java
| 128
| 43.890625
| 161
| 0.670085
|
tue-alga/UncertaintyTreemaps
| 2
| 0
| 0
|
GPL-3.0
|
9/5/2024, 12:12:40 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 7,070
|
1,053,136
|
GraphPath.java
|
rcpoison_jgrapht/jgrapht-core/src/main/java/org/jgrapht/GraphPath.java
|
/* ==========================================
* JGraphT : a free Java graph-theory library
* ==========================================
*
* Project Info: http://jgrapht.sourceforge.net/
* Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh)
*
* (C) Copyright 2003-2008, by Barak Naveh and Contributors.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/* ----------
* Graph.java
* ----------
* (C) Copyright 2008-2008, by John V. Sichi and Contributors.
*
* Original Author: John V. Sichi
* Contributor(s): -
*
* $Id$
*
* Changes
* -------
* 1-Jan-2008 : Initial revision (JVS);
*
*/
package org.jgrapht;
import java.util.*;
/**
* A GraphPath represents a <a href="http://mathworld.wolfram.com/Path.html">
* path</a> in a {@link Graph}. Note that a path is defined primarily in terms
* of edges (rather than vertices) so that multiple edges between the same pair
* of vertices can be discriminated.
*
* @author John Sichi
* @since Jan 1, 2008
*/
public interface GraphPath<V, E>
{
//~ Methods ----------------------------------------------------------------
/**
* Returns the graph over which this path is defined. The path may also be
* valid with respect to other graphs.
*
* @return the containing graph
*/
public Graph<V, E> getGraph();
/**
* Returns the start vertex in the path.
*
* @return the start vertex
*/
public V getStartVertex();
/**
* Returns the end vertex in the path.
*
* @return the end vertex
*/
public V getEndVertex();
/**
* Returns the edges making up the path. The first edge in this path is
* incident to the start vertex. The last edge is incident to the end
* vertex. The vertices along the path can be obtained by traversing from
* the start vertex, finding its opposite across the first edge, and then
* doing the same successively across subsequent edges; {@link
* Graphs#getPathVertexList} provides a convenience method for this.
*
* <p>Whether or not the returned edge list is modifiable depends on the
* path implementation.
*
* @return list of edges traversed by the path
*/
public List<E> getEdgeList();
/**
* Returns the weight assigned to the path. Typically, this will be the sum
* of the weights of the edge list entries (as defined by the containing
* graph), but some path implementations may use other definitions.
*
* @return the weight of the path
*/
public double getWeight();
}
// End GraphPath.java
| 3,303
|
Java
|
.java
| 96
| 30.770833
| 80
| 0.656973
|
rcpoison/jgrapht
| 47
| 861
| 1
|
LGPL-2.1
|
9/4/2024, 7:11:02 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 3,303
|
226,169
|
Rect.java
|
BotLibre_BotLibre/botlibre-desktop/source/android/graphics/Rect.java
|
/******************************************************************************
*
* Copyright 2014 Paphus Solutions Inc.
*
* Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html
*
* 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 android.graphics;
/**
* Stub class.
*/
public class Rect {
}
| 854
|
Java
|
.java
| 23
| 35.304348
| 80
| 0.601205
|
BotLibre/BotLibre
| 580
| 225
| 17
|
EPL-1.0
|
9/4/2024, 7:05:50 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 854
|
2,072,318
|
CustomerManager.java
|
SabaUrgup_Java_React-BootCamp/JavaDemos/interfaces/src/interfaces/CustomerManager.java
|
package interfaces;
public class CustomerManager {
private ICustomerDal customerDal;
public CustomerManager(ICustomerDal customerDal) {
this.customerDal = customerDal;
}
public void add() {
//iş kodları
customerDal.Add();
}
}
| 261
|
Java
|
.java
| 11
| 19.545455
| 52
| 0.755274
|
SabaUrgup/Java_React-BootCamp
| 19
| 0
| 0
|
EPL-2.0
|
9/4/2024, 8:28:31 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| true
| true
| 259
|
873,080
|
IObjectBuffer.java
|
heartsome_tmxeditor8/base_plugins/net.heartsome.xml/src/com/ximpleware/IObjectBuffer.java
|
/*
* Copyright (C) 2002-2012 XimpleWare, [email protected]
*
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.ximpleware;
/**
* Abstract object pointer storage interface
*/
interface IObjectBuffer {
Object objectAt(int i);
/**
* Modify the Object pointer at index to value val. *
* @param index int
* @param obj Object
*/
void modifyEntry(int index, Object obj);
/**
* Get the total number of Object pointer in the buffer.
* @return int
*/
int size();
}
| 1,239
|
Java
|
.java
| 35
| 31.2
| 78
| 0.696339
|
heartsome/tmxeditor8
| 69
| 47
| 7
|
GPL-2.0
|
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 1,239
|
3,362,218
|
ParamLayoutFormatter.java
|
pedro-salviano_DC-UFSCar-ES2-202201-GrupoBald/src/main/java/net/sf/jabref/logic/layout/ParamLayoutFormatter.java
|
/* Copyright (C) 2003-2011 JabRef contributors.
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 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package net.sf.jabref.logic.layout;
/**
* This interface extends LayoutFormatter, adding the capability of taking
* and additional parameter. Such a parameter is specified in the layout file
* by the following construct: \format[MyFormatter(argument){\field}
* If and only if MyFormatter is a class that implements ParamLayoutFormatter,
* it will be set up with the argument given in the parenthesis by way of the
* method setArgument(String). If no argument is given, the formatter will be
* invoked without the setArgument() method being called first.
*/
public interface ParamLayoutFormatter extends LayoutFormatter {
/**
* Method for setting the argument of this formatter.
* @param arg A String argument.
*/
void setArgument(String arg);
}
| 1,555
|
Java
|
.java
| 30
| 48.166667
| 78
| 0.765789
|
pedro-salviano/DC-UFSCar-ES2-202201-GrupoBald
| 4
| 0
| 0
|
GPL-2.0
|
9/4/2024, 11:15:32 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 1,555
|
1,427,556
|
MonkSprite.java
|
FthrNature_unleashed-pixel-dungeon/src/main/java/com/shatteredpixel/pixeldungeonunleashed/sprites/MonkSprite.java
|
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2015 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.pixeldungeonunleashed.sprites;
import com.watabou.noosa.TextureFilm;
import com.shatteredpixel.pixeldungeonunleashed.Assets;
import com.watabou.utils.Random;
public class MonkSprite extends MobSprite {
private Animation kick;
public MonkSprite() {
super();
texture( Assets.MONK );
TextureFilm frames = new TextureFilm( texture, 15, 14 );
idle = new Animation( 6, true );
idle.frames( frames, 1, 0, 1, 2 );
run = new Animation( 15, true );
run.frames( frames, 11, 12, 13, 14, 15, 16 );
attack = new Animation( 12, false );
attack.frames( frames, 3, 4, 3, 4 );
kick = new Animation( 10, false );
kick.frames( frames, 5, 6, 5 );
die = new Animation( 15, false );
die.frames( frames, 1, 7, 8, 8, 9, 10 );
play( idle );
}
@Override
public void attack( int cell ) {
super.attack( cell );
if (Random.Float() < 0.5f) {
play( kick );
}
}
@Override
public void onComplete( Animation anim ) {
super.onComplete( anim == kick ? attack : anim );
}
}
| 1,827
|
Java
|
.java
| 54
| 30.962963
| 71
| 0.717654
|
FthrNature/unleashed-pixel-dungeon
| 23
| 13
| 3
|
GPL-3.0
|
9/4/2024, 7:50:14 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| true
| true
| 1,827
|
2,419,533
|
ProfileBanEntry.java
|
dotexe1337_bdsm-client-1_16/src/main/java/net/minecraft/server/management/ProfileBanEntry.java
|
package net.minecraft.server.management;
import com.google.gson.JsonObject;
import com.mojang.authlib.GameProfile;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
import javax.annotation.Nullable;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
public class ProfileBanEntry extends BanEntry<GameProfile>
{
public ProfileBanEntry(GameProfile profile)
{
this(profile, (Date)null, (String)null, (Date)null, (String)null);
}
public ProfileBanEntry(GameProfile profile, @Nullable Date startDate, @Nullable String banner, @Nullable Date endDate, @Nullable String banReason)
{
super(profile, startDate, banner, endDate, banReason);
}
public ProfileBanEntry(JsonObject json)
{
super(toGameProfile(json), json);
}
protected void onSerialization(JsonObject data)
{
if (this.getValue() != null)
{
data.addProperty("uuid", this.getValue().getId() == null ? "" : this.getValue().getId().toString());
data.addProperty("name", this.getValue().getName());
super.onSerialization(data);
}
}
public ITextComponent getDisplayName()
{
GameProfile gameprofile = this.getValue();
return new StringTextComponent(gameprofile.getName() != null ? gameprofile.getName() : Objects.toString(gameprofile.getId(), "(Unknown)"));
}
/**
* Convert a {@linkplain com.google.gson.JsonObject JsonObject} into a {@linkplain com.mojang.authlib.GameProfile}.
* The json object must have {@code uuid} and {@code name} attributes or {@code null} will be returned.
*/
private static GameProfile toGameProfile(JsonObject json)
{
if (json.has("uuid") && json.has("name"))
{
String s = json.get("uuid").getAsString();
UUID uuid;
try
{
uuid = UUID.fromString(s);
}
catch (Throwable throwable)
{
return null;
}
return new GameProfile(uuid, json.get("name").getAsString());
}
else
{
return null;
}
}
}
| 2,227
|
Java
|
.java
| 63
| 28
| 150
| 0.642691
|
dotexe1337/bdsm-client-1.16
| 8
| 1
| 1
|
GPL-2.0
|
9/4/2024, 9:22:36 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 2,227
|
4,192,885
|
FuncSystemProperty.java
|
diamantisk_openjdk9-sctp/jaxp/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/functions/FuncSystemProperty.java
|
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Copyright 1999-2004 The Apache Software 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.
*/
/*
* $Id: FuncSystemProperty.java,v 1.2.4.2 2005/09/14 20:18:45 jeffsuttor Exp $
*/
package com.sun.org.apache.xpath.internal.functions;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.Properties;
import com.sun.org.apache.xpath.internal.XPathContext;
import com.sun.org.apache.xpath.internal.objects.XObject;
import com.sun.org.apache.xpath.internal.objects.XString;
import com.sun.org.apache.xpath.internal.res.XPATHErrorResources;
import com.sun.org.apache.xalan.internal.utils.SecuritySupport;
/**
* Execute the SystemProperty() function.
* @xsl.usage advanced
*/
public class FuncSystemProperty extends FunctionOneArg
{
static final long serialVersionUID = 3694874980992204867L;
/**
* The path/filename of the property file: XSLTInfo.properties
* Maintenance note: see also
* com.sun.org.apache.xalan.internal.processor.TransformerFactoryImpl.XSLT_PROPERTIES
*/
static final String XSLT_PROPERTIES =
"com/sun/org/apache/xalan/internal/res/XSLTInfo.properties";
/**
* Execute the function. The function must return
* a valid object.
* @param xctxt The current execution context.
* @return A valid XObject.
*
* @throws javax.xml.transform.TransformerException
*/
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
{
String fullName = m_arg0.execute(xctxt).str();
int indexOfNSSep = fullName.indexOf(':');
String result;
String propName = "";
// List of properties where the name of the
// property argument is to be looked for.
Properties xsltInfo = new Properties();
loadPropertyFile(xsltInfo);
if (indexOfNSSep > 0)
{
String prefix = (indexOfNSSep >= 0)
? fullName.substring(0, indexOfNSSep) : "";
String namespace;
namespace = xctxt.getNamespaceContext().getNamespaceForPrefix(prefix);
propName = (indexOfNSSep < 0)
? fullName : fullName.substring(indexOfNSSep + 1);
if (namespace.startsWith("http://www.w3.org/XSL/Transform")
|| namespace.equals("http://www.w3.org/1999/XSL/Transform"))
{
result = xsltInfo.getProperty(propName);
if (null == result)
{
warn(xctxt, XPATHErrorResources.WG_PROPERTY_NOT_SUPPORTED,
new Object[]{ fullName }); //"XSL Property not supported: "+fullName);
return XString.EMPTYSTRING;
}
}
else
{
warn(xctxt, XPATHErrorResources.WG_DONT_DO_ANYTHING_WITH_NS,
new Object[]{ namespace,
fullName }); //"Don't currently do anything with namespace "+namespace+" in property: "+fullName);
try
{
result = SecuritySupport.getSystemProperty(propName);
if (null == result)
{
// result = System.getenv(propName);
return XString.EMPTYSTRING;
}
}
catch (SecurityException se)
{
warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION,
new Object[]{ fullName }); //"SecurityException when trying to access XSL system property: "+fullName);
return XString.EMPTYSTRING;
}
}
}
else
{
try
{
result = SecuritySupport.getSystemProperty(fullName);
if (null == result)
{
// result = System.getenv(fullName);
return XString.EMPTYSTRING;
}
}
catch (SecurityException se)
{
warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION,
new Object[]{ fullName }); //"SecurityException when trying to access XSL system property: "+fullName);
return XString.EMPTYSTRING;
}
}
if (propName.equals("version") && result.length() > 0)
{
try
{
// Needs to return the version number of the spec we conform to.
return new XString("1.0");
}
catch (Exception ex)
{
return new XString(result);
}
}
else
return new XString(result);
}
/**
* Retrieve a property bundle from XSLT_PROPERTIES
*
* @param target The target property bag the file will be placed into.
*/
private void loadPropertyFile(Properties target)
{
try
{
// Use SecuritySupport class to provide privileged access to property file
InputStream is = SecuritySupport.getResourceAsStream(XSLT_PROPERTIES);
// get a buffered version
try (BufferedInputStream bis = new BufferedInputStream(is)) {
target.load(bis); // and load up the property bag from this
}
}
catch (Exception ex)
{
// ex.printStackTrace();
throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(ex);
}
}
}
| 5,503
|
Java
|
.java
| 160
| 28.2
| 126
| 0.668107
|
diamantisk/openjdk9-sctp
| 2
| 0
| 0
|
GPL-2.0
|
9/5/2024, 12:05:36 AM (Europe/Amsterdam)
| false
| true
| true
| true
| false
| true
| true
| true
| 5,503
|
2,592,951
|
DoWhileLoopTree.java
|
JPortal-system_system/jdk12-06222165c35f/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/tree/DoWhileLoopTree.java
|
/*
* Copyright (c) 2015, 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 jdk.nashorn.api.tree;
/**
* A tree node for a 'do' statement.
*
* For example:
* <pre>
* do
* <em>statement</em>
* while ( <em>expression</em> );
* </pre>
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface DoWhileLoopTree extends ConditionalLoopTree {
/**
* Returns the condition expression of this do-while statement.
*
* @return the condition expression
*/
@Override
ExpressionTree getCondition();
/**
* The statement contained within this do-while statement.
*
* @return the statement
*/
@Override
StatementTree getStatement();
}
| 2,007
|
Java
|
.java
| 57
| 32.385965
| 76
| 0.731895
|
JPortal-system/system
| 7
| 2
| 1
|
GPL-3.0
|
9/4/2024, 9:49:36 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 2,007
|
2,175,154
|
DownloadProgress.java
|
RockCityDev_Alphagram-Android/TMessagesProj/src/main/java/com/google/android/exoplayer2/offline/DownloadProgress.java
|
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.offline;
import com.google.android.exoplayer2.C;
/** Mutable {@link Download} progress. */
public class DownloadProgress {
/** The number of bytes that have been downloaded. */
public long bytesDownloaded;
/** The percentage that has been downloaded, or {@link C#PERCENTAGE_UNSET} if unknown. */
public float percentDownloaded;
}
| 1,000
|
Java
|
.java
| 24
| 39.583333
| 91
| 0.761317
|
RockCityDev/Alphagram-Android
| 12
| 4
| 0
|
GPL-2.0
|
9/4/2024, 8:31:40 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 1,000
|
3,454,834
|
ToolType.java
|
IntegratedBreedingPlatform_Middleware/src/main/java/org/generationcp/middleware/pojos/workbench/ToolType.java
|
/*******************************************************************************
* Copyright (c) 2012, All Rights Reserved.
*
* Generation Challenge Programme (GCP)
*
*
* This software is licensed for use under the terms of the GNU General Public License (http://bit.ly/8Ztv8M) and the provisions of Part F
* of the Generation Challenge Programme Amended Consortium Agreement (http://bit.ly/KQX1nL)
*
*******************************************************************************/
package org.generationcp.middleware.pojos.workbench;
/**
* The type of tools - WEB, WEB_WITH_LOGIN, NATIVE.
*/
public enum ToolType {
WEB, WEB_WITH_LOGIN, NATIVE, WORKBENCH, ADMIN
}
| 697
|
Java
|
.java
| 17
| 38.058824
| 139
| 0.557692
|
IntegratedBreedingPlatform/Middleware
| 3
| 2
| 9
|
GPL-3.0
|
9/4/2024, 11:28:51 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 697
|
4,248,953
|
ListIteration.java
|
rockleeprc_sourcecode/ThinkInJava4/holding/ListIteration.java
|
//: holding/ListIteration.java
import typeinfo.pets.*;
import java.util.*;
public class ListIteration {
public static void main(String[] args) {
List<Pet> pets = Pets.arrayList(8);
ListIterator<Pet> it = pets.listIterator();
while(it.hasNext())
System.out.print(it.next() + ", " + it.nextIndex() +
", " + it.previousIndex() + "; ");
System.out.println();
// Backwards:
while(it.hasPrevious())
System.out.print(it.previous().id() + " ");
System.out.println();
System.out.println(pets);
it = pets.listIterator(3);
while(it.hasNext()) {
it.next();
it.set(Pets.randomPet());
}
System.out.println(pets);
}
} /* Output:
Rat, 1, 0; Manx, 2, 1; Cymric, 3, 2; Mutt, 4, 3; Pug, 5, 4; Cymric, 6, 5; Pug, 7, 6; Manx, 8, 7;
7 6 5 4 3 2 1 0
[Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug, Manx]
[Rat, Manx, Cymric, Cymric, Rat, EgyptianMau, Hamster, EgyptianMau]
*///:~
| 938
|
Java
|
.java
| 29
| 28.37931
| 96
| 0.613436
|
rockleeprc/sourcecode
| 2
| 2
| 0
|
GPL-3.0
|
9/5/2024, 12:07:03 AM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 938
|
1,317,178
|
B.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/test3/out/B.java
|
package p;
class B{
}
class AA extends B{
}
| 43
|
Java
|
.java
| 5
| 7.8
| 19
| 0.74359
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 43
|
55,797
|
TbManageUser.java
|
xubinux_xbin-store/xbin-store-common-pojo/src/main/java/cn/binux/pojo/TbManageUser.java
|
package cn.binux.pojo;
import lombok.Data;
import java.util.Date;
@Data
public class TbManageUser {
private Long id;
private String username;
private String name;
private String password;
private String phone;
private String email;
private String job;
private Date created;
private Date updated;
}
| 345
|
Java
|
.java
| 15
| 18.866667
| 28
| 0.749216
|
xubinux/xbin-store
| 2,149
| 1,128
| 28
|
GPL-3.0
|
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 345
|
4,579,917
|
WrapperPlayClientBookEdit.java
|
Zerek-Cheng_Zerek-Develop-Projects-For-Work/PeaceElite/src/main/java/com/comphenix/packetwrapper/WrapperPlayClientBookEdit.java
|
/**
* This file is part of PacketWrapper.
* Copyright (C) 2012-2015 Kristian S. Strangeland
* Copyright (C) 2015 dmulloy2
*
* PacketWrapper is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PacketWrapper 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 Lesser General Public License
* along with PacketWrapper. If not, see <http://www.gnu.org/licenses/>.
*/
package com.comphenix.packetwrapper;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.PacketContainer;
import org.bukkit.inventory.ItemStack;
public class WrapperPlayClientBookEdit extends AbstractPacket {
public static final PacketType TYPE = PacketType.Play.Client.BOOK_EDIT;
public WrapperPlayClientBookEdit() {
super(new PacketContainer(TYPE), TYPE);
handle.getModifier().writeDefaults();
}
public WrapperPlayClientBookEdit(PacketContainer packet) {
super(packet, TYPE);
}
/**
* Retrieve New book.
* @return The current New book
*/
public ItemStack getNewBook() {
return handle.getItemModifier().read(0);
}
/**
* Set New book.
* @param value - new value.
*/
public void setNewBook(ItemStack value) {
handle.getItemModifier().write(0, value);
}
/**
* Retrieve Is signing.
* <p>
* Notes: true if the player is signing the book; false if the player is saving a draft.
* @return The current Is signing
*/
public boolean getIsSigning() {
return handle.getBooleans().read(0);
}
/**
* Set Is signing.
* @param value - new value.
*/
public void setIsSigning(boolean value) {
handle.getBooleans().write(0, value);
}
}
| 2,165
|
Java
|
.java
| 62
| 29.983871
| 92
| 0.704831
|
Zerek-Cheng/Zerek-Develop-Projects-For-Work
| 2
| 1
| 0
|
GPL-3.0
|
9/5/2024, 12:18:11 AM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| true
| true
| true
| 2,165
|
2,920,094
|
CallVisitor.java
|
8BitPlus_BitPlus/src_vendor/org/objectweb/asm/commons/cfg/CallVisitor.java
|
package org.objectweb.asm.commons.cfg;
import org.objectweb.asm.Handle;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.cfg.graph.CallGraph;
import org.objectweb.asm.tree.MethodNode;
/**
* @author Tyler Sedlar
*/
public class CallVisitor extends MethodVisitor {
public CallVisitor() {
super(Opcodes.ASM5);
}
public final CallGraph graph = new CallGraph();
private MethodNode mn;
public void visit(MethodNode mn) {
this.mn = mn;
mn.accept(this);
}
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc) {
graph.addMethodCall(mn.handle, new Handle(0, owner, name, desc));
}
@Override
public void visitMethodInsn(int opcode, String owner, String name,
String desc, boolean itf) {
graph.addMethodCall(mn.handle, new Handle(0, owner, name, desc));
}
}
| 942
|
Java
|
.java
| 29
| 28
| 82
| 0.725446
|
8BitPlus/BitPlus
| 5
| 3
| 4
|
GPL-3.0
|
9/4/2024, 10:35:11 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 942
|
3,434,600
|
For_c.java
|
Sable_polyglot/src/polyglot/ext/jl/ast/For_c.java
|
package polyglot.ext.jl.ast;
import polyglot.ast.*;
import polyglot.types.*;
import polyglot.visit.*;
import polyglot.util.*;
import java.util.*;
/**
* An immutable representation of a Java language <code>for</code>
* statement. Contains a statement to be executed and an expression
* to be tested indicating whether to reexecute the statement.
*/
public class For_c extends Loop_c implements For
{
protected List inits;
protected Expr cond;
protected List iters;
protected Stmt body;
public For_c(Position pos, List inits, Expr cond, List iters, Stmt body) {
super(pos);
this.inits = TypedList.copyAndCheck(inits, ForInit.class, true);
this.cond = cond;
this.iters = TypedList.copyAndCheck(iters, ForUpdate.class, true);
this.body = body;
}
/** List of initialization statements */
public List inits() {
return Collections.unmodifiableList(this.inits);
}
/** Set the inits of the statement. */
public For inits(List inits) {
For_c n = (For_c) copy();
n.inits = TypedList.copyAndCheck(inits, ForInit.class, true);
return n;
}
/** Loop condition */
public Expr cond() {
return this.cond;
}
/** Set the conditional of the statement. */
public For cond(Expr cond) {
For_c n = (For_c) copy();
n.cond = cond;
return n;
}
/** List of iterator expressions. */
public List iters() {
return Collections.unmodifiableList(this.iters);
}
/** Set the iterator expressions of the statement. */
public For iters(List iters) {
For_c n = (For_c) copy();
n.iters = TypedList.copyAndCheck(iters, ForUpdate.class, true);
return n;
}
/** Loop body */
public Stmt body() {
return this.body;
}
/** Set the body of the statement. */
public For body(Stmt body) {
For_c n = (For_c) copy();
n.body = body;
return n;
}
/** Reconstruct the statement. */
protected For_c reconstruct(List inits, Expr cond, List iters, Stmt body) {
if (! CollectionUtil.equals(inits, this.inits) || cond != this.cond || ! CollectionUtil.equals(iters, this.iters) || body != this.body) {
For_c n = (For_c) copy();
n.inits = TypedList.copyAndCheck(inits, ForInit.class, true);
n.cond = cond;
n.iters = TypedList.copyAndCheck(iters, ForUpdate.class, true);
n.body = body;
return n;
}
return this;
}
/** Visit the children of the statement. */
public Node visitChildren(NodeVisitor v) {
List inits = visitList(this.inits, v);
Expr cond = (Expr) visitChild(this.cond, v);
List iters = visitList(this.iters, v);
Stmt body = (Stmt) visitChild(this.body, v);
return reconstruct(inits, cond, iters, body);
}
public Context enterScope(Context c) {
return c.pushBlock();
}
/** Type check the statement. */
public Node typeCheck(TypeChecker tc) throws SemanticException {
TypeSystem ts = tc.typeSystem();
// Check that all initializers have the same type.
// This should be enforced by the parser, but check again here,
// just to be sure.
Type t = null;
for (Iterator i = inits.iterator(); i.hasNext(); ) {
ForInit s = (ForInit) i.next();
if (s instanceof LocalDecl) {
LocalDecl d = (LocalDecl) s;
Type dt = d.type().type();
if (t == null) {
t = dt;
}
else if (! t.equals(dt)) {
throw new InternalCompilerError("Local variable " +
"declarations in a for loop initializer must all " +
"be the same type, in this case " + t + ", not " +
dt + ".", d.position());
}
}
}
if (cond != null &&
! ts.isImplicitCastValid(cond.type(), ts.Boolean())) {
throw new SemanticException(
"The condition of a for statement must have boolean type.",
cond.position());
}
return this;
}
public Type childExpectedType(Expr child, AscriptionVisitor av) {
TypeSystem ts = av.typeSystem();
if (child == cond) {
return ts.Boolean();
}
return child.type();
}
/** Write the statement to an output file. */
public void prettyPrint(CodeWriter w, PrettyPrinter tr) {
w.write("for (");
w.begin(0);
if (inits != null) {
boolean first = true;
for (Iterator i = inits.iterator(); i.hasNext(); ) {
ForInit s = (ForInit) i.next();
printForInit(s, w, tr, first);
first = false;
if (i.hasNext()) {
w.write(",");
w.allowBreak(2, " ");
}
}
}
w.write(";");
w.allowBreak(0);
if (cond != null) {
printBlock(cond, w, tr);
}
w.write (";");
w.allowBreak(0);
if (iters != null) {
for (Iterator i = iters.iterator(); i.hasNext();) {
ForUpdate s = (ForUpdate) i.next();
printForUpdate(s, w, tr);
if (i.hasNext()) {
w.write(",");
w.allowBreak(2, " ");
}
}
}
w.end();
w.write(")");
printSubStmt(body, w, tr);
}
public String toString() {
return "for (...) ...";
}
private void printForInit(ForInit s, CodeWriter w, PrettyPrinter tr, boolean printType) {
boolean oldSemiColon = tr.appendSemicolon(false);
boolean oldPrintType = tr.printType(printType);
printBlock(s, w, tr);
tr.printType(oldPrintType);
tr.appendSemicolon(oldSemiColon);
}
private void printForUpdate(ForUpdate s, CodeWriter w, PrettyPrinter tr) {
boolean oldSemiColon = tr.appendSemicolon(false);
printBlock(s, w, tr);
tr.appendSemicolon(oldSemiColon);
}
public Term entry() {
return listEntry(inits, (cond != null ? cond.entry() : body.entry()));
}
public List acceptCFG(CFGBuilder v, List succs) {
v.visitCFGList(inits, (cond != null ? cond.entry() : body.entry()));
if (cond != null) {
if (condIsConstantTrue()) {
v.visitCFG(cond, body.entry());
}
else {
v.visitCFG(cond, FlowGraph.EDGE_KEY_TRUE, body.entry(),
FlowGraph.EDGE_KEY_FALSE, this);
}
}
v.push(this).visitCFG(body, continueTarget());
v.visitCFGList(iters, (cond != null ? cond.entry() : body.entry()));
return succs;
}
public Term continueTarget() {
return listEntry(iters, (cond != null ? cond.entry() : body.entry()));
}
}
| 6,499
|
Java
|
.java
| 199
| 26.356784
| 138
| 0.605053
|
Sable/polyglot
| 3
| 3
| 0
|
LGPL-2.1
|
9/4/2024, 11:26:54 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 6,499
|
1,260,108
|
ConsumerServiceImpl.java
|
romeoblog_spring-cloud/mesh-mq/mesh-rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java
|
/*
* Copyright 2019 https://github.com/romeoblog/spring-cloud.git Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.console.service.impl;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.MQVersion;
import org.apache.rocketmq.common.admin.ConsumeStats;
import org.apache.rocketmq.common.admin.RollbackStats;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.common.protocol.ResponseCode;
import org.apache.rocketmq.common.protocol.body.ClusterInfo;
import org.apache.rocketmq.common.protocol.body.Connection;
import org.apache.rocketmq.common.protocol.body.ConsumerConnection;
import org.apache.rocketmq.common.protocol.body.ConsumerRunningInfo;
import org.apache.rocketmq.common.protocol.body.GroupList;
import org.apache.rocketmq.common.protocol.body.SubscriptionGroupWrapper;
import org.apache.rocketmq.common.protocol.route.BrokerData;
import org.apache.rocketmq.common.subscription.SubscriptionGroupConfig;
import org.apache.rocketmq.console.aspect.admin.annotation.MultiMQAdminCmdMethod;
import org.apache.rocketmq.console.model.ConsumerGroupRollBackStat;
import org.apache.rocketmq.console.model.GroupConsumeInfo;
import org.apache.rocketmq.console.model.QueueStatInfo;
import org.apache.rocketmq.console.model.TopicConsumerInfo;
import org.apache.rocketmq.console.model.request.ConsumerConfigInfo;
import org.apache.rocketmq.console.model.request.DeleteSubGroupRequest;
import org.apache.rocketmq.console.model.request.ResetOffsetRequest;
import org.apache.rocketmq.console.service.AbstractCommonService;
import org.apache.rocketmq.console.service.ConsumerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import static com.google.common.base.Throwables.propagate;
@Service
public class ConsumerServiceImpl extends AbstractCommonService implements ConsumerService {
private Logger logger = LoggerFactory.getLogger(ConsumerServiceImpl.class);
@Override
@MultiMQAdminCmdMethod
public List<GroupConsumeInfo> queryGroupList() {
Set<String> consumerGroupSet = Sets.newHashSet();
try {
ClusterInfo clusterInfo = mqAdminExt.examineBrokerClusterInfo();
for (BrokerData brokerData : clusterInfo.getBrokerAddrTable().values()) {
SubscriptionGroupWrapper subscriptionGroupWrapper = mqAdminExt.getAllSubscriptionGroup(brokerData.selectBrokerAddr(), 3000L);
consumerGroupSet.addAll(subscriptionGroupWrapper.getSubscriptionGroupTable().keySet());
}
}
catch (Exception err) {
throw Throwables.propagate(err);
}
List<GroupConsumeInfo> groupConsumeInfoList = Lists.newArrayList();
for (String consumerGroup : consumerGroupSet) {
groupConsumeInfoList.add(queryGroup(consumerGroup));
}
Collections.sort(groupConsumeInfoList);
return groupConsumeInfoList;
}
@Override
@MultiMQAdminCmdMethod
public GroupConsumeInfo queryGroup(String consumerGroup) {
GroupConsumeInfo groupConsumeInfo = new GroupConsumeInfo();
try {
ConsumeStats consumeStats = null;
try {
consumeStats = mqAdminExt.examineConsumeStats(consumerGroup);
}
catch (Exception e) {
logger.warn("examineConsumeStats exception, " + consumerGroup, e);
}
ConsumerConnection consumerConnection = null;
try {
consumerConnection = mqAdminExt.examineConsumerConnectionInfo(consumerGroup);
}
catch (Exception e) {
logger.warn("examineConsumerConnectionInfo exception, " + consumerGroup, e);
}
groupConsumeInfo.setGroup(consumerGroup);
if (consumeStats != null) {
groupConsumeInfo.setConsumeTps((int)consumeStats.getConsumeTps());
groupConsumeInfo.setDiffTotal(consumeStats.computeTotalDiff());
}
if (consumerConnection != null) {
groupConsumeInfo.setCount(consumerConnection.getConnectionSet().size());
groupConsumeInfo.setMessageModel(consumerConnection.getMessageModel());
groupConsumeInfo.setConsumeType(consumerConnection.getConsumeType());
groupConsumeInfo.setVersion(MQVersion.getVersionDesc(consumerConnection.computeMinVersion()));
}
}
catch (Exception e) {
logger.warn("examineConsumeStats or examineConsumerConnectionInfo exception, "
+ consumerGroup, e);
}
return groupConsumeInfo;
}
@Override
public List<TopicConsumerInfo> queryConsumeStatsListByGroupName(String groupName) {
return queryConsumeStatsList(null, groupName);
}
@Override
@MultiMQAdminCmdMethod
public List<TopicConsumerInfo> queryConsumeStatsList(final String topic, String groupName) {
ConsumeStats consumeStats = null;
try {
consumeStats = mqAdminExt.examineConsumeStats(groupName, topic);
}
catch (Exception e) {
throw propagate(e);
}
List<MessageQueue> mqList = Lists.newArrayList(Iterables.filter(consumeStats.getOffsetTable().keySet(), new Predicate<MessageQueue>() {
@Override
public boolean apply(MessageQueue o) {
return StringUtils.isBlank(topic) || o.getTopic().equals(topic);
}
}));
Collections.sort(mqList);
List<TopicConsumerInfo> topicConsumerInfoList = Lists.newArrayList();
TopicConsumerInfo nowTopicConsumerInfo = null;
Map<MessageQueue, String> messageQueueClientMap = getClientConnection(groupName);
for (MessageQueue mq : mqList) {
if (nowTopicConsumerInfo == null || (!StringUtils.equals(mq.getTopic(), nowTopicConsumerInfo.getTopic()))) {
nowTopicConsumerInfo = new TopicConsumerInfo(mq.getTopic());
topicConsumerInfoList.add(nowTopicConsumerInfo);
}
QueueStatInfo queueStatInfo = QueueStatInfo.fromOffsetTableEntry(mq, consumeStats.getOffsetTable().get(mq));
queueStatInfo.setClientInfo(messageQueueClientMap.get(mq));
nowTopicConsumerInfo.appendQueueStatInfo(queueStatInfo);
}
return topicConsumerInfoList;
}
private Map<MessageQueue, String> getClientConnection(String groupName) {
Map<MessageQueue, String> results = Maps.newHashMap();
try {
ConsumerConnection consumerConnection = mqAdminExt.examineConsumerConnectionInfo(groupName);
for (Connection connection : consumerConnection.getConnectionSet()) {
String clinetId = connection.getClientId();
ConsumerRunningInfo consumerRunningInfo = mqAdminExt.getConsumerRunningInfo(groupName, clinetId, false);
for (MessageQueue messageQueue : consumerRunningInfo.getMqTable().keySet()) {
// results.put(messageQueue, clinetId + " " + connection.getClientAddr());
results.put(messageQueue, clinetId);
}
}
}
catch (Exception err) {
logger.error("op=getClientConnection_error", err);
}
return results;
}
@Override
@MultiMQAdminCmdMethod
public Map<String /*groupName*/, TopicConsumerInfo> queryConsumeStatsListByTopicName(String topic) {
Map<String, TopicConsumerInfo> group2ConsumerInfoMap = Maps.newHashMap();
try {
GroupList groupList = mqAdminExt.queryTopicConsumeByWho(topic);
for (String group : groupList.getGroupList()) {
List<TopicConsumerInfo> topicConsumerInfoList = null;
try {
topicConsumerInfoList = queryConsumeStatsList(topic, group);
}
catch (Exception ignore) {
}
group2ConsumerInfoMap.put(group, CollectionUtils.isEmpty(topicConsumerInfoList) ? new TopicConsumerInfo(topic) : topicConsumerInfoList.get(0));
}
return group2ConsumerInfoMap;
}
catch (Exception e) {
throw propagate(e);
}
}
@Override
@MultiMQAdminCmdMethod
public Map<String, ConsumerGroupRollBackStat> resetOffset(ResetOffsetRequest resetOffsetRequest) {
Map<String, ConsumerGroupRollBackStat> groupRollbackStats = Maps.newHashMap();
for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) {
try {
Map<MessageQueue, Long> rollbackStatsMap =
mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce());
ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true);
List<RollbackStats> rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList();
for (Map.Entry<MessageQueue, Long> rollbackStatsEntty : rollbackStatsMap.entrySet()) {
RollbackStats rollbackStats = new RollbackStats();
rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue());
rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId());
rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName());
rollbackStatsList.add(rollbackStats);
}
groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat);
}
catch (MQClientException e) {
if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) {
try {
ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true);
List<RollbackStats> rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true);
consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList);
groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat);
continue;
}
catch (Exception err) {
logger.error("op=resetOffset_which_not_online_error", err);
}
}
else {
logger.error("op=resetOffset_error", e);
}
groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage()));
}
catch (Exception e) {
logger.error("op=resetOffset_error", e);
groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage()));
}
}
return groupRollbackStats;
}
@Override
@MultiMQAdminCmdMethod
public List<ConsumerConfigInfo> examineSubscriptionGroupConfig(String group) {
List<ConsumerConfigInfo> consumerConfigInfoList = Lists.newArrayList();
try {
ClusterInfo clusterInfo = mqAdminExt.examineBrokerClusterInfo();
for (String brokerName : clusterInfo.getBrokerAddrTable().keySet()) { //foreach brokerName
String brokerAddress = clusterInfo.getBrokerAddrTable().get(brokerName).selectBrokerAddr();
SubscriptionGroupConfig subscriptionGroupConfig = mqAdminExt.examineSubscriptionGroupConfig(brokerAddress, group);
if (subscriptionGroupConfig == null) {
continue;
}
consumerConfigInfoList.add(new ConsumerConfigInfo(Lists.newArrayList(brokerName), subscriptionGroupConfig));
}
}
catch (Exception e) {
throw propagate(e);
}
return consumerConfigInfoList;
}
@Override
@MultiMQAdminCmdMethod
public boolean deleteSubGroup(DeleteSubGroupRequest deleteSubGroupRequest) {
try {
ClusterInfo clusterInfo = mqAdminExt.examineBrokerClusterInfo();
for (String brokerName : deleteSubGroupRequest.getBrokerNameList()) {
logger.info("addr={} groupName={}", clusterInfo.getBrokerAddrTable().get(brokerName).selectBrokerAddr(), deleteSubGroupRequest.getGroupName());
mqAdminExt.deleteSubscriptionGroup(clusterInfo.getBrokerAddrTable().get(brokerName).selectBrokerAddr(), deleteSubGroupRequest.getGroupName());
}
}
catch (Exception e) {
throw propagate(e);
}
return true;
}
@Override
public boolean createAndUpdateSubscriptionGroupConfig(ConsumerConfigInfo consumerConfigInfo) {
try {
ClusterInfo clusterInfo = mqAdminExt.examineBrokerClusterInfo();
for (String brokerName : changeToBrokerNameSet(clusterInfo.getClusterAddrTable(),
consumerConfigInfo.getClusterNameList(), consumerConfigInfo.getBrokerNameList())) {
mqAdminExt.createAndUpdateSubscriptionGroupConfig(clusterInfo.getBrokerAddrTable().get(brokerName).selectBrokerAddr(), consumerConfigInfo.getSubscriptionGroupConfig());
}
}
catch (Exception err) {
throw Throwables.propagate(err);
}
return true;
}
@Override
@MultiMQAdminCmdMethod
public Set<String> fetchBrokerNameSetBySubscriptionGroup(String group) {
Set<String> brokerNameSet = Sets.newHashSet();
try {
List<ConsumerConfigInfo> consumerConfigInfoList = examineSubscriptionGroupConfig(group);
for (ConsumerConfigInfo consumerConfigInfo : consumerConfigInfoList) {
brokerNameSet.addAll(consumerConfigInfo.getBrokerNameList());
}
}
catch (Exception e) {
throw Throwables.propagate(e);
}
return brokerNameSet;
}
@Override
public ConsumerConnection getConsumerConnection(String consumerGroup) {
try {
return mqAdminExt.examineConsumerConnectionInfo(consumerGroup);
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
@Override
public ConsumerRunningInfo getConsumerRunningInfo(String consumerGroup, String clientId, boolean jstack) {
try {
return mqAdminExt.getConsumerRunningInfo(consumerGroup, clientId, jstack);
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
| 15,722
|
Java
|
.java
| 318
| 39.537736
| 188
| 0.690958
|
romeoblog/spring-cloud
| 36
| 17
| 6
|
AGPL-3.0
|
9/4/2024, 7:29:21 PM (Europe/Amsterdam)
| false
| true
| false
| true
| true
| true
| true
| true
| 15,722
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.