hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
80a834eefb80f653a8133e5ae4138c6c39a00103
4,499
package com.samagra.parent.StudentAddressBook; import androidx.test.rule.ActivityTestRule; import com.samagra.parent.R; import com.samagra.parent.ui.HomeScreen.HomeActivity; import org.junit.Rule; import org.junit.Test; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard; import static androidx.test.espresso.action.ViewActions.pressBack; import static androidx.test.espresso.action.ViewActions.pressImeActionButton; import static androidx.test.espresso.action.ViewActions.replaceText; import static androidx.test.espresso.action.ViewActions.scrollTo; import static androidx.test.espresso.matcher.ViewMatchers.isRoot; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static com.samagra.parent.EspressoTools.ButtonDisplayandClick; import static com.samagra.parent.EspressoTools.EditInputDisplayed; import static com.samagra.parent.EspressoTools.ListAdapterDisplayandClick; import static com.samagra.parent.EspressoTools.waitFor; import static com.samagra.parent.EspressoTools.waitForButtonDisplay; import static com.samagra.parent.EspressoTools.withIndex; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.is; public class EditStudentBookTest { @Rule public ActivityTestRule<HomeActivity> mActivityTestRule = new ActivityTestRule<>(HomeActivity.class); @Test public void EditStudentBookTest() { checkRenderEditInputClick(R.id.student_address_book); onView(isRoot()).perform(waitFor(1000)); //Edit Student Data onView(withIndex(withId(R.id.edit), 2)).perform(click()); onView(isRoot()).perform(waitFor(1000)); //Update Student Name checkRenderEditInput(R.id.name,"Hello"); checkRenderButtonDisplayandClick(R.id.add_student,"UPDATE","android.widget.LinearLayout",11,0); onView(isRoot()).perform(waitFor(1000)); pressBack(); /* //Popup Save data buyyon click ViewInteraction appCompatButton_Save = onView( allOf(withId(R.id.save_students), withText(R.string.save), childAtPosition( childAtPosition( withClassName(is("android.widget.LinearLayout")), 2), 1), isDisplayed())); onView(isRoot()).perform(waitFor(1000)); appCompatButton_Save.perform(click()); onView(isRoot()).perform(waitFor(1000)); //Popup Add Now Button Click ViewInteraction appCompatButton_addnow = onView( allOf(withId(R.id.add_students), withText(R.string.update), childAtPosition( childAtPosition( withClassName(is("android.widget.LinearLayout")), 2), 0), isDisplayed())); onView(isRoot()).perform(waitFor(1000)); appCompatButton_addnow.perform(click()); onView(isRoot()).perform(waitFor(1000));*/ //Moving to Delete StudentBook } private void checkRenderEditInputClick(int id) { EditInputDisplayed(id).perform(click()); } private void checkRenderListAdapterDisplayandClick(int id, int classid, int postion, int childposition) { ListAdapterDisplayandClick(id,classid,postion,childposition).perform(click()); } private void checkRenderButtonDisplayandClick(int id, String withString, String classname, int postion, int childposition) { ButtonDisplayandClick(id,withString, classname,postion,childposition).perform(click()); } private void checkRenderEditInput(int id,String text) { EditInputDisplayed(id).perform(replaceText(text),closeSoftKeyboard()); } private void checkRenderEditInputImeClose(int id,String text) { EditInputDisplayed(id).perform(replaceText(text),pressImeActionButton()); } private void checkRenderwaitForButtonDisplay(int id, int childid, String withString, String classname, int postion, int childposition) { waitForButtonDisplay(id, childid, withString, classname, postion,childposition).perform(scrollTo(), click()); } }
39.814159
140
0.689042
50911237dbf4eaa4c8a8921873e308af1b58ee6f
5,031
package org.cmucreatelab.android.flutterprek.activities.student_section.coping_skills.coping_skill_cuddle_with_squeeze; import android.os.Bundle; import android.view.View; import android.widget.TextView; import org.cmucreatelab.android.flutterprek.BackgroundTimer; import org.cmucreatelab.android.flutterprek.R; import org.cmucreatelab.android.flutterprek.activities.student_section.coping_skills.AbstractCopingSkillActivity; public class SqueezeCuddleCopingSkillActivity extends AbstractCopingSkillActivity { private static final long DISPLAY_OVERLAY_AFTER_MILLISECONDS = 30000; private static final long DISMISS_OVERLAY_AFTER_MILLISECONDS = 10000; private static final long HEART_ANIMATION_MILLISECONDS = 2000; private boolean activityIsPaused = false; private boolean overlayIsDisplayed = false; private boolean heartAnimationIsReady = true; private SqueezeCuddleStateHandler squeezeCuddleStateHandler; private SqueezeCuddleCopingSkillAnimation squeezeCuddleCopingSkillAnimation; private final BackgroundTimer timerToDisplayOverlay = new BackgroundTimer(DISPLAY_OVERLAY_AFTER_MILLISECONDS, new BackgroundTimer.TimeExpireListener() { @Override public void timerExpired() { displayOverlay(true); } }); private final BackgroundTimer timerToExitFromOverlay = new BackgroundTimer(DISMISS_OVERLAY_AFTER_MILLISECONDS, new BackgroundTimer.TimeExpireListener() { @Override public void timerExpired() { releaseOverlayTimers(); finish(); } }); private final BackgroundTimer timerToWaitForNextHeartAnimation = new BackgroundTimer(HEART_ANIMATION_MILLISECONDS, new BackgroundTimer.TimeExpireListener() { @Override public void timerExpired() { heartAnimationIsReady = true; } }); private void playAudioInstructions() { playAudio("etc/audio_prompts/audio_sheep_hug.wav"); } private void playAudioOverlay() { playAudio("etc/audio_prompts/audio_sheep_overlay.wav"); } public boolean isPaused() { return activityIsPaused; } public void initializeSqueezeCuddleActivity() { releaseOverlayTimers(); displayOverlay(false); squeezeCuddleStateHandler.lookForSqueeze(); timerToDisplayOverlay.startTimer(); playAudioInstructions(); } public void doSqueeze() { if (heartAnimationIsReady) { heartAnimationIsReady = false; runOnUiThread(new Runnable() { @Override public void run() { try { squeezeCuddleCopingSkillAnimation.startAnimation(); } catch (InterruptedException e) { e.printStackTrace(); } timerToWaitForNextHeartAnimation.startTimer(); } }); } } public void displayOverlay(final boolean toDisplay) { this.overlayIsDisplayed = toDisplay; runOnUiThread(new Runnable() { @Override public void run() { if (toDisplay) { findViewById(R.id.overlayYesNo).setVisibility(View.VISIBLE); timerToExitFromOverlay.startTimer(); playAudioOverlay(); } else { findViewById(R.id.overlayYesNo).setVisibility(View.GONE); } } }); } public void releaseOverlayTimers() { timerToDisplayOverlay.stopTimer(); timerToExitFromOverlay.stopTimer(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); squeezeCuddleStateHandler = new SqueezeCuddleStateHandler(this); squeezeCuddleCopingSkillAnimation = new SqueezeCuddleCopingSkillAnimation(this); ((TextView)findViewById(R.id.textViewOverlayTitle)).setText(R.string.coping_skill_sheep_overlay); findViewById(R.id.imageViewYes).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { initializeSqueezeCuddleActivity(); } }); findViewById(R.id.imageViewNo).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override protected void onPause() { activityIsPaused = true; releaseOverlayTimers(); super.onPause(); } @Override protected void onResume() { activityIsPaused = false; if (overlayIsDisplayed) { timerToExitFromOverlay.startTimer(); } else { initializeSqueezeCuddleActivity(); } super.onResume(); } @Override public int getResourceIdForActivityLayout() { return R.layout.activity_squeeze_cuddle_coping_skill; } }
31.44375
161
0.652157
cc1f6868051f6f8ea78c26079f0286223b9af337
3,358
package scripting; import backend.game_engine.ResultQuadPredicate; import backend.player.Team; import backend.unit.Unit; import backend.unit.properties.ActiveAbility; import backend.unit.properties.InteractionModifier; import backend.util.*; import util.io.Serializer; import util.io.Unserializer; import java.io.Serializable; import java.util.*; /** * @author Created by th174 on 4/7/2017. */ public interface VoogaScriptEngine extends Serializer, Unserializer, InteractionModifier.Modifier, TriggeredEffect.Effect, ActiveAbility.AbilityEffect, ResultQuadPredicate, Requirement.SerializableBiPredicate, Actionable.SerializableBiConsumer, Serializable { ResourceBundle RESOURCES = ResourceBundle.getBundle("resources/Scripting", Locale.US); VoogaScriptEngine setScript(String script) throws VoogaScriptException; Object eval(Map<String, Object> bindings) throws VoogaScriptException; @Override default ResultQuadPredicate.Result determine(Team team, GameplayState gameState) { try { return ResultQuadPredicate.Result.valueOf((String) eval(createBindings("team", team, "gameState", gameState))); } catch (ClassCastException e) { throw new VoogaScriptException(e); } } @Override default Object doUnserialize(Serializable serializableObject) throws VoogaScriptException { try { return eval(createBindings("serializedObject", serializableObject)); } catch (ClassCastException e) { throw new VoogaScriptException(e); } } @Override default Serializable doSerialize(Object object) throws VoogaScriptException { try { return (Serializable) eval(createBindings("object", object)); } catch (ClassCastException e) { throw new VoogaScriptException(e); } } @Override default void affect(Unit unit, Event event, GameplayState gameState) { eval(createBindings("unit", unit, "event", event, "gameState", gameState)); } @Override default void useAbility(Unit user, VoogaEntity target, GameplayState gameState) { eval(createBindings("user", user, "target", target, "gameState", gameState)); } @Override default Object modify(Object originalValue, Unit agent, Unit target, GameplayState gameState) { return eval(createBindings("originalValue", originalValue, "agent", agent, "target", target, "gameState", gameState)); } @Override default boolean test(Team team, ReadonlyGameplayState gameState) { Object nonBooleanValue = eval(createBindings("team", team, "gameState", gameState)); if (nonBooleanValue instanceof String) { try { return Boolean.valueOf((String) nonBooleanValue); } catch (Exception e) { return !((String) nonBooleanValue).isEmpty(); } } else if (nonBooleanValue instanceof Boolean) { return (Boolean) nonBooleanValue; } else { return Objects.nonNull(nonBooleanValue); } } @Override default void accept(Team team, ReadonlyGameplayState gameState) { eval(createBindings("team", team, "gameState", gameState)); } static HashMap<String, Object> createBindings(Object... params) { HashMap<String, Object> bindings = new LinkedHashMap<>(); try { for (int i = 0; i < params.length; i += 2) { bindings.put((String) params[i], params[i + 1]); } } catch (ClassCastException | IndexOutOfBoundsException e) { throw new Error("Invalid arguments, must be name, binding, name, binding, name binding etc."); } return bindings; } }
33.58
259
0.754318
124f22ae0173ecb7f22cb74d37177689875d978b
176
package main.java.exception; public class IllegalNumberException extends Exception { @Override public String toString() { return "Illegal input data"; } }
19.555556
55
0.698864
813040326804f27ef843262912f908e13167117d
2,884
/*- * =========================================================================== * meta-freemarker * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright (C) 2019 - 2022 Kapralov Sergey * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * 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.pragmaticobjects.oo.meta.freemarker; import com.pragmaticobjects.oo.tests.AssertAssertionFails; import com.pragmaticobjects.oo.tests.AssertAssertionPasses; import com.pragmaticobjects.oo.tests.TestCase; import com.pragmaticobjects.oo.tests.junit5.TestsSuite; import io.vavr.collection.HashMap; import io.vavr.collection.Map; /** * * @author skapral */ public class AssertFreemarkerModelValueTest extends TestsSuite { public AssertFreemarkerModelValueTest() { super( new TestCase( "positive test", new AssertAssertionPasses( new AssertFreemarkerModelValue( new FAMSimple(HashMap.of("A", 42)), "A", 42 ) ) ), new TestCase( "negative test", new AssertAssertionFails( new AssertFreemarkerModelValue( new FAMSimple(HashMap.of("A", 42)), "A", 123 ) ) ) ); } } class FAMSimple implements FreemarkerArtifactModel { private final Map<String, Object> contents; public FAMSimple(Map<String, Object> contents) { this.contents = contents; } @Override public final <T> T get(String item) { return (T) contents.get(item).get(); } }
37.947368
80
0.581831
6b459a2ee47a8d5499307532e37344452b5f96fe
2,909
/* * MIT License * * Copyright (c) 2017 N Abhishek (aka Kodatos) * * 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.kodatos.cumulonimbus; import android.os.Bundle; import com.github.paolorotolo.appintro.AppIntro; import com.kodatos.cumulonimbus.uihelper.welcome.PreferenceSlideFragment; import com.kodatos.cumulonimbus.uihelper.welcome.SimpleSlideFragment; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; public class WelcomeActivity extends AppIntro { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addSlide(SimpleSlideFragment.newInstance(getString(R.string.welcome_title_1), getString(R.string.welcome_description_1), R.drawable.ic_launcher_foreground, ContextCompat.getColor(this, R.color.first_slide_background))); addSlide(SimpleSlideFragment.newInstance(getString(R.string.welcome_title_2), getString(R.string.welcome_description_2), R.drawable.ic_location_permission, ContextCompat.getColor(this, R.color.second_slide_background))); addSlide(PreferenceSlideFragment.newInstance(ContextCompat.getColor(this, R.color.third_slide_background))); addSlide(SimpleSlideFragment.newInstance(getString(R.string.welcome_title_4), getString(R.string.welcome_description_4), R.drawable.ic_sun_emoticon, ContextCompat.getColor(this, R.color._01d_background))); //askForPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 2); setColorTransitionsEnabled(true); showSkipButton(false); setWizardMode(true); } @Override public void onSlideChanged(@Nullable Fragment oldFragment, @Nullable Fragment newFragment) { if (newFragment == null) { setResult(RESULT_OK); finish(); } } }
44.753846
228
0.768305
e382384180aacea3433e1b3dfce1422b4610843d
25,526
/** * Licensed to Apereo under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright ownership. Apereo * 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 the * following location: * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>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.apereo.portal.groups.grouper; import edu.internet2.middleware.grouperClient.api.GcAddMember; import edu.internet2.middleware.grouperClient.api.GcFindGroups; import edu.internet2.middleware.grouperClient.api.GcGetGroups; import edu.internet2.middleware.grouperClient.api.GcGetMembers; import edu.internet2.middleware.grouperClient.api.GcGetSubjects; import edu.internet2.middleware.grouperClient.api.GcGroupDelete; import edu.internet2.middleware.grouperClient.api.GcGroupSave; import edu.internet2.middleware.grouperClient.api.GcHasMember; import edu.internet2.middleware.grouperClient.util.GrouperClientUtils; import edu.internet2.middleware.grouperClient.ws.StemScope; import edu.internet2.middleware.grouperClient.ws.beans.WsFindGroupsResults; import edu.internet2.middleware.grouperClient.ws.beans.WsGetGroupsResult; import edu.internet2.middleware.grouperClient.ws.beans.WsGetGroupsResults; import edu.internet2.middleware.grouperClient.ws.beans.WsGetMembersResults; import edu.internet2.middleware.grouperClient.ws.beans.WsGetSubjectsResults; import edu.internet2.middleware.grouperClient.ws.beans.WsGroup; import edu.internet2.middleware.grouperClient.ws.beans.WsGroupLookup; import edu.internet2.middleware.grouperClient.ws.beans.WsGroupToSave; import edu.internet2.middleware.grouperClient.ws.beans.WsHasMemberResult; import edu.internet2.middleware.grouperClient.ws.beans.WsHasMemberResults; import edu.internet2.middleware.grouperClient.ws.beans.WsQueryFilter; import edu.internet2.middleware.grouperClient.ws.beans.WsStemLookup; import edu.internet2.middleware.grouperClient.ws.beans.WsSubject; import edu.internet2.middleware.grouperClient.ws.beans.WsSubjectLookup; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apereo.portal.EntityIdentifier; import org.apereo.portal.groups.EntityGroupImpl; import org.apereo.portal.groups.EntityImpl; import org.apereo.portal.groups.GroupsException; import org.apereo.portal.groups.ICompositeGroupService; import org.apereo.portal.groups.IEntity; import org.apereo.portal.groups.IEntityGroup; import org.apereo.portal.groups.IEntityGroupStore; import org.apereo.portal.groups.IEntitySearcher; import org.apereo.portal.groups.IEntityStore; import org.apereo.portal.groups.IGroupMember; import org.apereo.portal.groups.ILockableEntityGroup; import org.apereo.portal.security.IPerson; import org.apereo.portal.spring.locator.EntityTypesLocator; /** * GrouperEntityGroupStore provides an implementation of the group store interface capable of * retrieving groups information from Grouper web services. This implementation uses the standard * Grouper client jar to search for group information. It does not currently support write access or * group locking. */ public class GrouperEntityGroupStore implements IEntityGroupStore, IEntityStore, IEntitySearcher { private static final String STEM_PREFIX = "uportal.stem"; /** Logger. */ protected static final Log LOGGER = LogFactory.getLog(GrouperEntityGroupStoreFactory.class); /** Package protected constructor used by the factory method. */ GrouperEntityGroupStore() { /* Package protected. */ if (LOGGER.isDebugEnabled()) { LOGGER.debug(this + " created"); } } /* (non-Javadoc) * @see org.apereo.portal.groups.IEntityGroupStore#contains(org.apereo.portal.groups.IEntityGroup, org.apereo.portal.groups.IGroupMember) */ public boolean contains(IEntityGroup group, IGroupMember member) throws GroupsException { String groupContainerName = group.getLocalKey(); String groupMemberName = member.getKey(); if (!validKey(groupContainerName) || !validKey(groupMemberName)) { return false; } GcHasMember gcHasMember = new GcHasMember(); gcHasMember.assignGroupName(groupContainerName); gcHasMember.addSubjectLookup(new WsSubjectLookup(null, "g:gsa", groupMemberName)); WsHasMemberResults wsHasMemberResults = gcHasMember.execute(); if (GrouperClientUtils.length(wsHasMemberResults.getResults()) == 1) { WsHasMemberResult wsHasMemberResult = wsHasMemberResults.getResults()[0]; return StringUtils.equals( "IS_MEMBER", wsHasMemberResult.getResultMetadata().getResultCode()); } return false; } /* (non-Javadoc) * @see org.apereo.portal.groups.IEntityGroupStore#find(java.lang.String) */ public IEntityGroup find(String key) throws GroupsException { try { // Search the Grouper server for groups with the specified local // key if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for a direct match for key: " + key); } WsGroup wsGroup = findGroupFromKey(key); if (wsGroup == null) { return null; } IEntityGroup group = createUportalGroupFromGrouperGroup(wsGroup); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Retrieved group from the Grouper server matching key " + key + ": " + group.toString()); } // return the group return group; } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "group with key " + key + " from Grouper web services: " + e.getMessage()); return null; } } /* (non-Javadoc) * @see org.apereo.portal.groups.IEntityGroupStore#findParentGroups(org.apereo.portal.groups.IGroupMember) */ @SuppressWarnings("unchecked") public Iterator findParentGroups(IGroupMember gm) throws GroupsException { final List<IEntityGroup> parents = new LinkedList<IEntityGroup>(); GcGetGroups getGroups = new GcGetGroups(); String uportalStem = getStemPrefix(); // if only searching in a specific stem if (!StringUtils.isBlank(uportalStem)) { getGroups.assignStemScope(StemScope.ALL_IN_SUBTREE); getGroups.assignWsStemLookup(new WsStemLookup(uportalStem, null)); } String key = null; String subjectSourceId = null; if (gm.isGroup()) { key = ((IEntityGroup) gm).getLocalKey(); if (!validKey(key)) { return parents.iterator(); } subjectSourceId = "g:gsa"; } else { // Determine the key to use for this entity. If the entity is a // group, we should use the group's local key (excluding the // "grouper." portion of the full key. If the entity is not a // group type, just use the key. key = gm.getKey(); } getGroups.addSubjectLookup(new WsSubjectLookup(null, subjectSourceId, key)); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for parent groups of the entity with key: " + key); } try { WsGetGroupsResults results = getGroups.execute(); if (results == null || results.getResults() == null || results.getResults().length != 1) { LOGGER.debug("Grouper service returned no matches for key " + key); return parents.iterator(); } WsGetGroupsResult wsg = results.getResults()[0]; if (wsg.getWsGroups() != null) { for (WsGroup g : wsg.getWsGroups()) { if (LOGGER.isDebugEnabled()) { LOGGER.trace("Retrieved group: " + g.getName()); } IEntityGroup parent = createUportalGroupFromGrouperGroup(g); parents.add(parent); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Retrieved " + parents.size() + " parent groups of entity with key " + key); } } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "parents for entity with key " + key + " from Grouper web services: " + e.getMessage()); return Collections.<IEntityGroup>emptyList().iterator(); } return parents.iterator(); } /* (non-Javadoc) * @see org.apereo.portal.groups.IEntityGroupStore#findEntitiesForGroup(org.apereo.portal.groups.IEntityGroup) */ @SuppressWarnings("unchecked") public Iterator findEntitiesForGroup(IEntityGroup group) throws GroupsException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for members of the group with key: " + group.getKey()); } try { // execute a search for members of the specified group GcGetMembers getGroupsMembers = new GcGetMembers(); getGroupsMembers.addGroupName(group.getLocalKey()); getGroupsMembers.assignIncludeSubjectDetail(true); WsGetMembersResults results = getGroupsMembers.execute(); if (results == null || results.getResults() == null || results.getResults().length == 0 || results.getResults()[0].getWsSubjects() == null) { LOGGER.debug("No members found for Grouper group with key " + group.getLocalKey()); return Collections.<IGroupMember>emptyList().iterator(); } WsSubject[] gInfos = results.getResults()[0].getWsSubjects(); final List<IGroupMember> members = new ArrayList<IGroupMember>(gInfos.length); // add each result to the member list for (WsSubject gInfo : gInfos) { // if the member is not a group (aka person) if (!StringUtils.equals(gInfo.getSourceId(), "g:gsa")) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "creating leaf member:" + gInfo.getId() + " and name: " + gInfo.getName() + " from group: " + group.getLocalKey()); } // use the name instead of id as it shows better in the display IGroupMember member = new EntityImpl(gInfo.getName(), IPerson.class); members.add(member); } } // return an iterator for the assembled group return members.iterator(); } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "member entities of group with key " + group.getKey() + " from Grouper web services: " + e.getMessage()); return Collections.<IGroupMember>emptyList().iterator(); } } /* (non-Javadoc) * @see org.apereo.portal.groups.IEntityGroupStore#findMemberGroupKeys(org.apereo.portal.groups.IEntityGroup) */ @SuppressWarnings("unchecked") public String[] findMemberGroupKeys(IEntityGroup group) throws GroupsException { // first the get an iterator for the member groups final Iterator<IEntityGroup> it = findMemberGroups(group); // construct a list of group keys from this iterator List<String> keys = new ArrayList<String>(); while (it.hasNext()) { IEntityGroup eg = it.next(); keys.add(eg.getKey()); } // return an iterator over the assembled list return keys.toArray(new String[keys.size()]); } @SuppressWarnings("unchecked") public Iterator findMemberGroups(IEntityGroup group) throws GroupsException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching for group-type members of group with key: " + group.getKey()); } try { if (!validKey(group.getLocalKey())) { return Collections.<IEntityGroup>emptyList().iterator(); } GcGetMembers gcGetMembers = new GcGetMembers(); gcGetMembers.addGroupName(group.getLocalKey()); gcGetMembers.assignIncludeSubjectDetail(true); gcGetMembers.addSourceId("g:gsa"); WsGetMembersResults results = gcGetMembers.execute(); if (results == null || results.getResults() == null || results.getResults().length == 0 || results.getResults()[0].getWsSubjects() == null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "No group-type members found for group with key " + group.getKey()); } return Collections.<IEntityGroup>emptyList().iterator(); } final List<IEntityGroup> members = new ArrayList<IEntityGroup>(); WsSubject[] subjects = results.getResults()[0].getWsSubjects(); for (WsSubject wsSubject : subjects) { if (validKey(wsSubject.getName())) { WsGroup wsGroup = findGroupFromKey(wsSubject.getName()); if (wsGroup != null) { IEntityGroup member = createUportalGroupFromGrouperGroup(wsGroup); members.add(member); if (LOGGER.isTraceEnabled()) { LOGGER.trace("found IEntityGroup member: " + member); } } } } return members.iterator(); } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "member groups of group with key " + group.getKey() + " from Grouper web services: " + e.getMessage()); return Collections.<IGroupMember>emptyList().iterator(); } } /* (non-Javadoc) * @see org.apereo.portal.groups.IEntityGroupStore#searchForGroups(java.lang.String, int, java.lang.Class) */ public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) { if (validKey(g.getName())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved group: " + g.getName()); } groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class)); } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Returning " + groups.size() + " results for query " + query); } return groups.toArray(new EntityIdentifier[groups.size()]); } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "search results for query " + query + " and entity type " + leaftype.getCanonicalName() + " : " + e.getMessage()); return new EntityIdentifier[] {}; } } /** * @see IEntitySearcher#searchForEntities(java.lang.String, * org.apereo.portal.groups.IGroupConstants.SearchMethod, java.lang.Class) */ @SuppressWarnings("unchecked") public EntityIdentifier[] searchForEntities(String query, SearchMethod method, Class type) throws GroupsException { // only search for groups if (type != IPerson.class) { return new EntityIdentifier[] {}; } List<EntityIdentifier> entityIdentifiers = new ArrayList<EntityIdentifier>(); try { GcGetSubjects subjects = new GcGetSubjects(); subjects.assignIncludeSubjectDetail(true); WsGetSubjectsResults results = subjects.assignSearchString(query).execute(); if (results != null && results.getWsSubjects() != null) { for (WsSubject wsSubject : results.getWsSubjects()) { entityIdentifiers.add( new EntityIdentifier( wsSubject.getName(), ICompositeGroupService.LEAF_ENTITY_TYPE)); } } return entityIdentifiers.toArray(new EntityIdentifier[entityIdentifiers.size()]); } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "search results for query " + query + " and entity type " + type.getCanonicalName() + " : " + e.getMessage()); return new EntityIdentifier[] {}; } } /** @see IEntityStore#newInstance(java.lang.String, java.lang.Class) */ @SuppressWarnings("unchecked") public IEntity newInstance(String key, Class type) throws GroupsException { if (EntityTypesLocator.getEntityTypes().getEntityIDFromType(type) == null) { throw new GroupsException("Invalid group type: " + type); } return new EntityImpl(key, type); } /** * Construct an IEntityGroup from a Grouper WsGroup. * * @param wsGroup * @return the group */ protected IEntityGroup createUportalGroupFromGrouperGroup(WsGroup wsGroup) { IEntityGroup iEntityGroup = new EntityGroupImpl(wsGroup.getName(), IPerson.class); // need to set the group name and description to the actual // display name and description iEntityGroup.setName(wsGroup.getDisplayName()); iEntityGroup.setDescription(wsGroup.getDescription()); return iEntityGroup; } /** * Find the Grouper group matching the specified key. * * @param key * @return the group or null */ protected WsGroup findGroupFromKey(String key) { WsGroup wsGroup = null; if (key != null) { GcFindGroups gcFindGroups = new GcFindGroups(); gcFindGroups.addGroupName(key); WsFindGroupsResults results = gcFindGroups.execute(); // if no results were returned, return null if (results != null && results.getGroupResults() != null && results.getGroupResults().length > 0) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "found group from key " + key + ": " + results.getGroupResults()[0]); } wsGroup = results.getGroupResults()[0]; } } return wsGroup; } /** * Get the prefix for the stem containing uPortal groups. If this value is non-empty, all groups * will be required to be prefixed with the specified stem name. * * @return the uportal stem in the registry, without trailing colon */ protected static String getStemPrefix() { String uportalStem = GrouperClientUtils.propertiesValue(STEM_PREFIX, false); // make sure it ends in colon if (!StringUtils.isBlank(uportalStem)) { if (uportalStem.endsWith(":")) { uportalStem = uportalStem.substring(0, uportalStem.length() - 1); } } return uportalStem; } /** * @param key * @return true if ok key (group name) false if not */ protected static boolean validKey(String key) { String uportalStem = getStemPrefix(); if (!StringUtils.isBlank(uportalStem) && (StringUtils.isBlank(key) || !key.startsWith(uportalStem.concat(":")))) { // if the uPortal stem prefix is specified and the key is blank // or does not contain the stem prefix, return false return false; } else { // otherwise, indicate that the key is valid return true; } } /** @see IEntityGroupStore#update(IEntityGroup) */ public void update(IEntityGroup group) throws GroupsException { // assume key is fully qualified group name String groupName = group.getLocalKey(); String description = group.getDescription(); // the name is the displayExtension String displayExtension = group.getName(); WsGroupToSave wsGroupToSave = new WsGroupToSave(); wsGroupToSave.setCreateParentStemsIfNotExist("T"); wsGroupToSave.setWsGroupLookup(new WsGroupLookup(groupName, null)); WsGroup wsGroup = new WsGroup(); wsGroup.setName(groupName); wsGroup.setDisplayExtension(displayExtension); wsGroup.setDescription(description); wsGroupToSave.setWsGroup(wsGroup); new GcGroupSave().addGroupToSave(wsGroupToSave).execute(); updateMembers(group); } /** @see IEntityGroupStore#updateMembers(IEntityGroup) */ public void updateMembers(IEntityGroup group) throws GroupsException { // assume key is fully qualified group name String groupName = group.getLocalKey(); GcAddMember gcAddMember = new GcAddMember().assignGroupName(groupName); for (IGroupMember iGroupMember : group.getChildren()) { EntityIdentifier entityIdentifier = iGroupMember.getEntityIdentifier(); String identifier = entityIdentifier.getKey(); gcAddMember.addSubjectIdentifier(identifier); } gcAddMember.execute(); } /** @see IEntityGroupStore#delete(IEntityGroup) */ public void delete(IEntityGroup group) throws GroupsException { String groupName = group.getLocalKey(); new GcGroupDelete().addGroupLookup(new WsGroupLookup(groupName, null)).execute(); } /** @see IEntityGroupStore#findLockable(java.lang.String) */ public ILockableEntityGroup findLockable(String key) throws GroupsException { throw new UnsupportedOperationException( "Group locking is not supported by the Grouper groups service"); } /* * @see * org.apereo.portal.groups.IEntityGroupStore#newInstance(java.lang.Class) */ @SuppressWarnings("unchecked") public IEntityGroup newInstance(Class entityType) throws GroupsException { throw new UnsupportedOperationException( "Group updates are not supported by the Grouper groups service"); } }
39.698289
141
0.599976
9daef3b83d9ee9be1fc72b9640ac417b9ebbbc11
2,259
package com.tosh.dude; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.tosh.dude.Adapter.LeagueAdapter; import com.tosh.dude.Api.ApiClient; import com.tosh.dude.Api.LeagueService; import com.tosh.dude.Models.DudeApi; import com.tosh.dude.Models.League; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity { private ArrayList<League> leagues; private LeagueAdapter leagueAdapter; private RecyclerView recyclerView; @BindView(R.id.btn_fixtures) Button btnFixtures; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); getLeagues(); } private Object getLeagues() { LeagueService leagueService = ApiClient.getService(); Call<DudeApi> call = leagueService.fetchAllLeagues(); call.enqueue(new Callback<DudeApi>() { @Override public void onResponse(Call<DudeApi> call, Response<DudeApi> response) { DudeApi dudeApi = response.body(); if(dudeApi != null && dudeApi.getApi() != null){ leagues = (ArrayList<League>)dudeApi.getApi().getLeagues(); viewData(); } } @Override public void onFailure(Call<DudeApi> call, Throwable t) { } }); return leagues; } private void viewData() { recyclerView = (RecyclerView) findViewById(R.id.rv_leagues_list); leagueAdapter = new LeagueAdapter(leagues); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(leagueAdapter); } }
24.824176
94
0.686587
73a0bc3d07663e625b12745314273b4396f647f9
559
package voldemort.store.readonly.io; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; /** * A closeable which is smart enough to work on byte buffers. */ public class ByteBufferCloser implements Closeable { private ByteBuffer buff; public ByteBufferCloser(ByteBuffer buff) { this.buff = buff; } @Override public void close() throws IOException { sun.misc.Cleaner cl = ((sun.nio.ch.DirectBuffer) buff).cleaner(); if(cl != null) { cl.clean(); } } }
18.633333
73
0.647585
019444917a53d515910daaa2148d7b3eae08928e
242
package exileMod.patches; import com.evacipated.cardcrawl.modthespire.lib.SpireEnum; import com.megacrit.cardcrawl.characters.AbstractPlayer; public class ExileEnum { @SpireEnum public static AbstractPlayer.PlayerClass EXHILE; }
24.2
59
0.805785
bbaa41706acb103a6b8ce5c7ff219ec77796ec4c
35,237
package android.support.v4.widget; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.os.Build.VERSION; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.v4.content.ContextCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.NestedScrollingChild; import android.support.v4.view.NestedScrollingChildHelper; import android.support.v4.view.NestedScrollingParent; import android.support.v4.view.NestedScrollingParentHelper; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.DecelerateInterpolator; import android.view.animation.Transformation; import android.widget.AbsListView; import com.itextpdf.text.pdf.BaseField; public class SwipeRefreshLayout extends ViewGroup implements NestedScrollingParent, NestedScrollingChild { private static final int ALPHA_ANIMATION_DURATION = 300; private static final int ANIMATE_TO_START_DURATION = 200; private static final int ANIMATE_TO_TRIGGER_DURATION = 200; private static final int CIRCLE_BG_LIGHT = -328966; @VisibleForTesting static final int CIRCLE_DIAMETER = 40; @VisibleForTesting static final int CIRCLE_DIAMETER_LARGE = 56; private static final float DECELERATE_INTERPOLATION_FACTOR = 2.0f; public static final int DEFAULT = 1; private static final int DEFAULT_CIRCLE_TARGET = 64; private static final float DRAG_RATE = 0.5f; private static final int INVALID_POINTER = -1; public static final int LARGE = 0; private static final int[] LAYOUT_ATTRS = new int[]{16842766}; private static final String LOG_TAG = SwipeRefreshLayout.class.getSimpleName(); private static final int MAX_ALPHA = 255; private static final float MAX_PROGRESS_ANGLE = 0.8f; private static final int SCALE_DOWN_DURATION = 150; private static final int STARTING_PROGRESS_ALPHA = 76; private int mActivePointerId; private Animation mAlphaMaxAnimation; private Animation mAlphaStartAnimation; private final Animation mAnimateToCorrectPosition; private final Animation mAnimateToStartPosition; private OnChildScrollUpCallback mChildScrollUpCallback; private int mCircleDiameter; CircleImageView mCircleView; private int mCircleViewIndex; int mCurrentTargetOffsetTop; private final DecelerateInterpolator mDecelerateInterpolator; protected int mFrom; private float mInitialDownY; private float mInitialMotionY; private boolean mIsBeingDragged; OnRefreshListener mListener; private int mMediumAnimationDuration; private boolean mNestedScrollInProgress; private final NestedScrollingChildHelper mNestedScrollingChildHelper; private final NestedScrollingParentHelper mNestedScrollingParentHelper; boolean mNotify; protected int mOriginalOffsetTop; private final int[] mParentOffsetInWindow; private final int[] mParentScrollConsumed; MaterialProgressDrawable mProgress; private AnimationListener mRefreshListener; boolean mRefreshing; private boolean mReturningToStart; boolean mScale; private Animation mScaleAnimation; private Animation mScaleDownAnimation; private Animation mScaleDownToStartAnimation; int mSpinnerOffsetEnd; float mStartingScale; private View mTarget; private float mTotalDragDistance; private float mTotalUnconsumed; private int mTouchSlop; boolean mUsingCustomStart; class C02471 implements AnimationListener { C02471() { } public void onAnimationStart(Animation animation) { } public void onAnimationRepeat(Animation animation) { } @SuppressLint({"NewApi"}) public void onAnimationEnd(Animation animation) { if (SwipeRefreshLayout.this.mRefreshing) { SwipeRefreshLayout.this.mProgress.setAlpha(255); SwipeRefreshLayout.this.mProgress.start(); if (SwipeRefreshLayout.this.mNotify && SwipeRefreshLayout.this.mListener != null) { SwipeRefreshLayout.this.mListener.onRefresh(); } SwipeRefreshLayout.this.mCurrentTargetOffsetTop = SwipeRefreshLayout.this.mCircleView.getTop(); return; } SwipeRefreshLayout.this.reset(); } } class C02482 extends Animation { C02482() { } public void applyTransformation(float interpolatedTime, Transformation t) { SwipeRefreshLayout.this.setAnimationProgress(interpolatedTime); } } class C02493 extends Animation { C02493() { } public void applyTransformation(float interpolatedTime, Transformation t) { SwipeRefreshLayout.this.setAnimationProgress(BaseField.BORDER_WIDTH_THIN - interpolatedTime); } } class C02515 implements AnimationListener { C02515() { } public void onAnimationStart(Animation animation) { } public void onAnimationEnd(Animation animation) { if (!SwipeRefreshLayout.this.mScale) { SwipeRefreshLayout.this.startScaleDownAnimation(null); } } public void onAnimationRepeat(Animation animation) { } } class C02526 extends Animation { C02526() { } public void applyTransformation(float interpolatedTime, Transformation t) { int endTarget; if (SwipeRefreshLayout.this.mUsingCustomStart) { endTarget = SwipeRefreshLayout.this.mSpinnerOffsetEnd; } else { endTarget = SwipeRefreshLayout.this.mSpinnerOffsetEnd - Math.abs(SwipeRefreshLayout.this.mOriginalOffsetTop); } SwipeRefreshLayout.this.setTargetOffsetTopAndBottom((SwipeRefreshLayout.this.mFrom + ((int) (((float) (endTarget - SwipeRefreshLayout.this.mFrom)) * interpolatedTime))) - SwipeRefreshLayout.this.mCircleView.getTop(), false); SwipeRefreshLayout.this.mProgress.setArrowScale(BaseField.BORDER_WIDTH_THIN - interpolatedTime); } } class C02537 extends Animation { C02537() { } public void applyTransformation(float interpolatedTime, Transformation t) { SwipeRefreshLayout.this.moveToStart(interpolatedTime); } } class C02548 extends Animation { C02548() { } public void applyTransformation(float interpolatedTime, Transformation t) { SwipeRefreshLayout.this.setAnimationProgress(SwipeRefreshLayout.this.mStartingScale + ((-SwipeRefreshLayout.this.mStartingScale) * interpolatedTime)); SwipeRefreshLayout.this.moveToStart(interpolatedTime); } } public interface OnChildScrollUpCallback { boolean canChildScrollUp(SwipeRefreshLayout swipeRefreshLayout, @Nullable View view); } public interface OnRefreshListener { void onRefresh(); } void reset() { this.mCircleView.clearAnimation(); this.mProgress.stop(); this.mCircleView.setVisibility(8); setColorViewAlpha(255); if (this.mScale) { setAnimationProgress(0.0f); } else { setTargetOffsetTopAndBottom(this.mOriginalOffsetTop - this.mCurrentTargetOffsetTop, true); } this.mCurrentTargetOffsetTop = this.mCircleView.getTop(); } public void setEnabled(boolean enabled) { super.setEnabled(enabled); if (!enabled) { reset(); } } protected void onDetachedFromWindow() { super.onDetachedFromWindow(); reset(); } @SuppressLint({"NewApi"}) private void setColorViewAlpha(int targetAlpha) { this.mCircleView.getBackground().setAlpha(targetAlpha); this.mProgress.setAlpha(targetAlpha); } public void setProgressViewOffset(boolean scale, int start, int end) { this.mScale = scale; this.mOriginalOffsetTop = start; this.mSpinnerOffsetEnd = end; this.mUsingCustomStart = true; reset(); this.mRefreshing = false; } public int getProgressViewStartOffset() { return this.mOriginalOffsetTop; } public int getProgressViewEndOffset() { return this.mSpinnerOffsetEnd; } public void setProgressViewEndTarget(boolean scale, int end) { this.mSpinnerOffsetEnd = end; this.mScale = scale; this.mCircleView.invalidate(); } public void setSize(int size) { if (size == 0 || size == 1) { DisplayMetrics metrics = getResources().getDisplayMetrics(); if (size == 0) { this.mCircleDiameter = (int) (56.0f * metrics.density); } else { this.mCircleDiameter = (int) (40.0f * metrics.density); } this.mCircleView.setImageDrawable(null); this.mProgress.updateSizes(size); this.mCircleView.setImageDrawable(this.mProgress); } } public SwipeRefreshLayout(Context context) { this(context, null); } public SwipeRefreshLayout(Context context, AttributeSet attrs) { super(context, attrs); this.mRefreshing = false; this.mTotalDragDistance = -1.0f; this.mParentScrollConsumed = new int[2]; this.mParentOffsetInWindow = new int[2]; this.mActivePointerId = -1; this.mCircleViewIndex = -1; this.mRefreshListener = new C02471(); this.mAnimateToCorrectPosition = new C02526(); this.mAnimateToStartPosition = new C02537(); this.mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); this.mMediumAnimationDuration = getResources().getInteger(17694721); setWillNotDraw(false); this.mDecelerateInterpolator = new DecelerateInterpolator(2.0f); DisplayMetrics metrics = getResources().getDisplayMetrics(); this.mCircleDiameter = (int) (40.0f * metrics.density); createProgressView(); ViewCompat.setChildrenDrawingOrderEnabled(this, true); this.mSpinnerOffsetEnd = (int) (64.0f * metrics.density); this.mTotalDragDistance = (float) this.mSpinnerOffsetEnd; this.mNestedScrollingParentHelper = new NestedScrollingParentHelper(this); this.mNestedScrollingChildHelper = new NestedScrollingChildHelper(this); setNestedScrollingEnabled(true); int i = -this.mCircleDiameter; this.mCurrentTargetOffsetTop = i; this.mOriginalOffsetTop = i; moveToStart(BaseField.BORDER_WIDTH_THIN); TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS); setEnabled(a.getBoolean(0, true)); a.recycle(); } protected int getChildDrawingOrder(int childCount, int i) { if (this.mCircleViewIndex < 0) { return i; } if (i == childCount - 1) { return this.mCircleViewIndex; } if (i >= this.mCircleViewIndex) { return i + 1; } return i; } private void createProgressView() { this.mCircleView = new CircleImageView(getContext(), CIRCLE_BG_LIGHT); this.mProgress = new MaterialProgressDrawable(getContext(), this); this.mProgress.setBackgroundColor(CIRCLE_BG_LIGHT); this.mCircleView.setImageDrawable(this.mProgress); this.mCircleView.setVisibility(8); addView(this.mCircleView); } public void setOnRefreshListener(OnRefreshListener listener) { this.mListener = listener; } private boolean isAlphaUsedForScale() { return VERSION.SDK_INT < 11; } public void setRefreshing(boolean refreshing) { if (!refreshing || this.mRefreshing == refreshing) { setRefreshing(refreshing, false); return; } int endTarget; this.mRefreshing = refreshing; if (this.mUsingCustomStart) { endTarget = this.mSpinnerOffsetEnd; } else { endTarget = this.mSpinnerOffsetEnd + this.mOriginalOffsetTop; } setTargetOffsetTopAndBottom(endTarget - this.mCurrentTargetOffsetTop, true); this.mNotify = false; startScaleUpAnimation(this.mRefreshListener); } @SuppressLint({"NewApi"}) private void startScaleUpAnimation(AnimationListener listener) { this.mCircleView.setVisibility(0); if (VERSION.SDK_INT >= 11) { this.mProgress.setAlpha(255); } this.mScaleAnimation = new C02482(); this.mScaleAnimation.setDuration((long) this.mMediumAnimationDuration); if (listener != null) { this.mCircleView.setAnimationListener(listener); } this.mCircleView.clearAnimation(); this.mCircleView.startAnimation(this.mScaleAnimation); } void setAnimationProgress(float progress) { if (isAlphaUsedForScale()) { setColorViewAlpha((int) (255.0f * progress)); return; } ViewCompat.setScaleX(this.mCircleView, progress); ViewCompat.setScaleY(this.mCircleView, progress); } private void setRefreshing(boolean refreshing, boolean notify) { if (this.mRefreshing != refreshing) { this.mNotify = notify; ensureTarget(); this.mRefreshing = refreshing; if (this.mRefreshing) { animateOffsetToCorrectPosition(this.mCurrentTargetOffsetTop, this.mRefreshListener); } else { startScaleDownAnimation(this.mRefreshListener); } } } void startScaleDownAnimation(AnimationListener listener) { this.mScaleDownAnimation = new C02493(); this.mScaleDownAnimation.setDuration(150); this.mCircleView.setAnimationListener(listener); this.mCircleView.clearAnimation(); this.mCircleView.startAnimation(this.mScaleDownAnimation); } @SuppressLint({"NewApi"}) private void startProgressAlphaStartAnimation() { this.mAlphaStartAnimation = startAlphaAnimation(this.mProgress.getAlpha(), 76); } @SuppressLint({"NewApi"}) private void startProgressAlphaMaxAnimation() { this.mAlphaMaxAnimation = startAlphaAnimation(this.mProgress.getAlpha(), 255); } @SuppressLint({"NewApi"}) private Animation startAlphaAnimation(final int startingAlpha, final int endingAlpha) { if (this.mScale && isAlphaUsedForScale()) { return null; } Animation alpha = new Animation() { public void applyTransformation(float interpolatedTime, Transformation t) { SwipeRefreshLayout.this.mProgress.setAlpha((int) (((float) startingAlpha) + (((float) (endingAlpha - startingAlpha)) * interpolatedTime))); } }; alpha.setDuration(300); this.mCircleView.setAnimationListener(null); this.mCircleView.clearAnimation(); this.mCircleView.startAnimation(alpha); return alpha; } @Deprecated public void setProgressBackgroundColor(int colorRes) { setProgressBackgroundColorSchemeResource(colorRes); } public void setProgressBackgroundColorSchemeResource(@ColorRes int colorRes) { setProgressBackgroundColorSchemeColor(ContextCompat.getColor(getContext(), colorRes)); } public void setProgressBackgroundColorSchemeColor(@ColorInt int color) { this.mCircleView.setBackgroundColor(color); this.mProgress.setBackgroundColor(color); } @Deprecated public void setColorScheme(@ColorInt int... colors) { setColorSchemeResources(colors); } public void setColorSchemeResources(@ColorRes int... colorResIds) { Context context = getContext(); int[] colorRes = new int[colorResIds.length]; for (int i = 0; i < colorResIds.length; i++) { colorRes[i] = ContextCompat.getColor(context, colorResIds[i]); } setColorSchemeColors(colorRes); } public void setColorSchemeColors(@ColorInt int... colors) { ensureTarget(); this.mProgress.setColorSchemeColors(colors); } public boolean isRefreshing() { return this.mRefreshing; } private void ensureTarget() { if (this.mTarget == null) { int i = 0; while (i < getChildCount()) { View child = getChildAt(i); if (child.equals(this.mCircleView)) { i++; } else { this.mTarget = child; return; } } } } public void setDistanceToTriggerSync(int distance) { this.mTotalDragDistance = (float) distance; } protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int width = getMeasuredWidth(); int height = getMeasuredHeight(); if (getChildCount() != 0) { if (this.mTarget == null) { ensureTarget(); } if (this.mTarget != null) { View child = this.mTarget; int childLeft = getPaddingLeft(); int childTop = getPaddingTop(); child.layout(childLeft, childTop, childLeft + ((width - getPaddingLeft()) - getPaddingRight()), childTop + ((height - getPaddingTop()) - getPaddingBottom())); int circleWidth = this.mCircleView.getMeasuredWidth(); this.mCircleView.layout((width / 2) - (circleWidth / 2), this.mCurrentTargetOffsetTop, (width / 2) + (circleWidth / 2), this.mCurrentTargetOffsetTop + this.mCircleView.getMeasuredHeight()); } } } public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (this.mTarget == null) { ensureTarget(); } if (this.mTarget != null) { this.mTarget.measure(MeasureSpec.makeMeasureSpec((getMeasuredWidth() - getPaddingLeft()) - getPaddingRight(), 1073741824), MeasureSpec.makeMeasureSpec((getMeasuredHeight() - getPaddingTop()) - getPaddingBottom(), 1073741824)); this.mCircleView.measure(MeasureSpec.makeMeasureSpec(this.mCircleDiameter, 1073741824), MeasureSpec.makeMeasureSpec(this.mCircleDiameter, 1073741824)); this.mCircleViewIndex = -1; for (int index = 0; index < getChildCount(); index++) { if (getChildAt(index) == this.mCircleView) { this.mCircleViewIndex = index; return; } } } } public int getProgressCircleDiameter() { return this.mCircleDiameter; } public boolean canChildScrollUp() { boolean z = false; if (this.mChildScrollUpCallback != null) { return this.mChildScrollUpCallback.canChildScrollUp(this, this.mTarget); } if (VERSION.SDK_INT >= 14) { return ViewCompat.canScrollVertically(this.mTarget, -1); } if (this.mTarget instanceof AbsListView) { AbsListView absListView = this.mTarget; if (absListView.getChildCount() <= 0 || (absListView.getFirstVisiblePosition() <= 0 && absListView.getChildAt(0).getTop() >= absListView.getPaddingTop())) { return false; } return true; } if (ViewCompat.canScrollVertically(this.mTarget, -1) || this.mTarget.getScrollY() > 0) { z = true; } return z; } public void setOnChildScrollUpCallback(@Nullable OnChildScrollUpCallback callback) { this.mChildScrollUpCallback = callback; } public boolean onInterceptTouchEvent(MotionEvent ev) { ensureTarget(); int action = MotionEventCompat.getActionMasked(ev); if (this.mReturningToStart && action == 0) { this.mReturningToStart = false; } if (!isEnabled() || this.mReturningToStart || canChildScrollUp() || this.mRefreshing || this.mNestedScrollInProgress) { return false; } int pointerIndex; switch (action) { case 0: setTargetOffsetTopAndBottom(this.mOriginalOffsetTop - this.mCircleView.getTop(), true); this.mActivePointerId = ev.getPointerId(0); this.mIsBeingDragged = false; pointerIndex = ev.findPointerIndex(this.mActivePointerId); if (pointerIndex >= 0) { this.mInitialDownY = ev.getY(pointerIndex); break; } return false; case 1: case 3: this.mIsBeingDragged = false; this.mActivePointerId = -1; break; case 2: if (this.mActivePointerId == -1) { Log.e(LOG_TAG, "Got ACTION_MOVE event but don't have an active pointer id."); return false; } pointerIndex = ev.findPointerIndex(this.mActivePointerId); if (pointerIndex >= 0) { startDragging(ev.getY(pointerIndex)); break; } return false; case 6: onSecondaryPointerUp(ev); break; } return this.mIsBeingDragged; } public void requestDisallowInterceptTouchEvent(boolean b) { if (VERSION.SDK_INT < 21 && (this.mTarget instanceof AbsListView)) { return; } if (this.mTarget == null || ViewCompat.isNestedScrollingEnabled(this.mTarget)) { super.requestDisallowInterceptTouchEvent(b); } } public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) { return (!isEnabled() || this.mReturningToStart || this.mRefreshing || (nestedScrollAxes & 2) == 0) ? false : true; } public void onNestedScrollAccepted(View child, View target, int axes) { this.mNestedScrollingParentHelper.onNestedScrollAccepted(child, target, axes); startNestedScroll(axes & 2); this.mTotalUnconsumed = 0.0f; this.mNestedScrollInProgress = true; } public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { if (dy > 0 && this.mTotalUnconsumed > 0.0f) { if (((float) dy) > this.mTotalUnconsumed) { consumed[1] = dy - ((int) this.mTotalUnconsumed); this.mTotalUnconsumed = 0.0f; } else { this.mTotalUnconsumed -= (float) dy; consumed[1] = dy; } moveSpinner(this.mTotalUnconsumed); } if (this.mUsingCustomStart && dy > 0 && this.mTotalUnconsumed == 0.0f && Math.abs(dy - consumed[1]) > 0) { this.mCircleView.setVisibility(8); } int[] parentConsumed = this.mParentScrollConsumed; if (dispatchNestedPreScroll(dx - consumed[0], dy - consumed[1], parentConsumed, null)) { consumed[0] = consumed[0] + parentConsumed[0]; consumed[1] = consumed[1] + parentConsumed[1]; } } public int getNestedScrollAxes() { return this.mNestedScrollingParentHelper.getNestedScrollAxes(); } public void onStopNestedScroll(View target) { this.mNestedScrollingParentHelper.onStopNestedScroll(target); this.mNestedScrollInProgress = false; if (this.mTotalUnconsumed > 0.0f) { finishSpinner(this.mTotalUnconsumed); this.mTotalUnconsumed = 0.0f; } stopNestedScroll(); } public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, this.mParentOffsetInWindow); int dy = dyUnconsumed + this.mParentOffsetInWindow[1]; if (dy < 0 && !canChildScrollUp()) { this.mTotalUnconsumed += (float) Math.abs(dy); moveSpinner(this.mTotalUnconsumed); } } public void setNestedScrollingEnabled(boolean enabled) { this.mNestedScrollingChildHelper.setNestedScrollingEnabled(enabled); } public boolean isNestedScrollingEnabled() { return this.mNestedScrollingChildHelper.isNestedScrollingEnabled(); } public boolean startNestedScroll(int axes) { return this.mNestedScrollingChildHelper.startNestedScroll(axes); } public void stopNestedScroll() { this.mNestedScrollingChildHelper.stopNestedScroll(); } public boolean hasNestedScrollingParent() { return this.mNestedScrollingChildHelper.hasNestedScrollingParent(); } public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { return this.mNestedScrollingChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow); } public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { return this.mNestedScrollingChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow); } public boolean onNestedPreFling(View target, float velocityX, float velocityY) { return dispatchNestedPreFling(velocityX, velocityY); } public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) { return dispatchNestedFling(velocityX, velocityY, consumed); } public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { return this.mNestedScrollingChildHelper.dispatchNestedFling(velocityX, velocityY, consumed); } public boolean dispatchNestedPreFling(float velocityX, float velocityY) { return this.mNestedScrollingChildHelper.dispatchNestedPreFling(velocityX, velocityY); } private boolean isAnimationRunning(Animation animation) { return (animation == null || !animation.hasStarted() || animation.hasEnded()) ? false : true; } @SuppressLint({"NewApi"}) private void moveSpinner(float overscrollTop) { float slingshotDist; this.mProgress.showArrow(true); float dragPercent = Math.min(BaseField.BORDER_WIDTH_THIN, Math.abs(overscrollTop / this.mTotalDragDistance)); float adjustedPercent = (((float) Math.max(((double) dragPercent) - 0.4d, 0.0d)) * 5.0f) / BaseField.BORDER_WIDTH_THICK; float extraOS = Math.abs(overscrollTop) - this.mTotalDragDistance; if (this.mUsingCustomStart) { slingshotDist = (float) (this.mSpinnerOffsetEnd - this.mOriginalOffsetTop); } else { slingshotDist = (float) this.mSpinnerOffsetEnd; } float tensionSlingshotPercent = Math.max(0.0f, Math.min(extraOS, 2.0f * slingshotDist) / slingshotDist); float tensionPercent = ((float) (((double) (tensionSlingshotPercent / 4.0f)) - Math.pow((double) (tensionSlingshotPercent / 4.0f), 2.0d))) * 2.0f; int targetY = this.mOriginalOffsetTop + ((int) ((slingshotDist * dragPercent) + ((slingshotDist * tensionPercent) * 2.0f))); if (this.mCircleView.getVisibility() != 0) { this.mCircleView.setVisibility(0); } if (!this.mScale) { ViewCompat.setScaleX(this.mCircleView, BaseField.BORDER_WIDTH_THIN); ViewCompat.setScaleY(this.mCircleView, BaseField.BORDER_WIDTH_THIN); } if (this.mScale) { setAnimationProgress(Math.min(BaseField.BORDER_WIDTH_THIN, overscrollTop / this.mTotalDragDistance)); } if (overscrollTop < this.mTotalDragDistance) { if (this.mProgress.getAlpha() > 76) { if (!isAnimationRunning(this.mAlphaStartAnimation)) { startProgressAlphaStartAnimation(); } } } else if (this.mProgress.getAlpha() < 255) { if (!isAnimationRunning(this.mAlphaMaxAnimation)) { startProgressAlphaMaxAnimation(); } } this.mProgress.setStartEndTrim(0.0f, Math.min(MAX_PROGRESS_ANGLE, adjustedPercent * MAX_PROGRESS_ANGLE)); this.mProgress.setArrowScale(Math.min(BaseField.BORDER_WIDTH_THIN, adjustedPercent)); this.mProgress.setProgressRotation(((-0.25f + (0.4f * adjustedPercent)) + (2.0f * tensionPercent)) * DRAG_RATE); setTargetOffsetTopAndBottom(targetY - this.mCurrentTargetOffsetTop, true); } private void finishSpinner(float overscrollTop) { if (overscrollTop > this.mTotalDragDistance) { setRefreshing(true, true); return; } this.mRefreshing = false; this.mProgress.setStartEndTrim(0.0f, 0.0f); AnimationListener listener = null; if (!this.mScale) { listener = new C02515(); } animateOffsetToStartPosition(this.mCurrentTargetOffsetTop, listener); this.mProgress.showArrow(false); } public boolean onTouchEvent(MotionEvent ev) { int action = MotionEventCompat.getActionMasked(ev); if (this.mReturningToStart && action == 0) { this.mReturningToStart = false; } if (!isEnabled() || this.mReturningToStart || canChildScrollUp() || this.mRefreshing || this.mNestedScrollInProgress) { return false; } int pointerIndex; float overscrollTop; switch (action) { case 0: this.mActivePointerId = ev.getPointerId(0); this.mIsBeingDragged = false; break; case 1: pointerIndex = ev.findPointerIndex(this.mActivePointerId); if (pointerIndex < 0) { Log.e(LOG_TAG, "Got ACTION_UP event but don't have an active pointer id."); return false; } if (this.mIsBeingDragged) { overscrollTop = (ev.getY(pointerIndex) - this.mInitialMotionY) * DRAG_RATE; this.mIsBeingDragged = false; finishSpinner(overscrollTop); } this.mActivePointerId = -1; return false; case 2: pointerIndex = ev.findPointerIndex(this.mActivePointerId); if (pointerIndex < 0) { Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id."); return false; } float y = ev.getY(pointerIndex); startDragging(y); if (this.mIsBeingDragged) { overscrollTop = (y - this.mInitialMotionY) * DRAG_RATE; if (overscrollTop > 0.0f) { moveSpinner(overscrollTop); break; } return false; } break; case 3: return false; case 5: pointerIndex = MotionEventCompat.getActionIndex(ev); if (pointerIndex >= 0) { this.mActivePointerId = ev.getPointerId(pointerIndex); break; } Log.e(LOG_TAG, "Got ACTION_POINTER_DOWN event but have an invalid action index."); return false; case 6: onSecondaryPointerUp(ev); break; } return true; } @SuppressLint({"NewApi"}) private void startDragging(float y) { if (y - this.mInitialDownY > ((float) this.mTouchSlop) && !this.mIsBeingDragged) { this.mInitialMotionY = this.mInitialDownY + ((float) this.mTouchSlop); this.mIsBeingDragged = true; this.mProgress.setAlpha(76); } } private void animateOffsetToCorrectPosition(int from, AnimationListener listener) { this.mFrom = from; this.mAnimateToCorrectPosition.reset(); this.mAnimateToCorrectPosition.setDuration(200); this.mAnimateToCorrectPosition.setInterpolator(this.mDecelerateInterpolator); if (listener != null) { this.mCircleView.setAnimationListener(listener); } this.mCircleView.clearAnimation(); this.mCircleView.startAnimation(this.mAnimateToCorrectPosition); } private void animateOffsetToStartPosition(int from, AnimationListener listener) { if (this.mScale) { startScaleDownReturnToStartAnimation(from, listener); return; } this.mFrom = from; this.mAnimateToStartPosition.reset(); this.mAnimateToStartPosition.setDuration(200); this.mAnimateToStartPosition.setInterpolator(this.mDecelerateInterpolator); if (listener != null) { this.mCircleView.setAnimationListener(listener); } this.mCircleView.clearAnimation(); this.mCircleView.startAnimation(this.mAnimateToStartPosition); } void moveToStart(float interpolatedTime) { setTargetOffsetTopAndBottom((this.mFrom + ((int) (((float) (this.mOriginalOffsetTop - this.mFrom)) * interpolatedTime))) - this.mCircleView.getTop(), false); } @SuppressLint({"NewApi"}) private void startScaleDownReturnToStartAnimation(int from, AnimationListener listener) { this.mFrom = from; if (isAlphaUsedForScale()) { this.mStartingScale = (float) this.mProgress.getAlpha(); } else { this.mStartingScale = ViewCompat.getScaleX(this.mCircleView); } this.mScaleDownToStartAnimation = new C02548(); this.mScaleDownToStartAnimation.setDuration(150); if (listener != null) { this.mCircleView.setAnimationListener(listener); } this.mCircleView.clearAnimation(); this.mCircleView.startAnimation(this.mScaleDownToStartAnimation); } void setTargetOffsetTopAndBottom(int offset, boolean requiresUpdate) { this.mCircleView.bringToFront(); ViewCompat.offsetTopAndBottom(this.mCircleView, offset); this.mCurrentTargetOffsetTop = this.mCircleView.getTop(); if (requiresUpdate && VERSION.SDK_INT < 11) { invalidate(); } } private void onSecondaryPointerUp(MotionEvent ev) { int pointerIndex = MotionEventCompat.getActionIndex(ev); if (ev.getPointerId(pointerIndex) == this.mActivePointerId) { this.mActivePointerId = ev.getPointerId(pointerIndex == 0 ? 1 : 0); } } }
39.547699
238
0.643528
9b1de766d71d6a60a2af4f0008cd8862a81b19f3
226
package _16visitor.my; /** * @author 孟享广 * @date 2020-08-13 2:26 下午 * @description */ public class Woman extends Person{ @Override public void accpect(Action action) { action.getWomanResult(this); } }
17.384615
40
0.646018
b437dd1aa08ce796ca76346ed3c2e01139069c20
4,872
package io.automatiko.engine.workflow.compiler.xml.processes; import java.util.ArrayList; import java.util.List; import java.util.Map; import io.automatiko.engine.api.definition.process.Connection; import io.automatiko.engine.workflow.base.core.context.exception.ExceptionScope; import io.automatiko.engine.workflow.base.core.context.variable.Variable; import io.automatiko.engine.workflow.base.core.context.variable.VariableScope; import io.automatiko.engine.workflow.compiler.xml.XmlWorkflowProcessDumper; import io.automatiko.engine.workflow.process.core.Node; import io.automatiko.engine.workflow.process.core.node.CompositeContextNode; import io.automatiko.engine.workflow.process.core.node.CompositeNode; public class CompositeNodeHandler extends AbstractNodeHandler { protected Node createNode() { CompositeContextNode result = new CompositeContextNode(); VariableScope variableScope = new VariableScope(); result.addContext(variableScope); result.setDefaultContext(variableScope); return result; } public Class<?> generateNodeFor() { return CompositeNode.class; } public boolean allowNesting() { return true; } protected String getNodeName() { return "composite"; } public void writeNode(Node node, StringBuilder xmlDump, boolean includeMeta) { super.writeNode(getNodeName(), node, xmlDump, includeMeta); CompositeNode compositeNode = (CompositeNode) node; writeAttributes(compositeNode, xmlDump, includeMeta); xmlDump.append(">" + EOL); if (includeMeta) { writeMetaData(compositeNode, xmlDump); } for (String eventType : compositeNode.getActionTypes()) { writeActions(eventType, compositeNode.getActions(eventType), xmlDump); } writeTimers(compositeNode.getTimers(), xmlDump); if (compositeNode instanceof CompositeContextNode) { VariableScope variableScope = (VariableScope) ((CompositeContextNode) compositeNode) .getDefaultContext(VariableScope.VARIABLE_SCOPE); if (variableScope != null) { List<Variable> variables = variableScope.getVariables(); XmlWorkflowProcessDumper.visitVariables(variables, xmlDump); } ExceptionScope exceptionScope = (ExceptionScope) ((CompositeContextNode) compositeNode) .getDefaultContext(ExceptionScope.EXCEPTION_SCOPE); if (exceptionScope != null) { XmlWorkflowProcessDumper.visitExceptionHandlers(exceptionScope.getExceptionHandlers(), xmlDump); } } xmlDump.append(" </connections>" + EOL); Map<String, CompositeNode.NodeAndType> inPorts = getInPorts(compositeNode); xmlDump.append(" <in-ports>" + EOL); for (Map.Entry<String, CompositeNode.NodeAndType> entry : inPorts.entrySet()) { xmlDump.append(" <in-port type=\"" + entry.getKey() + "\" nodeId=\"" + entry.getValue().getNodeId() + "\" nodeInType=\"" + entry.getValue().getType() + "\" />" + EOL); } xmlDump.append(" </in-ports>" + EOL); Map<String, CompositeNode.NodeAndType> outPorts = getOutPorts(compositeNode); xmlDump.append(" <out-ports>" + EOL); for (Map.Entry<String, CompositeNode.NodeAndType> entry : outPorts.entrySet()) { xmlDump.append(" <out-port type=\"" + entry.getKey() + "\" nodeId=\"" + entry.getValue().getNodeId() + "\" nodeOutType=\"" + entry.getValue().getType() + "\" />" + EOL); } xmlDump.append(" </out-ports>" + EOL); endNode(getNodeName(), xmlDump); } protected void writeAttributes(CompositeNode compositeNode, StringBuilder xmlDump, boolean includeMeta) { } protected List<Node> getSubNodes(CompositeNode compositeNode) { List<Node> subNodes = new ArrayList<Node>(); for (io.automatiko.engine.api.definition.process.Node subNode : compositeNode.getNodes()) { // filter out composite start and end nodes as they can be regenerated if ((!(subNode instanceof CompositeNode.CompositeNodeStart)) && (!(subNode instanceof CompositeNode.CompositeNodeEnd))) { subNodes.add((Node) subNode); } } return subNodes; } protected List<Connection> getSubConnections(CompositeNode compositeNode) { List<Connection> connections = new ArrayList<Connection>(); for (io.automatiko.engine.api.definition.process.Node subNode : compositeNode.getNodes()) { // filter out composite start and end nodes as they can be regenerated if (!(subNode instanceof CompositeNode.CompositeNodeEnd)) { for (Connection connection : subNode.getIncomingConnections(Node.CONNECTION_DEFAULT_TYPE)) { if (!(connection.getFrom() instanceof CompositeNode.CompositeNodeStart)) { connections.add(connection); } } } } return connections; } protected Map<String, CompositeNode.NodeAndType> getInPorts(CompositeNode compositeNode) { return compositeNode.getLinkedIncomingNodes(); } protected Map<String, CompositeNode.NodeAndType> getOutPorts(CompositeNode compositeNode) { return compositeNode.getLinkedOutgoingNodes(); } }
40.264463
110
0.745895
6274ea794461426a08bed1d55a847598bfea71dd
5,939
/* * Copyright (c) 2021, Veepee * * Permission to use, copy, modify, and/or distribute this software for any purpose * with or without fee is hereby granted, provided that the above copyright notice * and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF * THIS SOFTWARE. */ package com.privalia.qa.utils; import org.testng.annotations.Test; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; public class SoapServiceUtilsTest { SoapServiceUtils soap; private String addRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + " <soap:Body>\n" + " <Add xmlns=\"http://tempuri.org/\">\n" + " <intA>int</intA>\n" + " <intB>int</intB>\n" + " </Add>\n" + " </soap:Body>\n" + "</soap:Envelope>"; private String verifyEmailRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + " <soap:Body>\n" + " <AdvancedVerifyEmail xmlns=\"http://ws.cdyne.com/\">\n" + " <email>string</email>\n" + " <timeout>int</timeout>\n" + " <LicenseKey>string</LicenseKey>\n" + " </AdvancedVerifyEmail>\n" + " </soap:Body>\n" + "</soap:Envelope>"; /** * Evaluate if the library can parser correctly the elements in the WSDL document */ @Test(enabled = false) public void parseWsdlContent() { soap = new SoapServiceUtils(); soap.parseWsdl("http://www.dneonline.com/calculator.asmx?WSDL"); assertThat(soap.getServiceName()).isEqualToIgnoringCase("Calculator"); assertThat(soap.getPortName()).isEqualToIgnoringCase("CalculatorSoap"); assertThat(soap.getTargetNameSpace()).isEqualToIgnoringCase("http://tempuri.org/"); assertThat(soap.getAvailableSoapActions().get("Add")).isEqualToIgnoringCase("http://tempuri.org/Add"); assertThat(soap.getAvailableSoapActions().get("Subtract")).isEqualToIgnoringCase("http://tempuri.org/Subtract"); assertThat(soap.getAvailableSoapActions().get("Multiply")).isEqualToIgnoringCase("http://tempuri.org/Multiply"); assertThat(soap.getAvailableSoapActions().get("Divide")).isEqualToIgnoringCase("http://tempuri.org/Divide"); } /** * Evaluatethe function to read tags from an XML string * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ @Test(enabled = false) public void evaluateXmlTest() throws IOException, SAXException, ParserConfigurationException { soap = new SoapServiceUtils(); assertThat(soap.evaluateXml(this.addRequest, "intA")).isEqualToIgnoringCase("int"); assertThat(soap.evaluateXml(this.addRequest, "intB")).isEqualToIgnoringCase("int"); assertThat(soap.evaluateXml(this.addRequest, "intC")).isNull(); } /** * Test the function Add of the webservice in http://www.dneonline.com/calculator.asmx * and verify if the response is correct * @throws Exception */ @Test(enabled = false) public void executeRemoteMethodAdd() throws Exception { String response; Map<String, String> map = new LinkedHashMap<>(); soap = new SoapServiceUtils(); soap.parseWsdl("http://www.dneonline.com/calculator.asmx?WSDL"); map.put("intA", "2"); map.put("intB", "2"); response = soap.executeMethodWithParams("Add", this.addRequest, map); assertThat(soap.evaluateXml(response, "AddResult")).matches("4"); map.put("intA", "5"); map.put("intB", "5"); response = soap.executeMethodWithParams("Add", this.addRequest, map); assertThat(soap.evaluateXml(response, "AddResult")).matches("10"); } /** * Test the function Add of the webservice in http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx * and verify if the response is correct * @throws Exception */ @Test(enabled = false) public void executeRemoteMethodEmail() throws Exception { String response; Map<String, String> map = new LinkedHashMap<>(); soap = new SoapServiceUtils(); soap.parseWsdl("http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx?WSDL"); map.put("email", "josefd8@gmail.com"); map.put("timeout", "0"); map.put("LicenseKey", ""); response = soap.executeMethodWithParams("AdvancedVerifyEmail", this.verifyEmailRequest, map); assertThat(soap.evaluateXml(response, "GoodEmail")).matches("true"); map.put("email", "novalidemail"); map.put("timeout", "0"); map.put("LicenseKey", ""); response = soap.executeMethodWithParams("AdvancedVerifyEmail", this.verifyEmailRequest, map); assertThat(soap.evaluateXml(response, "GoodEmail")).matches("false"); } }
41.531469
193
0.651793
012a1c22a17fe25bc79abf71ab848abde30917b9
1,737
package vector_routing; import java.io.*; public class VectorRouting { // returns true if the system is stable public boolean shareTables() { boolean stable; int detect = 0; // has the system been updated // I will use this to determine if the system is stable. for (int i = 0; i < Main.MAX_NODES; i++) { stable = Main.routers.updateDistanceVectorTable(i); if (stable) { detect++; } System.out.println("Router " + (i + 1) + " updated " + Main.routers.changes); } // if the system is not stable, then detect will get up from zero // it will be used to return to the main function to detect if the system is indeed stable if (detect == 0) { // system is stable return true; } else { // system is not stable return false; } } // This simply reads data from the input file // Will return the node information public int[][] readInput(String fileName) { int i = 0; int[][] nodeInfo; // will store the information of the nodes from the file nodeInfo = new int[Main.MAX_NODES][Main.MAX_NODES]; try { File file = new File(fileName); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; // Read data from the file line by line and store it in the array while ((line = bufferedReader.readLine()) != null) { // we know how the file will be formatted String[] lines = line.split(" "); for (int j = 0; j < Main.MAX_NODES; j++) { // convert string to int nodeInfo[i][j] = Integer.parseInt(lines[j]); } i++; } fileReader.close(); } catch (IOException e) { e.printStackTrace(); } // return the created array to the main function return nodeInfo; } }
28.95
92
0.658031
f3f64186196d10504d203625218dbe6437b22f60
2,936
/* Copyright 2015 Denis Prasetio 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.dotosoft.dotoquiz.tools.thirdparty.metadata; import java.lang.reflect.InvocationTargetException; import java.util.Date; import javax.persistence.Transient; import org.apache.commons.beanutils.BeanUtils; import com.dotosoft.dotoquiz.model.data.DataTopics; import com.dotosoft.dotoquiz.tools.common.QuizParserConstant.APPLICATION_TYPE; public class DataTopicsParser extends DataTopics { public DataTopicsParser(String id, String picasaId, String imagePicasaUrl, String topicParentId, String name, String description, String imageUrl, String isDelete, Date createdDt, String createdBy, String isProcessed, APPLICATION_TYPE applicationType) { this.id = id; this.picasaId = picasaId; this.imagePicasaUrl = imagePicasaUrl; this.name = name; this.topicParentId = topicParentId; this.description = description; this.imageUrl = imageUrl; this.isDelete = isDelete; this.createdDt = createdDt; this.createdBy = createdBy; this.isProcessed = isProcessed; this.applicationType = applicationType; } // only need for batch @Transient protected String isProcessed; @Transient protected APPLICATION_TYPE applicationType; @Transient protected String topicParentId; public String getTopicParentId() { return topicParentId; } public void setTopicParentId(String topicParentId) { this.topicParentId = topicParentId; } public String getIsProcessed() { return isProcessed; } public void setIsProcessed(String isProcessed) { this.isProcessed = isProcessed; } public APPLICATION_TYPE getApplicationType() { return applicationType; } public void setApplicationType(APPLICATION_TYPE applicationType) { this.applicationType = applicationType; } public DataTopics toDataTopics() throws IllegalAccessException, InvocationTargetException { DataTopics datTopics = new DataTopics(); BeanUtils.copyProperties(datTopics, this); return datTopics; } @Override public String toString() { return "DataTopics [id=" + id + ", picasaId=" + picasaId + ", imagePicasaUrl=" + imagePicasaUrl + ", datTopics=" + datTopics + ", name=" + name + ", description=" + description + ", imageUrl=" + imageUrl + ", isDelete=" + isDelete + ", createdDt=" + createdDt + ", createdBy=" + createdBy + ", isProcessed=" + isProcessed + ", applicationType=" + applicationType + "]"; } }
29.36
92
0.755109
b1496c356b05ac3abc883e02d0016897e8134ecd
1,673
package es.udc.ws.util.configuration; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; public final class ConfigurationParametersManager { private static final String CONFIGURATION_FILE = "ConfigurationParameters.properties"; private static Map<String, String> parameters; private ConfigurationParametersManager() { } @SuppressWarnings({"unchecked", "rawtypes"}) private static synchronized Map<String, String> getParameters() { if (parameters == null) { Class<ConfigurationParametersManager> configurationParametersManagerClass = ConfigurationParametersManager.class; ClassLoader classLoader = configurationParametersManagerClass.getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(CONFIGURATION_FILE); Properties properties = new Properties(); try { properties.load(inputStream); inputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } /* * We use a "HashMap" instead of a "HashTable" because HashMap's * methods are *not* synchronized (so they are faster), and the * parameters are only read. */ parameters = (Map<String, String>) new HashMap(properties); } return parameters; } public static String getParameter(String name) { return getParameters().get(name); } }
30.981481
90
0.623431
b805ef9f4c933992f6cf91f754da3632e5b5df50
1,256
package dev.nito.xikra.utils; import lombok.experimental.UtilityClass; import java.io.IOException; import java.net.URI; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import static dev.nito.xikra.utils.TypeConversionsUtils.booleanToInteger; @UtilityClass public class XikraClientUtils { public static final Integer TIMEOUT_SEC = 2; public static final Duration TIMEOUT = Duration.ofSeconds(TIMEOUT_SEC); public static HttpRequest get64PositionsHttpRequest(String ip) { return HttpRequest.newBuilder() .uri(URI.create("http://" + ip + "/64OUT.cgi")) .timeout(TIMEOUT) .GET() .build(); } public static HttpRequest modifyState32PositionsHttpRequest(String ip, int position, boolean newValue) { String group = position > 16 ? "16OUTGR2" : "16OUTGR1"; int calculatedPosition = position > 16 ? position - 16 : position; return HttpRequest.newBuilder() .uri(URI.create("http://" + ip + "/" + group + ".cgi?OUT" + calculatedPosition + "=" + booleanToInteger(newValue))) .timeout(Duration.ofSeconds(2)) .GET() .build(); } }
33.052632
131
0.649682
7ea26f84cbc4db530a454c0932c52a1c418cb806
4,166
package org.allrecipes.CosineSimilarity; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.JobPriority; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.crawling.models.Review; import com.google.gson.Gson; public class UserRecipeCount extends Configured implements Tool{ /** * @param args */ public static class UserRecipeCountMap extends MapReduceBase implements Mapper<LongWritable, Text, Text, Text> { private static HashMap<String, Integer> userId = new HashMap<String,Integer>(); private static HashMap<String, Integer> recipeId = new HashMap<String,Integer>(); @Override public void configure(JobConf job) { readIds("allrecipes/id/UserID/part-r-00000", userId, job); readIds("allrecipes/id/RecipeID/part-r-00000", recipeId, job); } public void readIds(String path, HashMap<String, Integer> map, JobConf job) { String st = ""; try { FileSystem fs = FileSystem.get(job); BufferedReader br = new BufferedReader(new InputStreamReader( fs.open(new Path(path)))); while ((st = br.readLine()) != null) { if (st.trim().length() > 0) { String[] splits = st.trim().split("\\t"); map.put(splits[1], Integer.parseInt(splits[0])); } } br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void map(LongWritable key, Text value, OutputCollector<Text, Text> output, Reporter arg3) throws IOException { String text = value.toString().trim(); try { if (text.length() > 0) { Review review = new Gson().fromJson(text, Review.class); if (review.getRating() >= 3) { output.collect(new Text(userId.get(review.getReviewer().getName())+""), new Text(recipeId.get(review.getReviewDish().getName())+"")); } } }catch(Exception e){ } } } public static class UserRecipeCountReduce extends MapReduceBase implements Reducer<Text, Text, Text, Text> { @Override public void reduce(Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter arg3) throws IOException { int size = 0; while(values.hasNext()){ values.next(); size++;} output.collect(key, new Text(size+"")); } } public static void main(String[] args) { try { ToolRunner.run(new Configuration(), new UserRecipeCount(), args); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @SuppressWarnings("deprecation") @Override public int run(String[] args) throws Exception { JobConf job = new JobConf(super.getConf(), this.getClass()); job.setJarByClass(this.getClass()); job.setJobName("Compute recipe count"); job.setJobPriority(JobPriority.VERY_HIGH); job.setMapperClass(UserRecipeCountMap.class); job.setReducerClass(UserRecipeCountReduce.class); //job.setNumMapTasks(20); job.setNumReduceTasks(1); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); FileInputFormat.setInputPaths(job, args[0]); FileSystem.get(job).delete(new Path(args[1])); FileOutputFormat.setOutputPath(job, new Path(args[1])); JobClient.runJob(job); System.out.println("***********DONE********"); return 0; } }
31.089552
140
0.690831
f652f90dfa6b5ab4f4aed39ec96eddc103bd3fe2
16,802
/** * (c) Copyright 2013 WibiData, Inc. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kiji.schema.tools; import static junit.framework.Assert.assertNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Map; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.apache.hadoop.hbase.util.Bytes; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.kiji.schema.KijiClientTest; import org.kiji.schema.KijiColumnName; import org.kiji.schema.KijiTable; import org.kiji.schema.KijiTableAnnotator; import org.kiji.schema.KijiURI; import org.kiji.schema.layout.KijiTableLayouts; public class TestNotesTool extends KijiClientTest { private static final Logger LOG = LoggerFactory.getLogger(TestNotesTool.class); /** Horizontal ruler to delimit CLI outputs in logs. */ private static final String RULER = "--------------------------------------------------------------------------------"; private static final String LSEP = System.getProperty("line.separator"); /** Output of the CLI tool, as bytes. */ private ByteArrayOutputStream mToolOutputBytes = new ByteArrayOutputStream(); /** Output of the CLI tool, as a single string. */ private String mToolOutputStr; /** Output of the CLI tool, as an array of lines. */ private String[] mToolOutputLines; private int runTool(BaseTool tool, String...arguments) throws Exception { mToolOutputBytes.reset(); final PrintStream pstream = new PrintStream(mToolOutputBytes); tool.setPrintStream(pstream); tool.setConf(getConf()); try { LOG.info("Running tool: '{}' with parameters {}", tool.getName(), arguments); return tool.toolMain(Lists.newArrayList(arguments)); } finally { pstream.flush(); pstream.close(); mToolOutputStr = Bytes.toString(mToolOutputBytes.toByteArray()); LOG.info("Captured output for tool: '{}' with parameters {}:\n{}\n{}{}\n", tool.getName(), arguments, RULER, mToolOutputStr, RULER); mToolOutputLines = mToolOutputStr.split(LSEP); } } //------------------------------------------------------------------------------------------------ private static final String KEY = "abc"; private static final String VALUE = "def"; private static final String KEY2 = "123"; private static final String VALUE2 = "456"; private static final String KEY3 = "zyx"; private static final String VALUE3 = "wvu"; private static final Map<String, String> KVS = ImmutableMap.<String, String>builder().put(KEY, VALUE).put(KEY2, VALUE2).build(); private static final KijiColumnName INFONAME = new KijiColumnName("info:name"); private static final KijiColumnName INFOEMAIL = new KijiColumnName("info:email"); private static final String INFO = "info"; //------------------------------------------------------------------------------------------------ private KijiTable mTable = null; private KijiTableAnnotator mAnnotator = null; @Before public void setup() throws IOException { getKiji().createTable(KijiTableLayouts.getLayout(KijiTableLayouts.USER_TABLE)); mTable = getKiji().openTable("user"); mAnnotator = mTable.openTableAnnotator(); } @After public void cleanup() throws IOException { mAnnotator.close(); mTable.release(); } private KijiURI getInfoNameURI() { return KijiURI.newBuilder(mTable.getURI()) .withColumnNames(Lists.newArrayList(new KijiColumnName("info:name"))).build(); } private void assertFailure(String... args) throws Exception { assertEquals(BaseTool.FAILURE, runTool(new NotesTool(), args)); } private void assertSuccess(String... args) throws Exception { assertEquals(BaseTool.SUCCESS, runTool(new NotesTool(), args)); } @Test public void testValidateFlags() throws Exception { assertFailure("--target=kiji://.env/*^%/table"); assertTrue(mToolOutputStr.startsWith("Invalid Kiji URI:")); assertFailure("--target=kiji://.env/default"); assertTrue(mToolOutputStr.startsWith("--target URI must specify at least a table, got:")); assertFailure("--target=kiji://.env/default/table/info:name,info:email"); assertEquals("--target URI must include one or zero columns." + LSEP, mToolOutputStr); assertFailure("--target=kiji://.env/default/table/info:name", "--do=fake"); assertEquals("Invalid --do command: 'fake'. Valid commands are set, remove, get" + LSEP, mToolOutputStr); assertFailure("--target=kiji://.env/default/table/info:name", "--do=get", "--in-family=info", "--key=key"); assertEquals("--in-family requires that no columns are specified in --target" + LSEP, mToolOutputStr); } @Test public void testSetValidatFlags() throws Exception { assertFailure("--target=" + getInfoNameURI(), "--do=set", "--prefix"); assertEquals("Cannot specify --prefix, --partial, or --regex while --do=set" + LSEP, mToolOutputStr); assertFailure("--target=" + getInfoNameURI(), "--do=set", "--partial"); assertEquals("Cannot specify --prefix, --partial, or --regex while --do=set" + LSEP, mToolOutputStr); assertFailure("--target=" + getInfoNameURI(), "--do=set", "--regex"); assertEquals("Cannot specify --prefix, --partial, or --regex while --do=set" + LSEP, mToolOutputStr); assertFailure("--target=" + getInfoNameURI(), "--do=set", "--in-family=info"); assertEquals("Cannot specify a family with --in-family while --do=set" + LSEP, mToolOutputStr); assertFailure("--target=" + getInfoNameURI(), "--do=set"); assertEquals("--do=set requires --key and --value OR --map" + LSEP, mToolOutputStr); assertFailure("--target=" + getInfoNameURI(), "--do=set", "--key=key", "--map=bope"); assertEquals("--map is mutually exclusive with --key and --value" + LSEP, mToolOutputStr); } @Test public void testRemoveValidateFlags() throws Exception { assertFailure( "--target=" + getInfoNameURI(), "--do=remove", "--prefix", "--partial"); assertEquals("Cannot specify more than one of --prefix, --partial, and --regex" + LSEP, mToolOutputStr); assertFailure("--target=" + getInfoNameURI(), "--do=remove", "--map=bope"); assertEquals("Cannot specify --map while --do=remove" + LSEP, mToolOutputStr); assertFailure("--target=" + getInfoNameURI(), "--do=remove", "--value=bope"); assertEquals("Cannot specify --value while --do=remove" + LSEP, mToolOutputStr); } @Test public void testGetValidateFlags() throws Exception { assertFailure("--target=" + getInfoNameURI(), "--do=get", "--prefix", "--partial"); assertEquals("Cannot specify more than one of --prefix, --partial, and --regex" + LSEP, mToolOutputStr); assertFailure("--target=" + getInfoNameURI(), "--do=get", "--map=bope"); assertEquals("Cannot specify --map while --do=get" + LSEP, mToolOutputStr); assertFailure("--target=" + getInfoNameURI(), "--do=get", "--value=bope"); assertEquals("Cannot specify --value while --do=get" + LSEP, mToolOutputStr); } @Test public void testSet() throws Exception { assertSuccess( "--target=" + getInfoNameURI(), "--do=set", "--key=" + KEY, "--value=" + VALUE); assertEquals(VALUE, mAnnotator.getColumnAnnotation(INFONAME, KEY)); assertSuccess( "--target=" + mTable.getURI(), "--do=set", "--key=" + KEY, "--value=" + VALUE); assertEquals(VALUE, mAnnotator.getTableAnnotation(KEY)); assertSuccess( "--target=" + getInfoNameURI(), "--do=set", "--map=" + String.format("{\"%s\":\"%s\"}", KEY2, VALUE2)); assertEquals(VALUE2, mAnnotator.getColumnAnnotation(INFONAME, KEY2)); assertSuccess( "--target=" + mTable.getURI(), "--do=set", "--map=" + String.format("{\"%s\":\"%s\"}", KEY2, VALUE2)); assertEquals(VALUE2, mAnnotator.getTableAnnotation(KEY2)); } @Test public void testRemove() throws Exception { // exact mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + getInfoNameURI(), "--key=" + KEY, "--do=remove"); assertNull(mAnnotator.getColumnAnnotation(INFONAME, KEY)); mAnnotator.setTableAnnotation(KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=" + KEY, "--do=remove"); assertNull(mAnnotator.getTableAnnotation(KEY)); mAnnotator.setColumnAnnotation(INFOEMAIL, KEY, VALUE); mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=" + KEY, "--do=remove", "--in-family=info"); assertTrue(mAnnotator.getColumnAnnotationsInFamily("info", KEY).isEmpty()); // starts with mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + getInfoNameURI(), "--key=" + KEY.substring(0, 1), "--do=remove", "--prefix"); assertNull(mAnnotator.getColumnAnnotation(INFONAME, KEY)); mAnnotator.setTableAnnotation(KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=" + KEY.substring(0, 1), "--do=remove", "--prefix"); assertNull(mAnnotator.getTableAnnotation(KEY)); mAnnotator.setColumnAnnotation(INFOEMAIL, KEY, VALUE); mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=" + KEY.substring(0, 1), "--do=remove", "--in-family=info", "--prefix"); assertTrue(mAnnotator.getColumnAnnotationsInFamily("info", KEY).isEmpty()); // contains mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + getInfoNameURI(), "--key=" + KEY.substring(1, 2), "--do=remove", "--partial"); assertNull(mAnnotator.getColumnAnnotation(INFONAME, KEY)); mAnnotator.setTableAnnotation(KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=" + KEY.substring(1, 2), "--do=remove", "--partial"); assertNull(mAnnotator.getTableAnnotation(KEY)); mAnnotator.setColumnAnnotation(INFOEMAIL, KEY, VALUE); mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=" + KEY.substring(1, 2), "--do=remove", "--in-family=info", "--partial"); assertTrue(mAnnotator.getColumnAnnotationsInFamily("info", KEY).isEmpty()); // matching mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + getInfoNameURI(), "--key=^[a-z]*$", "--do=remove", "--regex"); assertNull(mAnnotator.getColumnAnnotation(INFONAME, KEY)); mAnnotator.setTableAnnotation(KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=^[a-z]*$", "--do=remove", "--regex"); assertNull(mAnnotator.getTableAnnotation(KEY)); mAnnotator.setColumnAnnotation(INFOEMAIL, KEY, VALUE); mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=^[a-z]*$", "--do=remove", "--in-family=info", "--regex"); assertTrue(mAnnotator.getColumnAnnotationsInFamily("info", KEY).isEmpty()); // All mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + getInfoNameURI(), "--do=remove"); assertNull(mAnnotator.getColumnAnnotation(INFONAME, KEY)); mAnnotator.setTableAnnotation(KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--do=remove"); assertNull(mAnnotator.getTableAnnotation(KEY)); mAnnotator.setColumnAnnotation(INFOEMAIL, KEY, VALUE); mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--do=remove", "--in-family=info"); assertTrue(mAnnotator.getColumnAnnotationsInFamily("info", KEY).isEmpty()); } @Test public void testGet() throws Exception { // exact mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + getInfoNameURI(), "--key=" + KEY, "--do=get"); assertEquals("column: 'info:name'", mToolOutputLines[0]); assertEquals(" 'abc': 'def'", mToolOutputLines[1]); mAnnotator.setTableAnnotation(KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=" + KEY, "--do=get"); assertEquals("table: 'user'", mToolOutputLines[0]); assertEquals(" 'abc': 'def'", mToolOutputLines[1]); mAnnotator.setColumnAnnotation(INFOEMAIL, KEY, VALUE); mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=" + KEY, "--do=get", "--in-family=info"); assertEquals("column: 'info:email'", mToolOutputLines[0]); assertEquals(" 'abc': 'def'", mToolOutputLines[1]); assertEquals("column: 'info:name'", mToolOutputLines[2]); assertEquals(" 'abc': 'def'", mToolOutputLines[3]); // starts with mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + getInfoNameURI(), "--key=" + KEY.substring(0, 1), "--do=get", "--prefix"); assertEquals("column: 'info:name'", mToolOutputLines[0]); assertEquals(" 'abc': 'def'", mToolOutputLines[1]); mAnnotator.setTableAnnotation(KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=" + KEY.substring(0, 1), "--do=get", "--prefix"); assertEquals("table: 'user'", mToolOutputLines[0]); assertEquals(" 'abc': 'def'", mToolOutputLines[1]); mAnnotator.setColumnAnnotation(INFOEMAIL, KEY, VALUE); mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=" + KEY.substring(0, 1), "--do=get", "--in-family=info", "--prefix"); assertEquals("column: 'info:email'", mToolOutputLines[0]); assertEquals(" 'abc': 'def'", mToolOutputLines[1]); assertEquals("column: 'info:name'", mToolOutputLines[2]); assertEquals(" 'abc': 'def'", mToolOutputLines[3]); // contains mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + getInfoNameURI(), "--key=" + KEY.substring(1, 2), "--do=get", "--partial"); assertEquals("column: 'info:name'", mToolOutputLines[0]); assertEquals(" 'abc': 'def'", mToolOutputLines[1]); mAnnotator.setTableAnnotation(KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=" + KEY.substring(1, 2), "--do=get", "--partial"); assertEquals("table: 'user'", mToolOutputLines[0]); assertEquals(" 'abc': 'def'", mToolOutputLines[1]); mAnnotator.setColumnAnnotation(INFOEMAIL, KEY, VALUE); mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=" + KEY.substring(1, 2), "--do=get", "--in-family=info", "--partial"); assertEquals("column: 'info:email'", mToolOutputLines[0]); assertEquals(" 'abc': 'def'", mToolOutputLines[1]); assertEquals("column: 'info:name'", mToolOutputLines[2]); assertEquals(" 'abc': 'def'", mToolOutputLines[3]); // matches mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + getInfoNameURI(), "--key=^[a-z]*$", "--do=get", "--regex"); assertEquals("column: 'info:name'", mToolOutputLines[0]); assertEquals(" 'abc': 'def'", mToolOutputLines[1]); mAnnotator.setTableAnnotation(KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=^[a-z]*$", "--do=get", "--regex"); assertEquals("table: 'user'", mToolOutputLines[0]); assertEquals(" 'abc': 'def'", mToolOutputLines[1]); mAnnotator.setColumnAnnotation(INFOEMAIL, KEY, VALUE); mAnnotator.setColumnAnnotation(INFONAME, KEY, VALUE); assertSuccess("--target=" + mTable.getURI(), "--key=^[a-z]*$", "--do=get", "--in-family=info", "--regex"); assertEquals("column: 'info:email'", mToolOutputLines[0]); assertEquals(" 'abc': 'def'", mToolOutputLines[1]); assertEquals("column: 'info:name'", mToolOutputLines[2]); assertEquals(" 'abc': 'def'", mToolOutputLines[3]); } }
42.21608
100
0.65641
2e0c96fb161151056ac0554222df486623e5db33
432
package org.zwobble.mammoth.internal.xml; import java.util.Optional; public class NamespacePrefix { private final Optional<String> prefix; private final String uri; public NamespacePrefix(Optional<String> prefix, String uri) { this.prefix = prefix; this.uri = uri; } public Optional<String> getPrefix() { return prefix; } public String getUri() { return uri; } }
19.636364
65
0.648148
e2ba76bc4f3b280acfb71290cc9ac381273b2a8e
23,997
package com.ociweb.pronghorn.ring; import static com.ociweb.pronghorn.ring.RingBuffer.addByteArray; import static com.ociweb.pronghorn.ring.RingBuffer.byteBackingArray; import static com.ociweb.pronghorn.ring.RingBuffer.byteMask; import static com.ociweb.pronghorn.ring.RingBuffer.bytePosition; import static com.ociweb.pronghorn.ring.RingBuffer.headPosition; import static com.ociweb.pronghorn.ring.RingBuffer.publishWrites; import static com.ociweb.pronghorn.ring.RingBuffer.releaseReadLock; import static com.ociweb.pronghorn.ring.RingBuffer.spinBlockOnTail; import static com.ociweb.pronghorn.ring.RingBuffer.tailPosition; import static com.ociweb.pronghorn.ring.RingBuffer.takeRingByteLen; import static com.ociweb.pronghorn.ring.RingBuffer.takeRingByteMetaData; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.junit.Test; import com.ociweb.pronghorn.GraphManager; import com.ociweb.pronghorn.ring.route.RoundRobinRouteStage2; import com.ociweb.pronghorn.ring.route.SplitterStage2; import com.ociweb.pronghorn.ring.stage.PronghornStage; import com.ociweb.pronghorn.ring.threading.StageManager; //import com.ociweb.pronghorn.ring.util.PipelineThreadPoolExecutor; import com.ociweb.pronghorn.ring.threading.ThreadPerStageManager; public class RingBufferPipeline2 { private final class DumpMonitorStage extends PronghornStage { private final RingBuffer inputRing; private int monitorMessageSize; private long nextTargetHeadPos; private long messageCount = 0; private long headPosCache; private DumpMonitorStage(GraphManager gm,RingBuffer inputRing) { super(gm,inputRing, NONE); this.inputRing = inputRing; this.monitorMessageSize = RingBuffer.from(inputRing).fragDataSize[0]; this.nextTargetHeadPos = monitorMessageSize; this.headPosCache = inputRing.headPos.longValue(); } @Override public void run() { do { if (headPosCache < nextTargetHeadPos) { headPosCache = inputRing.headPos.longValue(); if (headPosCache < nextTargetHeadPos) { return; //this is a state-less stage so it must return false not true unless there is good reason. } } //read the message int msgId = RingBuffer.readValue(0, inputRing.buffer,inputRing.mask,inputRing.workingTailPos.value); if (msgId<0) { System.out.println("exited after reading: " + messageCount+" monitor samples"); return; } long time = RingReader.readLong(inputRing, RingBufferMonitorStage.TEMPLATE_TIME_LOC); long head = RingReader.readLong(inputRing, RingBufferMonitorStage.TEMPLATE_HEAD_LOC); long tail = RingReader.readLong(inputRing, RingBufferMonitorStage.TEMPLATE_TAIL_LOC); int tmpId = RingReader.readInt(inputRing, RingBufferMonitorStage.TEMPLATE_MSG_LOC); //TODO: AAAAAA this is a mixed high low problem and must be converted to one side or the other //TODO: AAAAA need a monitor object that manages all this information so it does not cultter the businss logic //TODO: AAAAA need method on that object for building up the tree? inputRing.workingTailPos.value+=monitorMessageSize; int queueDepth = (int)(head-tail); //vs what? // System.err.println(time+" "+head+" "+tail+" "+tmpId); //doing nothing with the data releaseReadLock(inputRing); messageCount++; //block until one more byteVector is ready. nextTargetHeadPos += monitorMessageSize; } while (true); } } private final class DumpStageLowLevel extends PronghornStage { private final RingBuffer inputRing; private final boolean useRoute; private long total = 0; private int lastPos = -1; //only enter this block when we know there are records to read private long nextTargetHead; private long headPosCache; private long messageCount = 0; private DumpStageLowLevel(GraphManager gm,RingBuffer inputRing, boolean useRoute) { super(gm,inputRing, NONE); this.inputRing = inputRing; this.useRoute = useRoute; RingBuffer.setReleaseBatchSize(inputRing, 8); nextTargetHead = RingBuffer.EOF_SIZE + tailPosition(inputRing); headPosCache = headPosition(inputRing); } @Override public void run() { do { //System.err.println(headPosCache+" "+nextTargetHead+" "+messageCount+"vs"+testMessages); if (headPosCache < nextTargetHead) { headPosCache = inputRing.headPos.longValue(); if (headPosCache < nextTargetHead) { return; //come back later when we find more content } } //block until one more byteVector is ready. nextTargetHead += msgSize; int msgId = RingBuffer.takeMsgIdx(inputRing); if (msgId<0) { assertEquals(testMessages,useRoute? messageCount*splits: messageCount); RingBuffer.releaseAll(inputRing); return; } int meta = takeRingByteMetaData(inputRing); int len = takeRingByteLen(inputRing); assertEquals(testArray.length,len); //converting this to the position will cause the byte posistion to increment. int pos = bytePosition(meta, inputRing, len);//has side effect of moving the byte pointer!! if (lastPos>=0) { assertEquals((lastPos+len)&inputRing.byteMask,pos&inputRing.byteMask); } lastPos = pos; byte[] data = byteBackingArray(meta, inputRing); int mask = byteMask(inputRing); if (deepTest) { //This block causes a dramatic slow down of the work!! int i = testArray.length; while (--i>=0) { if (testArray[i]==data[(pos+i)&mask]) { } else { fail("String does not match at index "+i+" of "+len+" tailPos:"+inputRing.tailPos.get()+" byteFailurePos:"+(pos+i)+" masked "+((pos+i)&mask)); } } } releaseReadLock(inputRing); messageCount++; total += len; } while(true); } } private final class DumpStageHighLevel extends PronghornStage { private final RingBuffer inputRing; private final boolean useRoute; final int MSG_ID = FieldReferenceOffsetManager.LOC_CHUNKED_STREAM; final int FIELD_ID = FieldReferenceOffsetManager.LOC_CHUNKED_STREAM_FIELD; int msgCount=0; private DumpStageHighLevel(GraphManager gm,RingBuffer inputRing, boolean useRoute) { super(gm, inputRing, NONE); this.inputRing = inputRing; this.useRoute = useRoute; // RingWalker.setReleaseBatchSize(inputRing, 8); } @Override public void run() { int lastPos = -1; //try also releases previously read fragments while (RingReader.tryReadFragment(inputRing)) { assert(RingReader.isNewMessage(inputRing)) : "This test should only have one simple message made up of one fragment"; int msgId = RingReader.getMsgIdx(inputRing); if (msgId>=0) { msgCount++; //check the data int len = RingReader.readBytesLength(inputRing, FIELD_ID); assertEquals(testArray.length,len); //test that pos moves as expected int pos = RingReader.readBytesPosition(inputRing, FIELD_ID); if (lastPos>=0) { assertEquals((lastPos+len)&inputRing.byteMask, pos&inputRing.byteMask); } lastPos = pos; //This block causes a dramatic slow down of the work!! if (deepTest) { if (!RingReader.eqASCII(inputRing, FIELD_ID, testString)) { fail("\nexpected:\n"+testString+"\nfound:\n"+RingReader.readASCII(inputRing, FIELD_ID, new StringBuilder()).toString() ); } } } else if (-1 == msgId) { assertEquals(testMessages,useRoute? msgCount*splits: msgCount); RingReader.releaseReadLock(inputRing); //System.err.println("done"); return; } } return; } } private final class CopyStageLowLevel extends PronghornStage { private final RingBuffer outputRing; private final RingBuffer inputRing; private long nextHeadTarget; private long headPosCache; //two per message, and we only want half the buffer to be full private long tailPosCache; //keep local copy of the last time the tail was checked to avoid contention. private long nextTailTarget; private int mask; private CopyStageLowLevel(GraphManager gm,RingBuffer outputRing, RingBuffer inputRing) { super(gm,inputRing,outputRing); this.outputRing = outputRing; this.inputRing = inputRing; //RingBuffer.setReleaseBatchSize(inputRing, 8); //RingBuffer.setPublishBatchSize(outputRing, 8); //only enter this block when we know there are records to read this.nextHeadTarget = tailPosition(inputRing) + RingBuffer.EOF_SIZE; this.headPosCache = headPosition(inputRing); //two per message, and we only want half the buffer to be full this.tailPosCache = tailPosition(outputRing); //keep local copy of the last time the tail was checked to avoid contention. this.nextTailTarget = headPosition(outputRing) - (outputRing.maxSize- msgSize); this.mask = byteMask(outputRing); // data often loops around end of array so this mask is required } @Override public void run() { do { //TODO: B, need to find a way to make this pattern easy //must update headPosCache but only when we need to if (headPosCache < nextHeadTarget) { headPosCache = inputRing.headPos.longValue(); if (headPosCache < nextHeadTarget) { return; } } if (tailPosCache < nextTailTarget) { tailPosCache = outputRing.tailPos.longValue(); if (tailPosCache < nextTailTarget) { return; } } nextHeadTarget += msgSize; //read the message int msgId = RingBuffer.takeMsgIdx(inputRing); if (msgId==0) { int meta = takeRingByteMetaData(inputRing); int len = takeRingByteLen(inputRing); //is there room to write nextTailTarget += msgSize; RingBuffer.addMsgIdx(outputRing, 0); RingBuffer.addByteArrayWithMask(outputRing, mask, len, byteBackingArray(meta, inputRing), bytePosition(meta, inputRing, len)); RingBuffer.publishWrites(outputRing); RingBuffer.releaseReadLock(inputRing); } else if (-1 == msgId) { RingBuffer.publishEOF(outputRing); RingBuffer.releaseAll(inputRing); assert(RingBuffer.contentRemaining(inputRing)==0); return; } }while (true); } } private final class CopyStageHighLevel extends PronghornStage { private final RingBuffer outputRing; private final RingBuffer inputRing; final int MSG_ID = FieldReferenceOffsetManager.LOC_CHUNKED_STREAM; final int FIELD_ID = FieldReferenceOffsetManager.LOC_CHUNKED_STREAM_FIELD; int msgId=-2; private CopyStageHighLevel(GraphManager gm, RingBuffer outputRing, RingBuffer inputRing) { super(gm,inputRing,outputRing); this.outputRing = outputRing; this.inputRing = inputRing; RingReader.setReleaseBatchSize(inputRing, 8); RingWriter.setPublishBatchSize(outputRing, 8); } @Override public void run() { do { if (msgId<0) { if (RingReader.tryReadFragment(inputRing)) { assert(RingReader.isNewMessage(inputRing)) : "This test should only have one simple message made up of one fragment"; msgId = RingReader.getMsgIdx(inputRing); } else { return; } } //wait until the target ring has room for this message if (0==msgId) { if (RingWriter.tryWriteFragment(outputRing,MSG_ID)) { //copy this message from one ring to the next //NOTE: in the normal world I would expect the data to be modified before getting moved. RingReader.copyBytes(inputRing, outputRing, FIELD_ID, FIELD_ID); RingWriter.publishWrites(outputRing); msgId = -2; } else { return; } } else if (-1==msgId) { RingWriter.publishEOF(outputRing); //TODO, hidden blocking call RingReader.releaseReadLock(inputRing); assert(RingBuffer.contentRemaining(inputRing)==0); return; } } while (true); } } private final class ProductionStageLowLevel extends PronghornStage { private final RingBuffer outputRing; private long messageCount; private long nextTailTarget; private long tailPosCache; private ProductionStageLowLevel(GraphManager gm, RingBuffer outputRing) { super(gm,NONE,outputRing); this.outputRing = outputRing; this.messageCount = testMessages; this.nextTailTarget = headPosition(outputRing) - (outputRing.maxSize-msgSize); this.tailPosCache = tailPosition(outputRing); RingBuffer.setPublishBatchSize(outputRing, 8); } @Override public void run() { do { if (tailPosCache < nextTailTarget) { tailPosCache = outputRing.tailPos.longValue(); if (tailPosCache < nextTailTarget) { return; } } nextTailTarget += msgSize; if (--messageCount>=0) { //write the record RingBuffer.addMsgIdx(outputRing, 0); addByteArray(testArray, 0, testArray.length, outputRing); publishWrites(outputRing); } else { RingBuffer.publishEOF(outputRing); shutdown(); return; } } while (true); } } private final class ProductionStageHighLevel extends PronghornStage { private final RingBuffer outputRing; private final int MESSAGE_LOC = FieldReferenceOffsetManager.LOC_CHUNKED_STREAM; private final int FIELD_LOC = FieldReferenceOffsetManager.LOC_CHUNKED_STREAM_FIELD; private long messageCount = testMessages; private ProductionStageHighLevel(GraphManager gm, RingBuffer outputRing) { super(gm,NONE,outputRing); this.outputRing = outputRing; RingWriter.setPublishBatchSize(outputRing, 8); } @Override public void run() { while (messageCount>0) { if (RingWriter.tryWriteFragment(outputRing, MESSAGE_LOC)) { RingWriter.writeBytes(outputRing, FIELD_LOC, testArray, 0, testArray.length); RingWriter.publishWrites(outputRing); messageCount--; } else { return; } } RingWriter.publishEOF(outputRing); shutdown(); return;//do not come back } } private static final int TIMEOUT_SECONDS = 120; private static final String testString1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ:,.-_+()*@@@@@@@@@@@@@@@@"; private static final String testString = testString1+testString1+testString1+testString1+testString1+testString1+testString1+testString1; //using length of 61 because it is prime and will wrap at odd places private final byte[] testArray = testString.getBytes();//, this is a reasonable test message.".getBytes(); private final long testMessages = 1000000; private final int stages = 4; private final int splits = 2; private final boolean deepTest = false;//can be much faster if we change the threading model private final byte primaryBits = 6; private final byte secondaryBits = 15; private final int msgSize = FieldReferenceOffsetManager.RAW_BYTES.fragDataSize[0]; @Test public void pipelineExampleHighLevelRoute() { pipelineTest(true, false, true, true); } @Test public void pipelineExampleLowLevelRoute() { pipelineTest(false, false, true, true); } @Test public void pipelineExampleHighLevelRouteWithMonitor() { pipelineTest(true, true, true, true); } @Test public void pipelineExampleLowLevelRouteWithMonitor() { pipelineTest(false, true, true, true); } @Test public void pipelineExampleHighLevelSplits() { pipelineTest(true, false, true, false); } @Test public void pipelineExampleLowLevelSplits() { pipelineTest(false, false, true, false); } @Test public void pipelineExampleHighLevelSplitsWithMonitor() { pipelineTest(true, true, true, false); } @Test public void pipelineExampleLowLevelSplitsWithMonitor() { pipelineTest(false, true, true, false); } @Test public void pipelineExampleHighLevel() { pipelineTest(true, false, false, true); } @Test public void pipelineExampleLowLevel() { pipelineTest(false, false, false, true); } @Test public void pipelineExampleHighLevelWithMonitor() { pipelineTest(true, true, false, true); } @Test public void pipelineExampleLowLevelWithMonitor() { pipelineTest(false, true, false, true); } private void pipelineTest(boolean highLevelAPI, boolean monitor, boolean useTap, boolean useRouter) { GraphManager gm = new GraphManager(); StageManager normalService = new ThreadPerStageManager(gm); System.out.println(); assertEquals("For "+FieldReferenceOffsetManager.RAW_BYTES.name+" expected no need to add field.", 0,FieldReferenceOffsetManager.RAW_BYTES.fragNeedsAppendedCountOfBytesConsumed[0]); int stagesBetweenSourceAndSink = stages -2; int daemonThreads = (useTap ? stagesBetweenSourceAndSink : 0); int schcheduledThreads = 1; int normalThreads = 2/* source and sink*/ + ((useTap ? splits : 1)*stagesBetweenSourceAndSink); int totalThreads = daemonThreads+schcheduledThreads+normalThreads; //build all the rings int j = stages-1; RingBuffer[] rings = new RingBuffer[j]; PronghornStage[] monitorStages = null; RingBuffer[] monitorRings = null; FieldReferenceOffsetManager montorFROM = null; if (monitor) { monitorStages = new PronghornStage[j]; monitorRings = new RingBuffer[j]; montorFROM = RingBufferMonitorStage.buildFROM(); } byte ex = (byte)(useRouter ? 0 : 1); while (--j>=0) { if (stages-2==j) { //need to make this ring bigger when the splitter is used rings[j] = new RingBuffer(new RingBufferConfig((byte)(primaryBits+ex), (byte)(secondaryBits+ex), null, FieldReferenceOffsetManager.RAW_BYTES)); } else { rings[j] = new RingBuffer(new RingBufferConfig(primaryBits, secondaryBits, null, FieldReferenceOffsetManager.RAW_BYTES)); } assertEquals("For "+rings[j].ringWalker.from.name+" expected no need to add field.",0,rings[j].ringWalker.from.fragNeedsAppendedCountOfBytesConsumed[0]); //test by starting at different location in the ring to force roll over. rings[j].reset(rings[j].maxSize-13,rings[j].maxByteSize-101); if (monitor) { monitorRings[j] = new RingBuffer(new RingBufferConfig((byte)16, (byte)2, null, montorFROM)); //assertTrue(mo) monitorStages[j] = new RingBufferMonitorStage2(gm, rings[j], monitorRings[j]); //this is a bit complex may be better to move this inside on thread? GraphManager.setScheduleRate(gm, 41000000, monitorStages[j]); final RingBuffer mon = monitorRings[j]; GraphManager.setScheduleRate(gm, 47000000, new DumpMonitorStage(gm, mon)); } } //add all the stages start running j = 0; RingBuffer outputRing = rings[j]; GraphManager.setContinuousRun(gm, highLevelAPI ? new ProductionStageHighLevel(gm, outputRing) : new ProductionStageLowLevel(gm, outputRing)); int i = stagesBetweenSourceAndSink; while (--i>=0) { if (useTap & 0==i) { //only do taps on first stage or this test could end up using many many threads. RingBuffer[] splitsBuffers = new RingBuffer[splits]; splitsBuffers[0] = rings[j+1];//must jump ahead because we are setting this early assert(splitsBuffers[0].pBits == ex+primaryBits); if (splits>1) { int k = splits; while (--k>0) { splitsBuffers[k] = new RingBuffer(new RingBufferConfig((byte)(primaryBits+ex), (byte)(secondaryBits+ex), null, FieldReferenceOffsetManager.RAW_BYTES)); RingBuffer inputRing = splitsBuffers[k]; boolean useRoute = useTap&useRouter; /// GraphManager.setContinuousRun(gm, highLevelAPI ? new DumpStageHighLevel(gm, inputRing, useRoute) : new DumpStageLowLevel(gm, inputRing, useRoute)); } } if (useRouter) { int r = splitsBuffers.length; while (--r>=0) { RingBuffer.setPublishBatchSize(splitsBuffers[r],8); } RingReader.setReleaseBatchSize(rings[j], 8); GraphManager.setContinuousRun(gm, new RoundRobinRouteStage2(gm, rings[j++], splitsBuffers)); } else { GraphManager.setContinuousRun(gm, new SplitterStage2(gm, rings[j++], splitsBuffers)); } } else { RingBuffer inputRing = rings[j++]; RingBuffer outputRing1 = rings[j]; GraphManager.setContinuousRun(gm, highLevelAPI ? new CopyStageHighLevel(gm, outputRing1, inputRing) : new CopyStageLowLevel(gm, outputRing1, inputRing)); } } RingBuffer inputRing = rings[j]; boolean useRoute = useTap&useRouter; GraphManager.setContinuousRun(gm, highLevelAPI ? new DumpStageHighLevel(gm, inputRing, useRoute) : new DumpStageLowLevel(gm, inputRing, useRoute)); System.out.println("########################################################## Testing "+ (highLevelAPI?"HIGH level ":"LOW level ")+(useTap? "using "+splits+(useRouter?" router ":" splitter "):"")+(monitor?"monitored":"")+" totalThreads:"+totalThreads); //start the timer final long start = System.currentTimeMillis(); normalService.startup(); //blocks until all the submitted runnables have stopped //this timeout is set very large to support slow machines that may also run this test. boolean cleanExit = normalService.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!cleanExit) { //dump the Queue data int k=0; while (k<rings.length){ System.err.println(GraphManager.getRingProducer(gm, rings[k].ringId)+" ->\n "+rings[k].toString()+" -> "+GraphManager.getRingConsumer(gm, rings[k].ringId)); k++; } System.err.println(GraphManager.getRingConsumer(gm, rings[k-1].ringId)); } assertTrue("Test timed out, forced shut down of stages",cleanExit); //the tests are all getting cut here int t = rings.length; while (--t>=0) { assertFalse("Unexpected error in thread, see console output",RingBuffer.isShutdown(rings[t])); } if (monitor) { t = monitorRings.length; while (--t>=0) { assertFalse("Unexpected error in thread, see console output",RingBuffer.isShutdown(monitorRings[t])); } } //TODO: should we flush all the monitoring? long duration = System.currentTimeMillis()-start; long bytes = testMessages * (long)testArray.length; long bpSec = (1000l*bytes*8l)/duration; long msgPerMs = testMessages/duration; System.out.println("Bytes:"+bytes+" Gbits/sec:"+(bpSec/1000000000f)+" stages:"+stages+" msg/ms:"+msgPerMs+" MsgSize:"+testArray.length); t = rings.length; while (--t>=0) { RingBuffer.shutdown(rings[t]); } if (monitor) { t = monitorRings.length; while (--t>=0) { RingBuffer.shutdown(monitorRings[t]); } } } }
34.727931
256
0.66625
0c49a85957ee3d32acb3cab3237db741b0513269
13,235
/** * Copyright (c) 2018 MapR, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ojai.store.base; import java.math.BigDecimal; import org.ojai.Document; import org.ojai.DocumentStream; import org.ojai.FieldPath; import org.ojai.Value; import org.ojai.annotation.API; import org.ojai.store.DocumentMutation; import org.ojai.store.DocumentStore; import org.ojai.store.Query; import org.ojai.store.QueryCondition; import org.ojai.store.QueryResult; import org.ojai.store.exceptions.MultiOpException; import org.ojai.store.exceptions.StoreException; import com.google.common.base.Preconditions; /** * An adapter implementation of {@linkplain DocumentStore} interface which forwards the * individual API calls to the wrapped Store object. */ @API.Public @SuppressWarnings("deprecation") public class ForwardingStore implements DocumentStore { private final DocumentStore store; public ForwardingStore(final DocumentStore store) { this.store = Preconditions.checkNotNull(store); } @Override public void close() throws StoreException { store.close(); } @Override public boolean isReadOnly() { return store.isReadOnly(); } @Override public void beginTrackingWrites() throws StoreException { store.beginTrackingWrites(); } @Override public void beginTrackingWrites(final String previousWritesContext) throws StoreException { store.beginTrackingWrites(previousWritesContext); } @Override public String endTrackingWrites() throws StoreException { return store.endTrackingWrites(); } @Override public void clearTrackedWrites() throws StoreException { store.clearTrackedWrites(); } @Override public Document findById(final Value _id, final String... fieldPaths) throws StoreException { return store.findById(_id, fieldPaths); } @Override public Document findById(final Value _id, final FieldPath... fieldPaths) throws StoreException { return store.findById(_id, fieldPaths); } @Override public Document findById(final Value _id, final QueryCondition condition) throws StoreException { return store.findById(_id, condition); } @Override public Document findById(final Value _id, final QueryCondition condition, final String... fieldPaths) throws StoreException { return store.findById(_id, condition, fieldPaths); } @Override public Document findById(final Value _id, final QueryCondition condition, final FieldPath... fieldPaths) throws StoreException { return store.findById(_id, condition, fieldPaths); } @Override public QueryResult find(final Query query) throws StoreException { return store.find(query); } @Override public DocumentStream findQuery(final Query query) throws StoreException { return store.find(query); } @Override public DocumentStream findQuery(final String queryJSON) throws StoreException { return store.findQuery(queryJSON); } @Override public void insertOrReplace(final Value _id, final Document doc) throws StoreException { store.insertOrReplace(_id, doc); } @Override public void update(final Value _id, final DocumentMutation mutation) throws StoreException { store.update(_id, mutation); } @Override public void delete(final Value _id) throws StoreException { store.delete(_id); } @Override public void insert(final Value _id, final Document doc) throws StoreException { store.insert(_id, doc); } @Override public void replace(final Value _id, final Document doc) throws StoreException { store.replace(_id, doc); } @Override public void increment(final Value _id, final String field, final byte inc) throws StoreException { store.increment(_id, field, inc); } @Override public void increment(final Value _id, final String field, final short inc) throws StoreException { store.increment(_id, field, inc); } @Override public void increment(final Value _id, final String field, final int inc) throws StoreException { store.increment(_id, field, inc); } @Override public void increment(final Value _id, final String field, final long inc) throws StoreException { store.increment(_id, field, inc); } @Override public void increment(final Value _id, final String field, final float inc) throws StoreException { store.increment(_id, field, inc); } @Override public void increment(final Value _id, final String field, final double inc) throws StoreException { store.increment(_id, field, inc); } @Override public void increment(final Value _id, final String field, final BigDecimal inc) throws StoreException { store.increment(_id, field, inc); } @Override public boolean checkAndMutate(final Value _id, final QueryCondition condition, final DocumentMutation mutation) throws StoreException { return store.checkAndUpdate(_id, condition, mutation); } @Override public boolean checkAndDelete(final Value _id, final QueryCondition condition) throws StoreException { return store.checkAndDelete(_id, condition); } @Override public boolean checkAndReplace(final Value _id, final QueryCondition condition, final Document doc) throws StoreException { return store.checkAndReplace(_id, condition, doc); } @Override public void flush() throws StoreException { store.flush(); } @Override public Document findById(final String id) throws StoreException { return store.findById(id); } @Override public Document findById(final Value id) throws StoreException { return store.findById(id); } @Override public Document findById(final String id, final String... paths) throws StoreException { return store.findById(id, paths); } @Override public Document findById(final String id, final FieldPath... paths) throws StoreException { return store.findById(id, paths); } @Override public Document findById(final String id, final QueryCondition c) throws StoreException { return store.findById(id, c); } @Override public Document findById(final String id, final QueryCondition c, final String... paths) throws StoreException { return store.findById(id, c, paths); } @Override public Document findById(final String id, final QueryCondition c, final FieldPath... paths) throws StoreException { return store.findById(id, c, paths); } @Override public DocumentStream find() throws StoreException { return store.find(); } @Override public DocumentStream find(final String... paths) throws StoreException { return store.find(paths); } @Override public DocumentStream find(final FieldPath... paths) throws StoreException { return store.find(paths); } @Override public DocumentStream find(final QueryCondition c) throws StoreException { return store.find(c); } @Override public DocumentStream find(final QueryCondition c, final String... paths) throws StoreException { return store.find(c, paths); } @Override public DocumentStream find(final QueryCondition c, final FieldPath... paths) throws StoreException { return store.find(c, paths); } @Override public void insertOrReplace(final Document r) throws StoreException { store.insertOrReplace(r); } @Override public void insertOrReplace(final String id, final Document r) throws StoreException { store.insertOrReplace(id, r); } @Override public void insertOrReplace(final Document r, final FieldPath fieldAsKey) throws StoreException { store.insertOrReplace(r, fieldAsKey); } @Override public void insertOrReplace(final Document r, final String fieldAsKey) throws StoreException { store.insertOrReplace(r, fieldAsKey); } @Override public void insertOrReplace(final DocumentStream rs) throws MultiOpException { store.insertOrReplace(rs); } @Override public void insertOrReplace(final DocumentStream rs, final FieldPath fieldAsKey) throws MultiOpException { store.insertOrReplace(rs, fieldAsKey); } @Override public void insertOrReplace(final DocumentStream rs, final String fieldAsKey) throws MultiOpException { store.insertOrReplace(rs, fieldAsKey); } @Override public void update(final String id, final DocumentMutation m) throws StoreException { store.update(id, m); } @Override public void delete(final String id) throws StoreException { store.delete(id); } @Override public void delete(final Document r) throws StoreException { store.delete(r); } @Override public void delete(final Document r, final FieldPath fieldAsKey) throws StoreException { store.delete(r, fieldAsKey); } @Override public void delete(final Document r, final String fieldAsKey) throws StoreException { store.delete(r, fieldAsKey); } @Override public void delete(final DocumentStream rs) throws MultiOpException { store.delete(rs); } @Override public void delete(final DocumentStream rs, final FieldPath fieldAsKey) throws MultiOpException { store.delete(rs, fieldAsKey); } @Override public void delete(final DocumentStream rs, final String fieldAsKey) throws MultiOpException { store.delete(rs, fieldAsKey); } @Override public void insert(final String id, final Document r) throws StoreException { store.insert(id, r); } @Override public void insert(final Document r) throws StoreException { store.insert(r); } @Override public void insert(final Document r, final FieldPath fieldAsKey) throws StoreException { store.insert(r, fieldAsKey); } @Override public void insert(final Document r, final String fieldAsKey) throws StoreException { store.insert(r, fieldAsKey); } @Override public void insert(final DocumentStream rs) throws MultiOpException { store.insert(rs); } @Override public void insert(final DocumentStream rs, final FieldPath fieldAsKey) throws MultiOpException { store.insert(rs, fieldAsKey); } @Override public void insert(final DocumentStream rs, final String fieldAsKey) throws MultiOpException { store.insert(rs, fieldAsKey); } @Override public void replace(final String id, final Document r) throws StoreException { store.replace(id, r); } @Override public void replace(final Document r) throws StoreException { store.replace(r); } @Override public void replace(final Document r, final FieldPath fieldAsKey) throws StoreException { store.replace(r, fieldAsKey); } @Override public void replace(final Document r, final String fieldAsKey) throws StoreException { store.replace(r, fieldAsKey); } @Override public void replace(final DocumentStream rs) throws MultiOpException { store.replace(rs); } @Override public void replace(final DocumentStream rs, final FieldPath fieldAsKey) throws MultiOpException { store.replace(rs, fieldAsKey); } @Override public void replace(final DocumentStream rs, final String fieldAsKey) throws MultiOpException { store.replace(rs, fieldAsKey); } @Override public void increment(final String id, final String field, final byte inc) throws StoreException { store.increment(id, field, inc); } @Override public void increment(final String id, final String field, final short inc) throws StoreException { store.increment(id, field, inc); } @Override public void increment(final String id, final String field, final int inc) throws StoreException { store.increment(id, field, inc); } @Override public void increment(final String id, final String field, final long inc) throws StoreException { store.increment(id, field, inc); } @Override public void increment(final String id, final String field, final float inc) throws StoreException { store.increment(id, field, inc); } @Override public void increment(final String id, final String field, final double inc) throws StoreException { store.increment(id, field, inc); } @Override public void increment(final String id, final String field, final BigDecimal inc) throws StoreException { store.increment(id, field, inc); } @Override public boolean checkAndMutate(final String id, final QueryCondition condition, final DocumentMutation m) throws StoreException { return store.checkAndMutate(id, condition, m); } @Override public boolean checkAndDelete(final String id, final QueryCondition condition) throws StoreException { return store.checkAndDelete(id, condition); } @Override public boolean checkAndReplace(final String id, final QueryCondition condition, final Document r) throws StoreException { return store.checkAndReplace(id, condition, r); } }
28.279915
117
0.740083
ba0d24e5c4c0b01bb59b67f4db906b9c77161d9d
748
package ru.divinecraft.customstuff.api.block.manager; import lombok.AllArgsConstructor; @AllArgsConstructor public class UnknownBlockTypeException extends RuntimeException { public UnknownBlockTypeException(final String message) { super(message); } public UnknownBlockTypeException(final String message, final Throwable cause) { super(message, cause); } public UnknownBlockTypeException(final Throwable cause) { super(cause); } public UnknownBlockTypeException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
29.92
114
0.719251
c1b08003673be59564d29dd92e944472227b8e5b
5,096
package com.example.mateverunica.verunica_fueltrack; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Serializable; import java.lang.reflect.Type; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Iterator; /** * Created by Mate Verunica on 1/14/2016. */ // This class allows the user to view the items in the listview public class ViewLog extends AppCompatActivity{ // Initialize the Variables private ArrayList<Entry> entryArray; private ListView entryList; private static final String FILENAME = "file.sav"; private TextView totalCostView; private Entry currEntry; private float totalCost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view_log_layout); //Set entryList to ListView entryList = (ListView) findViewById(R.id.listView); loadFromFile(); // Initialize the adapter EntryAdapter adapter = new EntryAdapter(this, entryArray); entryList.setAdapter(adapter); // totalCostView = (TextView) findViewById(R.id.textView2); // Using Iterator to calculate the total cost Iterator arrayListIterator = entryArray.iterator(); while(arrayListIterator.hasNext()){ currEntry = (Entry) arrayListIterator.next(); totalCost = totalCost + (currEntry.getFuelAmount() * (currEntry.getUnitCost() / 100 )); } totalCostView.setText("$ " + String.format("%.2f",totalCost)); // Using an item on click listener to do editing and go to EditLog.class entryList.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView adapterView, View view, int position, long id) { Entry editEntry = entryArray.get(position); saveInFile(); Intent intent = new Intent(view.getContext(), EditLog.class); intent.putExtra("message", (Serializable) editEntry); intent.putExtra("arrayList", (Serializable) entryArray); intent.putExtra("position", position); startActivity(intent); } }); } @Override protected void onStart() { super.onStart(); // Reload the file on start after returning from the edit log activity loadFromFile(); // Reinitialize the totalCost to be 0 then calculate new values based on the new entries totalCost = 0; Iterator arrayListIterator = entryArray.iterator(); while(arrayListIterator.hasNext()){ currEntry = (Entry) arrayListIterator.next(); totalCost = totalCost + (currEntry.getFuelAmount() * (currEntry.getUnitCost() / 100 )); } totalCostView.setText("$ " + String.format("%.2f",totalCost)); EntryAdapter adapter = new EntryAdapter(this, entryArray); entryList.setAdapter(adapter); } private void loadFromFile() { try { FileInputStream fis = openFileInput(FILENAME); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); Gson gson = new Gson(); // Took from https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html 01-19 2016 Type listType = new TypeToken<ArrayList<Entry>>() {}.getType(); entryArray = gson.fromJson(in, listType); } catch (FileNotFoundException e) { entryArray = new ArrayList<Entry>(); } catch (IOException e) { throw new RuntimeException(); } } private void saveInFile() { try { FileOutputStream fos = openFileOutput(FILENAME, 0); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos)); Gson gson = new Gson(); gson.toJson(entryArray, out); out.flush(); fos.close(); } catch (FileNotFoundException e) { throw new RuntimeException(); } catch (IOException e) { throw new RuntimeException(); } } }
35.636364
126
0.643838
becb530c5dbe78a538e3d67e3236ca3fa34a5161
1,621
package com.puresoltechnologies.genesis.transformation.cassandra; import java.util.Properties; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; import com.puresoltechnologies.genesis.commons.SequenceMetadata; import com.puresoltechnologies.genesis.transformation.spi.AbstractTransformationSequence; public class CassandraTransformationSequence extends AbstractTransformationSequence { private Cluster cluster; private Session session; private final String host; private final int port; private final String keyspace; public CassandraTransformationSequence(String host, int port, SequenceMetadata metadata) { super(metadata); this.host = host; this.port = port; this.keyspace = null; } public CassandraTransformationSequence(String host, int port, String keyspace, SequenceMetadata metadata) { super(metadata); this.host = host; this.port = port; this.keyspace = keyspace; } @Override public final void open(Properties configuration) { cluster = Cluster.builder().addContactPoint(host).withPort(port).build(); if (keyspace == null) { session = cluster.connect(); } else { session = cluster.connect(keyspace); } } @Override public final void close() { try { session.close(); session = null; } finally { cluster.close(); cluster = null; } } public final String getHost() { return host; } public final int getPort() { return port; } public final String getKeyspace() { return keyspace; } public Session getSession() { return session; } }
23.157143
111
0.716225
c906db29b2056cde958ad71a71e1672c99fd47e2
3,940
/* * Copyright (C) 2020 The ToastHub 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. */ /** * @author Edward H. Seufert */ package org.toasthub.pm.model; import java.io.Serializable; import java.time.Instant; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.toasthub.core.general.api.View; import org.toasthub.core.general.model.BaseEntity; import org.toasthub.core.general.model.Text; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonView; @Entity @Table(name = "pm_role") public class Role extends BaseEntity implements Serializable{ private static final long serialVersionUID = 1L; protected Team team; protected String name; protected String code; protected Set<RolePermission> permissions; protected Instant startDate; protected Instant endDate; protected Set<MemberRole> memberRoles; // transient protected MemberRole memberRole; //Constructor public Role() { super(); } public Role(String code, Text title, Boolean defaultLang, String dir){ this.setActive(true); this.setArchive(false); this.setLocked(false); this.setCreated(Instant.now()); } public Role(boolean active, boolean archive, boolean locked, String name, String code, Team team, Instant startDate, Instant endDate) { this.setActive(active); this.setArchive(archive); this.setLocked(locked); this.setName(name); this.setCode(code); this.setTeam(team); this.setStartDate(startDate); this.setEndDate(endDate); } // Methods @JsonIgnore @ManyToOne(targetEntity = Team.class) @JoinColumn(name = "team_id") public Team getTeam() { return team; } public void setTeam(Team team) { this.team = team; } @JsonView({View.Member.class,View.Admin.class}) @Column(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } @JsonView({View.Member.class,View.Admin.class}) @Column(name = "code") public String getCode() { return code; } public void setCode(String code) { this.code = code; } @JsonIgnore @OneToMany(mappedBy = "role", cascade = CascadeType.ALL) public Set<RolePermission> getPermissions() { return permissions; } public void setPermissions(Set<RolePermission> permissions) { this.permissions = permissions; } @JsonView({View.Member.class,View.Admin.class}) @Column(name = "start_date") public Instant getStartDate() { return startDate; } public void setStartDate(Instant startDate) { this.startDate = startDate; } @JsonView({View.Member.class,View.Admin.class}) @Column(name = "end_date") public Instant getEndDate() { return endDate; } public void setEndDate(Instant endDate) { this.endDate = endDate; } @JsonView({View.Member.class,View.Admin.class}) @Transient public MemberRole getMemberRole() { return memberRole; } public void setMemberRole(MemberRole memberRole) { this.memberRole = memberRole; } @JsonIgnore @OneToMany(mappedBy = "role", cascade = CascadeType.ALL) public Set<MemberRole> getMemberRoles() { return memberRoles; } public void setMemberRoles(Set<MemberRole> memberRoles) { this.memberRoles = memberRoles; } }
25.095541
136
0.744162
b6076703653483a89e5e2c9cd6548e3d0d707a82
6,201
package com.github.nijian.jkeel.algorithms; import java.net.URI; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * AlgorithmContextManager is responsible for creating AlgorithmContext with global identifier. * * @author nj * @since 0.0.1 */ public final class AlgorithmContextManager { /** * Singleton instance */ private static AlgorithmContextManager instance; /** * AlgorithmContext cache, will be change to repository later. */ private final static ConcurrentMap<String, AlgorithmContext> contexts = new ConcurrentHashMap(); /** * private construction */ private AlgorithmContextManager() { } /** * Get algorithm context manager singleton instance * * @return AlgorithmContextManager instance */ public static AlgorithmContextManager getInstance() { if (instance == null) { synchronized (AlgorithmContextManager.class) { if (instance == null) { instance = new AlgorithmContextManager(); } } } return instance; } /** * Create AlgorithmContext with global identifier * * @param cid algorithm context global identifier * @param configUri uri of the algorithm config resource * @param clz class instance of algorithm config * @param env environment variables * @param <C> class type of algorithm config * @return algorithm context */ public <C extends AlgorithmConfig> AlgorithmContext createContext(String cid, URI configUri, Class<C> clz, Properties env) { AlgorithmContext context = contexts.get(cid); if (context == null) { synchronized (contexts) { context = contexts.get(cid); if (context == null) { AlgorithmConfig aConfig; try { aConfig = clz.newInstance(); aConfig.init(cid, configUri, null, env); } catch (Exception e) { throw new RuntimeException("Algorithm config can not be initialized", e); } context = new AlgorithmContext(cid, aConfig); contexts.put(cid, context); } } } return context; } /** * Create TemplateAlgorithmContext with global identifier * * @param cid algorithm context global identifier * @param template algorithm template * @param configUri uri of the algorithm config resource * @param clz class instance of algorithm config * @param env environment variables * @param <C> class type of algorithm config * @return template algorithm context */ public <C extends AlgorithmConfig> TemplateAlgorithmContext createTemplateContext(final String cid, final AlgorithmTemplate template, final URI configUri, final Class<C> clz, final Properties env) { return createTemplateContext(cid, template, configUri, clz, null, env); } /** * Create TemplateAlgorithmContext with global identifier * * @param cid algorithm context global identifier * @param template algorithm template * @param configUri uri of the algorithm config resource * @param clz class instance of algorithm config * @param delegateClz class instance of delegate config * @param env environment variables * @param <C> class type of algorithm config * @param <T> class type of delegate config * @return template algorithm context * @since 0.0.2 */ public <C extends AlgorithmConfig, T> TemplateAlgorithmContext createTemplateContext(final String cid, final AlgorithmTemplate template, final URI configUri, final Class<C> clz, final Class<T> delegateClz, final Properties env) { TemplateAlgorithmContext context = (TemplateAlgorithmContext) contexts.get(cid); if (context == null) { synchronized (contexts) { context = (TemplateAlgorithmContext) contexts.get(cid); if (context == null) { AlgorithmConfig aConfig; try { aConfig = clz.getConstructor().newInstance(); aConfig.init(cid, configUri, delegateClz, env); } catch (Exception e) { throw new RuntimeException("Algorithm config can not be initialized", e); } context = new TemplateAlgorithmContext(cid, template, aConfig); contexts.put(cid, context); } } } return context; } /** * Contains the algorithm context or not? * * @param cid algorithm context global identifier * @return true or false * @since 0.0.2 */ public boolean contains(String cid) { return contexts.containsKey(cid); } /** * Get algorithm context * * @param cid algorithm context global identifier * @return AlgorithmContext * @since 0.0.3 */ public AlgorithmContext getAlgorithmContext(String cid) { return contexts.get(cid); } }
38.277778
128
0.526205
fbb4d0ed50c7787fa4b83eca5bc0e054c5bb9fa9
476
package io.sentry.util; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; @ApiStatus.Internal public final class Pair<A, B> { private final @Nullable A first; private final @Nullable B second; public Pair(final @Nullable A first, final @Nullable B second) { this.first = first; this.second = second; } public @Nullable A getFirst() { return first; } public @Nullable B getSecond() { return second; } }
19.833333
66
0.703782
f7320ed43d3fc4f451b67e055ada6249368e5f94
5,853
package sa.revenue; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import com.orhanobut.hawk.Hawk; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.concurrent.TimeUnit; import sa.revenue.advertisers.admob.AdmobUtils; import sa.revenue.advertisers.admob.HistoricalLoadAdmobService; import sa.revenue.advertisers.admob.UpdateAdmobService; import sa.revenue.advertisers.tapjoy.HistoricalLoadTapjoyService; import sa.revenue.advertisers.tapjoy.TapjoyUtils; import sa.revenue.advertisers.tapjoy.UpdateTapjoyService; /** * Created by un on 12/29/2015. */ public class Utils { static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); public static Calendar updateCalendar(Calendar oldCalendar, int hour_of_day, int minute, int second, int millis) { Calendar newCalendar = (Calendar) oldCalendar.clone(); newCalendar.set(Calendar.HOUR_OF_DAY, hour_of_day); newCalendar.set(Calendar.MINUTE, minute); newCalendar.set(Calendar.SECOND, second); newCalendar.set(Calendar.MILLISECOND, millis); return newCalendar; } public final static boolean isValidEmail(CharSequence target) { return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } public static String formatDoubleAsCurreny(double value) { return NumberFormat.getCurrencyInstance().format(value); } public static String getDateXdaysAgo(int days) throws ParseException { Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, -days); return dateFormat.format(new Date(c.getTimeInMillis())); } public static void checkAndUpdateData(Context context) { //Start admob when is initiated if (AdmobUtils.admobSetupCorrect(context)) { try { String startDate = Hawk.get(context.getString(R.string.admob_start_date_key)); long daysAgo = Utils.getDaysAgo(AdmobUtils.admobDateFormat, startDate); long daysInDB = AdmobUtils.getDaysInDB(); //When database is up to date only update little, otherwise check which misses //TODO - Might be a better way. Intent admob; if (daysAgo == daysInDB || (daysAgo + 1) == daysInDB) { admob = new Intent(context, UpdateAdmobService.class); } else { admob = new Intent(context, HistoricalLoadAdmobService.class); } context.startService(admob); } catch (ParseException e) { e.printStackTrace(); } } //and should be valid to. if (TapjoyUtils.tapjoyCredentialsAreValid(context)) { try { String startDate = Hawk.get(context.getString(R.string.tapjoy_start_date_key)); long daysAgo = Utils.getDaysAgo(TapjoyUtils.tapjoyDateFormat, startDate); long daysInDB = TapjoyUtils.getDaysInDB(); //When database is up to date only update little, otherwise check which misses //TODO - Might be a better way. Intent tapjoy; if (daysAgo == daysInDB || (daysAgo + 1) == daysInDB) { tapjoy = new Intent(context, UpdateTapjoyService.class); } else { tapjoy = new Intent(context, HistoricalLoadTapjoyService.class); } context.startService(tapjoy); } catch (ParseException e) { e.printStackTrace(); } } } // // Advertiser date functions // // Get number of days to date in past public static long getDaysAgo(SimpleDateFormat dateFormat, String date) throws ParseException { Calendar c = Calendar.getInstance(); c.setTime(dateFormat.parse(date)); long diff = Calendar.getInstance().getTimeInMillis() - c.getTimeInMillis(); return TimeUnit.MILLISECONDS.toDays(diff); } //Formats date picked from date picket to date public static String getDateFromDatePicker(SimpleDateFormat dateFormat, int year, int month, int day) { Calendar c = Calendar.getInstance(); c.set(year, month, day); return dateFormat.format(c.getTime()); } //get today formated as date string public static String todayString(SimpleDateFormat dateFormat) throws ParseException { Calendar c = Calendar.getInstance(); return dateFormat.format(new Date(c.getTimeInMillis())); } //Get the next day based on a date string public static String nextDayString(SimpleDateFormat dateFormat, String date) throws ParseException { Calendar c = Calendar.getInstance(); c.setTime(dateFormat.parse(date)); c.add(Calendar.DATE, 1); return dateFormat.format(new Date(c.getTimeInMillis())); } //When date string is after today retun false, else true public static boolean shouldParseNextDay(SimpleDateFormat dateFormat, String oldDate) throws ParseException { Calendar old = Calendar.getInstance(); old.setTime(dateFormat.parse(oldDate)); old.set(Calendar.HOUR_OF_DAY, 23); old.set(Calendar.MINUTE, 59); old.set(Calendar.SECOND, 59); return old.before(Calendar.getInstance()); } //Convert date to calendar public static Calendar getCalendar(SimpleDateFormat dateFormat, String date) { Calendar c = Calendar.getInstance(); try { c.setTime(dateFormat.parse(date)); } catch (ParseException e) { e.printStackTrace(); } return c; } }
37.76129
118
0.654024
0eae322521e13cd66326fd57b0453b77ad087923
2,617
package com.forezp.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory; /** * Created by fangzhipeng on 2017/5/27. */ @Configuration @EnableAuthorizationServer public class OAuth2Config extends AuthorizationServerConfigurerAdapter { @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("user-service") .secret("123456") .scopes("service") .autoApprove(true) .authorizedGrantTypes("implicit","refresh_token", "password", "authorization_code") .accessTokenValiditySeconds(24*3600);//24小时过期 } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(tokenStore()).tokenEnhancer(jwtTokenEnhancer()).authenticationManager(authenticationManager); } @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Bean public TokenStore tokenStore() { return new JwtTokenStore(jwtTokenEnhancer()); } @Bean protected JwtAccessTokenConverter jwtTokenEnhancer() { KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("fzp-jwt.jks"), "fzp123".toCharArray()); JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setKeyPair(keyStoreKeyFactory.getKeyPair("fzp-jwt")); return converter; } }
45.912281
133
0.784486
8edf9384c0e19ebc1cdb681b87eb049349f9f7c8
5,526
/** * * Copyright 2005 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. */ package org.apache.geronimo.deployment.xmlbeans; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import java.util.Collection; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.w3c.dom.Element; import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; /** * @version $Rev$ $Date$ */ public class XmlBeansUtil { private static final Map NAMESPACE_UPDATES = new HashMap(); static { NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/j2ee/application-client", "http://geronimo.apache.org/xml/ns/j2ee/application-client-1.0"); NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/j2ee/application", "http://geronimo.apache.org/xml/ns/j2ee/application-1.0"); NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/deployment", "http://geronimo.apache.org/xml/ns/deployment-1.0"); NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/j2ee/connector", "http://geronimo.apache.org/xml/ns/j2ee/connector-1.0"); NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/deployment/javabean", "http://geronimo.apache.org/xml/ns/deployment/javabean-1.0"); NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/loginconfig", "http://geronimo.apache.org/xml/ns/loginconfig-1.0"); NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/naming", "http://geronimo.apache.org/xml/ns/naming-1.0"); NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/security", "http://geronimo.apache.org/xml/ns/security-1.1"); NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/web", "http://geronimo.apache.org/xml/ns/j2ee/web-1.0"); NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/web/jetty", "http://geronimo.apache.org/xml/ns/j2ee/web/jetty-1.0"); NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/web/jetty/config", "http://geronimo.apache.org/xml/ns/j2ee/web/jetty/config-1.0"); NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/web/tomcat", "http://geronimo.apache.org/xml/ns/j2ee/web/tomcat-1.0"); NAMESPACE_UPDATES.put("http://geronimo.apache.org/xml/ns/web/tomcat/config", "http://geronimo.apache.org/xml/ns/j2ee/web/tomcat/config-1.0"); NAMESPACE_UPDATES.put("http://www.openejb.org/xml/ns/openejb-jar", "http://www.openejb.org/xml/ns/openejb-jar-2.0"); NAMESPACE_UPDATES.put("http://www.openejb.org/xml/ns/pkgen", "http://www.openejb.org/xml/ns/pkgen-2.0"); NAMESPACE_UPDATES.put("http://www.openejb.org/xml/ns/corba-css-config_1_0", "http://www.openejb.org/xml/ns/corba-css-config-2.0"); NAMESPACE_UPDATES.put("http://www.openejb.org/xml/ns/corba-tss-config_1_0", "http://www.openejb.org/xml/ns/corba-tss-config-2.0"); } private XmlBeansUtil() { } public static XmlObject parse(File file) throws IOException, XmlException { ArrayList errors = new ArrayList(); XmlObject parsed = XmlObject.Factory.parse(file, createXmlOptions(errors)); if (errors.size() != 0) { throw new XmlException(errors.toArray().toString()); } return parsed; } public static XmlObject parse(URL url) throws IOException, XmlException { ArrayList errors = new ArrayList(); XmlObject parsed = XmlObject.Factory.parse(url, createXmlOptions(errors)); if (errors.size() != 0) { throw new XmlException(errors.toArray().toString()); } return parsed; } public static XmlObject parse(InputStream is) throws IOException, XmlException { ArrayList errors = new ArrayList(); XmlObject parsed = XmlObject.Factory.parse(is, createXmlOptions(errors)); if (errors.size() != 0) { throw new XmlException(errors.toArray().toString()); } return parsed; } public static XmlObject parse(String xml) throws XmlException { ArrayList errors = new ArrayList(); XmlObject parsed = XmlObject.Factory.parse(xml, createXmlOptions(errors)); if (errors.size() != 0) { throw new XmlException(errors.toArray().toString()); } return parsed; } public static XmlObject parse(Element element) throws XmlException { ArrayList errors = new ArrayList(); XmlObject parsed = XmlObject.Factory.parse(element, createXmlOptions(errors)); if (errors.size() != 0) { throw new XmlException(errors.toArray().toString()); } return parsed; } public static XmlOptions createXmlOptions(Collection errors) { XmlOptions options = new XmlOptions(); options.setLoadLineNumbers(); options.setErrorListener(errors); options.setLoadSubstituteNamespaces(NAMESPACE_UPDATES); return options; } }
47.637931
156
0.690192
2bbcecad74908254372a93dc93cbf0c8082d98e1
1,101
package com.rahulmehra.java8.datetimeapi; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import static java.time.Month.*; public class DateTimeWithZonesExample { public static void main(String[] args) { ZoneId SFO = ZoneId.of("America/Los_Angeles"); ZoneId BOS = ZoneId.of("America/New_York"); LocalDateTime departure = LocalDateTime.of(2014,JUNE,15,22,30); ZonedDateTime departSfo = ZonedDateTime.of(departure, SFO); System.out.println("flight 121 departs from SFO at "+departSfo); ZonedDateTime departBos = departSfo.toOffsetDateTime().atZoneSameInstant(BOS); System.out.println("flight 121 depart time at BOS "+departBos); System.out.println("flight 121 duration: 5 hours 30 minutes"); ZonedDateTime arrivalBOS = departSfo.plusHours(5).plusMinutes(30).toOffsetDateTime().atZoneSameInstant(BOS); System.out.println("flight 121 arrives boston at "+arrivalBOS); ZonedDateTime arrivalSFO = arrivalBOS.toOffsetDateTime().atZoneSameInstant(SFO); System.out.println("flight 121 arrives boston at "+arrivalSFO); } }
32.382353
110
0.763851
740ef85bd9b8a2d05497ebbd23c7aa59b45825a5
635
package havis.net.ui.shared.client.widgets; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.SimplePanel; import havis.net.ui.shared.resourcebundle.ResourceBundle; public class LoadingSpinner extends PopupPanel { public LoadingSpinner() { super(false, true); setStyleName(ResourceBundle.INSTANCE.css().webuiSpinnerOuter()); setGlassEnabled(true); setGlassStyleName(ResourceBundle.INSTANCE.css().webuiSpinnerBackground()); SimplePanel loader = new SimplePanel(); loader.setStyleName(ResourceBundle.INSTANCE.css().webuiSpinnerBounce()); this.add(loader); } }
30.238095
77
0.76378
adbcbfdfe54f45a2f8ac201f6d5d5fc367e91878
2,434
/* * * Copyright (c) 2016 Krupal Shah, Harsh Bhavsar * 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.experiments.core.util; import android.content.Context; import android.graphics.Typeface; import android.support.annotation.Nullable; import com.experiments.core.R; import java.io.File; import java.util.HashMap; import java.util.Map; /** * Author : Krupal Shah * Date : 01-Mar-16 * <p> * handles typeface creation from font files */ public class FontFactory { private static FontFactory instance; private final Map<String, Typeface> mapFonts; //cached map of fonts private FontFactory() { mapFonts = new HashMap<>(); } //singleton public synchronized static FontFactory getInstance() { if (instance == null) { instance = new FontFactory(); } return instance; } /** * returns {@link Typeface} object from given font file * * @param context context. will use application context. so don't worry about memory leak. it won't happend * @param fontFileNameWithExt file name with extension. do not include associated relative path. just need whole file name. * @return typeface */ @Nullable public Typeface getTypeFace(Context context, String fontFileNameWithExt) { Typeface typeface; Context mContext = context.getApplicationContext(); if (!mapFonts.containsKey(fontFileNameWithExt)) { //if map does not contain file name; create typeface and put it in map typeface = Typeface.createFromAsset(mContext.getAssets(), mContext.getString(R.string.fonts_folder_path_without_trailing_separator) + File.separator + fontFileNameWithExt); mapFonts.put(fontFileNameWithExt, typeface); return typeface; } return mapFonts.get(fontFileNameWithExt); //otherwise return cached typeface } }
33.805556
184
0.696385
a9d1f0c0a18396e0bc0429b32a1c264dee24b7c3
858
package com.example; import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.util.Map; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import com.excelbdd.Behavior; import com.excelbdd.TestWizard; class WeekManagerTest { static Stream<Map<String, String>> provideExampleList() throws IOException { String filePath = "src/test/resources/excel.xlsx"; return Behavior.getExampleStream(filePath, "FridayCheck"); } @ParameterizedTest(name = "#{index} - Test with Map : {0}") @MethodSource("provideExampleList") final void test(Map<String, String> mapParams) { TestWizard.showMap(mapParams); String actualAnswer = WeekManager.isFriday(mapParams.get("Day")); assertEquals(mapParams.get("Answer"), actualAnswer); } }
26.8125
77
0.770396
2ecb0f5fe6892b0ba83316b2e6441d4427058f67
1,173
package com.lanking.cloud.domain.yoo.order.fallible; import com.lanking.cloud.sdk.bean.Valueable; /** * 错题打印订单状态 * * @since 3.9.3 * @author <a href="mailto:sikai.wang@elanking.com">sikai.wang</a> * @version 2017年3月21日 */ public enum FallibleQuestionPrintOrderStatus implements Valueable { /** * 未支付 */ NOT_PAY(0), /** * 已支付/后台待处理 */ PAY(1), /** * 打印处理中 */ PRINTING(2), /** * 打印完成 */ PRINT_COMPLETE(3), /** * 已发货 */ DELIVERED(4), /** * 已收货/订单完成 */ COMPLETE(5), /** * 失败 */ FAIL(6), /** * 删除 */ DELETE(7); private int value; FallibleQuestionPrintOrderStatus(int value) { this.value = value; } @Override public int getValue() { return value; } public static FallibleQuestionPrintOrderStatus findByValue(int value) { switch (value) { case 0: return NOT_PAY; case 1: return PAY; case 2: return PRINTING; case 3: return PRINT_COMPLETE; case 4: return DELIVERED; case 5: return COMPLETE; case 6: return FAIL; case 7: return DELETE; default: return NOT_PAY; } } }
13.329545
73
0.570332
62f1faa4f6ee512bb8e8748e4155ad5adc21f535
414
package engine.input; import java.awt.event.KeyEvent; public class MarioHumanKeyboard extends MarioKeyboard { public MarioHumanKeyboard() { register(KeyEvent.VK_LEFT, MarioKey.LEFT); register(KeyEvent.VK_RIGHT, MarioKey.RIGHT); register(KeyEvent.VK_DOWN, MarioKey.DOWN); register(KeyEvent.VK_UP, MarioKey.UP); register(KeyEvent.VK_A, MarioKey.JUMP); register(KeyEvent.VK_S, MarioKey.SPEED); } }
24.352941
55
0.772947
d21e154d47bc22c87926a8cfaf01d994ee5b578c
3,674
package nl.nn.adapterframework.util; import nl.nn.adapterframework.core.Resource; import nl.nn.adapterframework.util.LogUtil; import org.apache.logging.log4j.Logger; import org.junit.Test; import javax.xml.transform.Source; import static org.junit.Assert.assertEquals; public class TransformerPoolTest { protected Logger log = LogUtil.getLogger(this); private String xml = "<root><message active=\"false\">hello</message></root>"; private String xpath = "root/message"; private String expectedXpath = "hello"; private String stylesheetURL = "xml/xsl/active.xsl"; private String expectedStylesheetURL = "<root/>"; @Test public void plainXPath() throws Exception { TransformerPool.clearTransformerPools(); String xpathEvaluatorSource = XmlUtils.createXPathEvaluatorSource(xpath); TransformerPool transformerPool = TransformerPool.getInstance(xpathEvaluatorSource); String result = transformerPool.transform(xml, null); assertEquals(expectedXpath, result); assertEquals(0, TransformerPool.getTransformerPoolsKeys().size()); } @Test public void plainXPathUsingMultiUseSource() throws Exception { TransformerPool.clearTransformerPools(); String xpathEvaluatorSource = XmlUtils.createXPathEvaluatorSource(xpath); TransformerPool transformerPool = TransformerPool.getInstance(xpathEvaluatorSource); Source source = XmlUtils.stringToSource(xml); String result = transformerPool.transform(source); assertEquals(expectedXpath, result); assertEquals(0, TransformerPool.getTransformerPoolsKeys().size()); } @Test public void plainViaUrl() throws Exception { TransformerPool.clearTransformerPools(); Resource resource = Resource.getResource(stylesheetURL); TransformerPool transformerPool = TransformerPool.getInstance(resource); String result = transformerPool.transform(xml, null); result=result.replaceAll("[\n\r]", ""); assertEquals(expectedStylesheetURL, result); assertEquals(0, TransformerPool.getTransformerPoolsKeys().size()); } @Test public void useCachingXpath() throws Exception { TransformerPool.clearTransformerPools(); String xpath = "root/message"; String xpathEvaluatorSource = XmlUtils.createXPathEvaluatorSource(xpath); TransformerPool.getInstance(xpathEvaluatorSource, null, 1, true); assertEquals(1, TransformerPool.getTransformerPoolsKeys().size()); TransformerPool.getInstance(xpathEvaluatorSource, "xyz", 1, true); assertEquals(2, TransformerPool.getTransformerPoolsKeys().size()); TransformerPool.getInstance(xpathEvaluatorSource, null, 2, true); assertEquals(3, TransformerPool.getTransformerPoolsKeys().size()); TransformerPool.getInstance(xpathEvaluatorSource, null, 1, true); assertEquals(3, TransformerPool.getTransformerPoolsKeys().size()); String xpath2 = "root/@message"; TransformerPool.getInstance(XmlUtils.createXPathEvaluatorSource(xpath2), null, 1, true); assertEquals(4, TransformerPool.getTransformerPoolsKeys().size()); } @Test public void useCachingUrl() throws Exception { TransformerPool.clearTransformerPools(); Resource resource = Resource.getResource("xml/xsl/active.xsl"); TransformerPool.getInstance(resource, 1, true); assertEquals(1, TransformerPool.getTransformerPoolsKeys().size()); TransformerPool.getInstance(resource, 2, true); assertEquals(2, TransformerPool.getTransformerPoolsKeys().size()); TransformerPool.getInstance(resource, 1, true); assertEquals(2, TransformerPool.getTransformerPoolsKeys().size()); Resource resource2 = Resource.getResource("xml/xsl/AttributesGetter.xsl"); TransformerPool.getInstance(resource2, 2, true); assertEquals(3, TransformerPool.getTransformerPoolsKeys().size()); } }
41.280899
90
0.790419
a3429f5b3fa7cddb36e98bfcaabd1b907cfb75e1
2,545
package info.itsthesky.disky.skript.events.skript.bot; import ch.njol.skript.Skript; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; import ch.njol.skript.doc.Name; import ch.njol.skript.doc.Since; import ch.njol.skript.lang.util.SimpleEvent; import ch.njol.skript.registrations.EventValues; import ch.njol.skript.util.Getter; import info.itsthesky.disky.tools.Utils; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.events.guild.GuildJoinEvent; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @Name("Bot Join Guild") @Description("Fired when a bot join any guild where the bot is in.") @Examples({"on bot join guild:", "\tsend message \"I'm the better bot ever, made with DiSky by Sky!\" to text channel with id \"750449611302371469\""}) @Since("1.0") public class EventBotJoin extends Event { static { // [seen by [bot] [(named|with name)]%string%] Skript.registerEvent("Bot Join", SimpleEvent.class, EventBotJoin.class, "[discord] bot join (guild|server)") .description("Fired when a bot join any guild where the bot is in.") .examples("on bot join guild:", "\tsend message \"I'm the better bot ever, made with DiSky by Sky!\" to text channel with id \"750449611302371469\"") .since("1.0"); EventValues.registerEventValue(EventBotJoin.class, JDA.class, new Getter<JDA, EventBotJoin>() { @Nullable @Override public JDA get(final @NotNull EventBotJoin event) { return event.getEvent().getJDA(); } }, 0); EventValues.registerEventValue(EventBotJoin.class, Guild.class, new Getter<Guild, EventBotJoin>() { @Nullable @Override public Guild get(final @NotNull EventBotJoin event) { return event.getEvent().getGuild(); } }, 0); } private static final HandlerList HANDLERS = new HandlerList(); private final GuildJoinEvent event; public EventBotJoin( final GuildJoinEvent event) { super(Utils.areEventAsync()); this.event = event; } public GuildJoinEvent getEvent() { return event; } @NotNull @Override public HandlerList getHandlers() { return HANDLERS; } public static HandlerList getHandlerList() { return HANDLERS; } }
33.933333
133
0.66444
4a25265e33442b9ab5891ebeb2e27c556df29fed
3,694
/* * PDF stamper * The PDF Stamper API enables the possibility to add both static and dynamic stamps on existing PDFs. The stamps can consist of one or more barcode, hyperlink, image, line or text elements. The API also supports digital signatures (blue bar), blockchain registrations and filling out forms The flow is generally as follows: 1. Make a configuration containing the stamp information 2. Create a job specifying the desired configuration 3. Add one or more PDF files to the job 4. Start the job for processing 5. Retrieve the processed files Full API Documentation: https://docs.sphereon.com/api/pdf-stamper/1.0 Interactive testing: A web based test console is available in the Sphereon API Store at https://store.sphereon.com * * OpenAPI spec version: 1.0 * Contact: dev@sphereon.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.sphereon.sdk.pdf.stamper.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * A Red Green Blue color value combination */ @ApiModel(description = "A Red Green Blue color value combination") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2021-04-08T13:37:39.498+02:00") public class RGBValue { @SerializedName("b") private Integer b = null; @SerializedName("r") private Integer r = null; @SerializedName("g") private Integer g = null; public RGBValue b(Integer b) { this.b = b; return this; } /** * Get b * @return b **/ @ApiModelProperty(required = true, value = "") public Integer getB() { return b; } public void setB(Integer b) { this.b = b; } public RGBValue r(Integer r) { this.r = r; return this; } /** * Get r * @return r **/ @ApiModelProperty(required = true, value = "") public Integer getR() { return r; } public void setR(Integer r) { this.r = r; } public RGBValue g(Integer g) { this.g = g; return this; } /** * Get g * @return g **/ @ApiModelProperty(required = true, value = "") public Integer getG() { return g; } public void setG(Integer g) { this.g = g; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RGBValue rgBValue = (RGBValue) o; return Objects.equals(this.b, rgBValue.b) && Objects.equals(this.r, rgBValue.r) && Objects.equals(this.g, rgBValue.g); } @Override public int hashCode() { return Objects.hash(b, r, g); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class RGBValue {\n"); sb.append(" b: ").append(toIndentedString(b)).append("\n"); sb.append(" r: ").append(toIndentedString(r)).append("\n"); sb.append(" g: ").append(toIndentedString(g)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
26.198582
735
0.661343
73f79a80bd45e774a5176122676cc1d6f5b9735d
4,165
package com.connectedparking.www; import com.sun.mail.dsn.Report; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; public class Mail { private static WebElement element = null; private static WebDriver driver = null; public static int result = 1; //set driver public Mail(WebDriver driver) { this.driver = driver; } public static void send_Report(String test) { // Create object of Property file Properties props = new Properties(); // this will set host of server- you can change based on your requirement props.put("mail.smtp.host", "smtp.gmail.com"); // set the port of socket factory props.put("mail.smtp.socketFactory.port", "465"); // set socket factory props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); // set the authentication to true props.put("mail.smtp.auth", "true"); // set the port of SMTP server props.put("mail.smtp.port", "465"); // This will handle the complete authentication Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("connectedcarsteam3", "Cars1234"); } }); try { // Create object of SimpleDateFormat class and decide the format DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy "); //get current date time with Date() Date date = new Date(); // Now format the date String date1= dateFormat.format(date); // Create object of MimeMessage class Message message = new MimeMessage(session); // Set the from address message.setFrom(new InternetAddress("connectedcarsteam3@gmail.com")); // Set the recipient address message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("gilad.robin@sap.com")); // message.setRecipients(Message.RecipientType.CC,InternetAddress.parse("inbal.motena@sap.com")); // Add the subject link message.setSubject("Automation Report for "+ date1); // Create object to add multimedia type content BodyPart messageBodyPart1 = new MimeBodyPart(); // Set the body of email messageBodyPart1.setText("Hi! " + " Pleas fined the attached report for the "+test+" test.The automated test got performed on "+date1); // Create another object to add another content MimeBodyPart messageBodyPart2 = new MimeBodyPart(); // Mention the file which you want to send String filename = "//Iltlvp01//Public//Automation//Reports//"+test+".html"; // Create data source and pass the filename DataSource source = new FileDataSource(filename); // set the handler messageBodyPart2.setDataHandler(new DataHandler(source)); // set the file messageBodyPart2.setFileName(filename); // Create object of MimeMultipart class Multipart multipart = new MimeMultipart(); // add body part 1 multipart.addBodyPart(messageBodyPart2); // add body part 2 multipart.addBodyPart(messageBodyPart1); // set the content message.setContent(multipart); // finally send the email Transport.send(message); System.out.println("=====Email Sent====="); } catch (MessagingException e) { throw new RuntimeException(e); } } }
33.055556
124
0.607203
39429d99ef1b377c147cf832fe120fcce5055531
6,867
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.ajapps.climatecars.slidingtabscolors; public final class R { public static final class attr { /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int metaButtonBarButtonStyle=0x7f010001; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int metaButtonBarStyle=0x7f010000; } public static final class color { public static final int black_overlay=0x7f040000; } public static final class dimen { public static final int activity_horizontal_margin=0x7f050000; public static final int activity_vertical_margin=0x7f050001; public static final int horizontal_page_margin=0x7f050002; public static final int margin_huge=0x7f050003; public static final int margin_large=0x7f050004; public static final int margin_medium=0x7f050005; public static final int margin_small=0x7f050006; public static final int margin_tiny=0x7f050007; public static final int vertical_page_margin=0x7f050008; } public static final class drawable { public static final int android=0x7f020000; public static final int androidlogo=0x7f020001; public static final int androidlogo23=0x7f020002; public static final int dos=0x7f020003; public static final int ic_launcher=0x7f020004; public static final int ios7=0x7f020005; public static final int ios8=0x7f020006; public static final int tux=0x7f020007; public static final int windows=0x7f020008; } public static final class id { public static final int button=0x7f090007; public static final int imageButton=0x7f090005; public static final int imageView=0x7f090004; public static final int imageView2=0x7f090009; public static final int imageView3=0x7f09000c; public static final int item_indicator_color=0x7f09000b; public static final int item_title=0x7f09000a; public static final int menu_toggle_log=0x7f09000d; public static final int pager=0x7f090001; public static final int sample_content_fragment=0x7f090002; public static final int sample_main_layout=0x7f090000; public static final int sliding_tabs=0x7f090008; public static final int textView=0x7f090003; public static final int viewpager=0x7f090006; } public static final class layout { public static final int activity_main=0x7f030000; public static final int activity_slide_tab=0x7f030001; public static final int android_frag=0x7f030002; public static final int fragment_dos=0x7f030003; public static final int fragment_linux=0x7f030004; public static final int fragment_sample=0x7f030005; public static final int ios_frag=0x7f030006; public static final int pager_item=0x7f030007; public static final int windows_frag=0x7f030008; } public static final class menu { public static final int main=0x7f080000; } public static final class string { public static final int action_settings=0x7f060000; public static final int app_name=0x7f060001; public static final int hello_world=0x7f060002; public static final int tab_android=0x7f060003; public static final int tab_dos=0x7f060004; public static final int tab_linux=0x7f060005; public static final int tab_next=0x7f060006; public static final int tab_osx=0x7f060007; public static final int tab_windows=0x7f060008; public static final int title_activity_slide_tab=0x7f060009; } public static final class style { public static final int AppTheme=0x7f070000; public static final int CustomActionBarTheme=0x7f070001; public static final int MyActionBar=0x7f070002; public static final int Theme_Base=0x7f070006; public static final int Widget=0x7f070003; public static final int Widget_SampleMessage=0x7f070004; public static final int Widget_SampleMessageTile=0x7f070005; } public static final class styleable { /** Attributes that can be used with a ButtonBarContainerTheme. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #ButtonBarContainerTheme_metaButtonBarButtonStyle com.ajapps.climatecars.slidingtabscolors:metaButtonBarButtonStyle}</code></td><td></td></tr> <tr><td><code>{@link #ButtonBarContainerTheme_metaButtonBarStyle com.ajapps.climatecars.slidingtabscolors:metaButtonBarStyle}</code></td><td></td></tr> </table> @see #ButtonBarContainerTheme_metaButtonBarButtonStyle @see #ButtonBarContainerTheme_metaButtonBarStyle */ public static final int[] ButtonBarContainerTheme = { 0x7f010000, 0x7f010001 }; /** <p>This symbol is the offset where the {@link com.ajapps.climatecars.slidingtabscolors.R.attr#metaButtonBarButtonStyle} attribute's value can be found in the {@link #ButtonBarContainerTheme} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.ajapps.climatecars.slidingtabscolors:metaButtonBarButtonStyle */ public static final int ButtonBarContainerTheme_metaButtonBarButtonStyle = 1; /** <p>This symbol is the offset where the {@link com.ajapps.climatecars.slidingtabscolors.R.attr#metaButtonBarStyle} attribute's value can be found in the {@link #ButtonBarContainerTheme} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.ajapps.climatecars.slidingtabscolors:metaButtonBarStyle */ public static final int ButtonBarContainerTheme_metaButtonBarStyle = 0; }; }
50.866667
174
0.692588
439159bec72e272898418b63cd4518a03e569a4a
234
package com.blog.sample.repositories; import org.springframework.data.jpa.repository.JpaRepository; import com.blog.sample.models.User; public interface UserJpaRepository extends JpaRepository<User, Long>, UserCustomRepository { }
26
92
0.833333
0b58196381d96deac97b34585a6fe3713b2e82f2
1,539
/* * Copyright (c) 2008-2016, GigaSpaces Technologies, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gigaspaces.server.filter; import com.gigaspaces.internal.metadata.ITypeDesc; import com.gigaspaces.internal.server.space.events.NotifyContext; import com.gigaspaces.internal.server.storage.IEntryHolder; import com.j_spaces.core.filters.entry.SpaceFilterEntryImpl; /** * NotifyEvent is the object passed to filter when notify occurs * * @author anna * @since 7.0 */ @com.gigaspaces.api.InternalApi public class NotifyEvent extends SpaceFilterEntryImpl { private static final long serialVersionUID = 9205896190317891054L; private final NotifyContext _notifyContext; /** * @param holder * @param tte */ public NotifyEvent(IEntryHolder holder, ITypeDesc tte, NotifyContext notifyContext) { super(holder, tte); _notifyContext = notifyContext; } public NotifyContext getNotifyContext() { return _notifyContext; } }
31.408163
89
0.74334
daf11fba0b11cf7168169f6c2c0284e8faf7918a
2,476
package com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius; import org.junit.runner.RunWith; import org.junit.runners.Suite; import com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius.read.BulkAdGroupRadiusCriterionReadAdGroupNameTest; import com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius.read.BulkAdGroupRadiusCriterionReadBidAdjustmentTest; import com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius.read.BulkAdGroupRadiusCriterionReadCampaignNameTest; import com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius.read.BulkAdGroupRadiusCriterionReadCashbackAdjustmentTest; import com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius.read.BulkAdGroupRadiusCriterionReadIdTest; import com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius.read.BulkAdGroupRadiusCriterionReadLatitudeTest; import com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius.read.BulkAdGroupRadiusCriterionReadLongitudeTest; import com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius.read.BulkAdGroupRadiusCriterionReadNameTest; import com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius.read.BulkAdGroupRadiusCriterionReadParentIdTest; import com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius.read.BulkAdGroupRadiusCriterionReadRadiusTest; import com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius.read.BulkAdGroupRadiusCriterionReadRadiusUnitTest; import com.microsoft.bingads.v13.api.test.entities.criterions.adgroup.radius.read.BulkAdGroupRadiusCriterionReadStatusTest; @RunWith(Suite.class) @Suite.SuiteClasses({ BulkAdGroupRadiusCriterionReadIdTest.class, BulkAdGroupRadiusCriterionReadParentIdTest.class, BulkAdGroupRadiusCriterionReadStatusTest.class, BulkAdGroupRadiusCriterionReadNameTest.class, BulkAdGroupRadiusCriterionReadAdGroupNameTest.class, BulkAdGroupRadiusCriterionReadCampaignNameTest.class, BulkAdGroupRadiusCriterionReadBidAdjustmentTest.class, BulkAdGroupRadiusCriterionReadLatitudeTest.class, BulkAdGroupRadiusCriterionReadLongitudeTest.class, BulkAdGroupRadiusCriterionReadRadiusTest.class, BulkAdGroupRadiusCriterionReadRadiusUnitTest.class, BulkAdGroupRadiusCriterionReadCashbackAdjustmentTest.class }) public class BulkAdGroupRadiusCriterionReadTests { }
68.777778
135
0.860258
ac580318728b3a74798240b2a8860ca06c77e373
5,126
import java.util.*; public class work { public static int seconds = 0; public static boolean full = false; public static int intensity; public static String foc; public static int min; public static Workout workout; public static ArrayList <String> exercise; public static void main(String [] args){ Scanner scan = new Scanner(System.in); System.out.println("Upper, Core, Lower, or Full Body?"); foc = scan.nextLine(); if(foc.equalsIgnoreCase("full body")){ full = true; System.out.println("Would you like to emphasize any one specific group? (Yes/No)"); String ans = scan.next(); if(ans.equalsIgnoreCase("Yes")){ System.out.println("Which one? Ex: Core or Upper or Lower"); foc = scan.next(); } if(ans.equalsIgnoreCase("No")){ foc = "None"; } } System.out.println("On a scale of 1 to 3, how intense do you want to workout?"); intensity = scan.nextInt(); System.out.println("10 minutes, 15 minutes, 20 minutes? (Example: 2 = 15min)"); int min = scan.nextInt(); workout = new Workout(intensity, foc, full, min); exercise = workout.sort(); //for(int i = 0; i<exercise.size();i++){ // System.out.println(exercise.get(i)); //} for(int i = 0; i<exercise.size(); i++){ select(exercise.get(i)); } System.out.println(workout.duration(exercise.get(exercise.size()-1))); } public static void select(String word){ if(word.equals("core")){ Core(); } if(word.equals("upper")){ Upper(); } if(word.equals("lower")){ Leg(); } } public static void Core(){ int b = (int)(5*Math.random()+1); int sec = workout.intensity(); if(b==1){ System.out.println("Situps for "+sec+" seconds"); System.out.println("Flutter Kicks for "+sec+" seconds"); System.out.println("Russian Twists for "+sec+" seconds"); seconds+=3*sec; } if(b==2){ System.out.println("Leg lifts for "+sec+" seconds"); System.out.println("Windshield Wipers for "+sec+" seconds"); System.out.println("Situps for "+sec+" seconds"); seconds+=3*sec; } if(b==3){ System.out.println("Plank for "+sec+" seconds"); System.out.println("Crunches for "+sec+" seconds"); System.out.println("Bicycle for "+sec+" seconds"); seconds+=3*sec; } if(b==4){ System.out.println("Scissors for "+sec+" seconds"); System.out.println("Left side plank for "+sec+" seconds"); System.out.println("Right side plank for "+sec+" seconds"); seconds+=3*sec; } if(b==5){ System.out.println("Mountain Climbers for "+sec+" seconds"); System.out.println("Plank Arm Raises for "+sec+" seconds"); System.out.println("Reverse Crunches for "+sec+" seconds"); seconds+=3*sec; } } public static void Upper(){ int c = (int)(4*Math.random()+1); int sec = workout.intensity(); if(c==1){ System.out.println("Pushups for "+sec+" seconds"); System.out.println("Tricep dips for "+sec+" seconds"); System.out.println("Diamond pushups for "+sec+" seconds"); seconds+=3*sec; } if(c==2){ System.out.println("Burpees for "+sec+" seconds"); System.out.println("Dive bombers for "+sec+" seconds"); System.out.println("Mountain climbers for "+sec+" seconds"); seconds+=3*sec; } if(c==3){ System.out.println("Wide Grip Pushups for "+sec+" seconds"); System.out.println("Arm Rotations for "+sec+" seconds"); seconds+=2*sec; } if(c==4){ System.out.println("Tricep-ups for "+sec+" seconds"); System.out.println("Pushups for "+sec+" seconds"); seconds+=2*sec; } } public static void Leg(){ int a = (int)(3*Math.random()+1); int sec = workout.intensity(); if(a==1){ System.out.println("Star jumps for "+sec+" seconds"); System.out.println("Squats for "+sec+" seconds"); System.out.println("Wall Sit for "+sec+" seconds"); seconds+=3*sec; } if(a==2){ System.out.println("Lunges for "+sec+" seconds"); System.out.println("Squats for "+sec+" seconds"); System.out.println("Calf Raises for "+sec+" seconds"); seconds+=3*sec; } if(a==3){ System.out.println("Squat jumps for "+sec+" seconds"); System.out.println("Bench lunge for "+sec+" seconds"); System.out.println("Step ups for "+sec+" seconds"); seconds+=3*sec; } } }
36.614286
95
0.522435
403b8a594615b2436b7609e483f846c691b802f7
2,211
package net.chwthewke.hamcrest.equivalence; import static net.chwthewke.hamcrest.equivalence.EquivalenceClassMatchers.equates; import static net.chwthewke.hamcrest.equivalence.EquivalenceClassMatchers.separates; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.Test; public class IdentityEquivalenceTest { @Test public void equatesWithSameReference( ) throws Exception { // Setup final V v = new V( 42 ); final IdentityEquivalence<V> equivalence = new IdentityEquivalence<V>( ); // Exercise // Verify assertThat( equivalence, equates( v, v ) ); } @Test public void differentiatesJustEqualObjects( ) throws Exception { // Setup final V v1 = new V( 42 ); final V v2 = new V( 42 ); final IdentityEquivalence<V> equivalence = new IdentityEquivalence<V>( ); // Exercise // Verify assertThat( equivalence, separates( v1, v2 ) ); } @Test public void identitySupportsNulls( ) throws Exception { // Setup // Exercise final IdentityEquivalence<V> equivalence = new IdentityEquivalence<V>( ); // Verify assertThat( equivalence, EquivalenceClassMatchers.<V>equates( null, null ) ); assertThat( equivalence, EquivalenceClassMatchers.<V>separates( null, new V( 12 ) ) ); } private static class V { public V( final int value ) { this.value = value; } @Override public int hashCode( ) { final int prime = 31; int result = 1; result = prime * result + value; return result; } @Override public boolean equals( final Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass( ) != obj.getClass( ) ) return false; final V other = (V) obj; if ( value != other.value ) return false; return true; } private final int value; } }
29.878378
95
0.558571
43af5a746723bc3317e29d645b430fb5cf21e461
5,185
/* * 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 ch.cscs.keycloak.broker.saml.mappers; import org.keycloak.broker.provider.AbstractIdentityProviderMapper; import org.keycloak.broker.provider.BrokeredIdentityContext; import org.keycloak.broker.saml.SAMLEndpoint; import org.keycloak.broker.saml.SAMLIdentityProviderFactory; import org.keycloak.dom.saml.v2.assertion.AssertionType; import org.keycloak.dom.saml.v2.assertion.AttributeStatementType; import org.keycloak.dom.saml.v2.assertion.AttributeType; import org.keycloak.models.IdentityProviderMapperModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import org.keycloak.provider.ProviderConfigProperty; import java.util.ArrayList; import java.util.List; public class IDMapper extends AbstractIdentityProviderMapper { public static final String[] COMPATIBLE_PROVIDERS = {SAMLIdentityProviderFactory.PROVIDER_ID}; private static final List<ProviderConfigProperty> CONFIG_PROPERTIES = new ArrayList<ProviderConfigProperty>(); public static final String USER_ID_ATTRIBUTE = "user-id-attribute"; public static final String USER_NAME_ATTRIBUTE = "user-name-attribute"; static { ProviderConfigProperty property; property = new ProviderConfigProperty(); property.setName(USER_ID_ATTRIBUTE); property.setLabel("User ID Attribute"); property.setHelpText("SAML attribute to use as the external user ID"); property.setType(ProviderConfigProperty.STRING_TYPE); property.setDefaultValue("uid"); CONFIG_PROPERTIES.add(property); property = new ProviderConfigProperty(); property.setName(USER_NAME_ATTRIBUTE); property.setLabel("Username Attribute"); property.setHelpText("SAML attribute to use as the external username"); property.setType(ProviderConfigProperty.STRING_TYPE); property.setDefaultValue("uid"); CONFIG_PROPERTIES.add(property); } public static final String PROVIDER_ID = "saml-id-mapper"; @Override public List<ProviderConfigProperty> getConfigProperties() { return CONFIG_PROPERTIES; } @Override public String getId() { return PROVIDER_ID; } @Override public String[] getCompatibleProviders() { return COMPATIBLE_PROVIDERS; } @Override public String getDisplayCategory() { return "Preprocessor"; } @Override public String getDisplayType() { return "SAML ID Mapper"; } @Override public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) { } @Override public void preprocessFederatedIdentity(KeycloakSession session, RealmModel realm, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) { AssertionType assertion = (AssertionType)context.getContextData().get(SAMLEndpoint.SAML_ASSERTION); String userIDAttribute = mapperModel.getConfig().get(USER_ID_ATTRIBUTE); String usernameAttribute = mapperModel.getConfig().get(USER_NAME_ATTRIBUTE); if (userIDAttribute != null && !userIDAttribute.isEmpty()) { String userID = getAttribute(assertion, userIDAttribute); if (userID != null) { context.setId(userID); } } if (usernameAttribute != null && !usernameAttribute.isEmpty()) { String username = getAttribute(assertion, usernameAttribute); if (username != null) { context.setUsername(username); context.setModelUsername(username); } } } @Override public String getHelpText() { return "Use SAML attributes to determine external username and ID"; } private String getAttribute(AssertionType assertion, String name) { String value = null; for (AttributeStatementType statement : assertion.getAttributeStatements()) { for (AttributeStatementType.ASTChoiceType choice : statement.getAttributes()) { AttributeType attr = choice.getAttribute(); if (name.equals(attr.getName()) || name.equals(attr.getFriendlyName())) { List<Object> attributeValue = attr.getAttributeValue(); if (attributeValue != null && !attributeValue.isEmpty()) { value = attributeValue.get(0).toString(); } break; } } } return value; } }
35.272109
169
0.696818
0099d626d66ca2fb95fe8a580f4b917cc2f48965
1,377
package yao.usage.compare.example; public class Student implements Comparable<Student> { private String id; private String name; private int age; public Student(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (obj.getClass() != this.getClass()) { return false; } Student student = (Student) obj; if (!student.getName().equals(getName())) { return false; } return true; } public int compareTo(Student student) { return this.age - student.age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", age=" + age + '}'; } }
18.608108
53
0.477124
78c7883bbc1e5b73ce381821e48827aceb1a7a83
236
package com.training.patterns.src.visitor; public interface SalesVisitor { public void visit(final Prospect prospect); public void visit(final Customer customer); public void visit(final RDManager prospect); }
21.454545
49
0.728814
c676d2eeb8f3f48882fe824283cd2f936633ee73
3,789
/* * * 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.airavata.test.suite.workflowtracking.tests.impl.publish; import java.io.IOException; import org.apache.airavata.workflow.tracking.impl.publish.WSMPublisher; import org.apache.axis2.addressing.EndpointReference; import org.junit.*; public class TestWSMPublisher { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @org.junit.Test public final void testWSMPublisherConstructor1() { EndpointReference brokerEpr = new EndpointReference("http://invalid/broker/address"); WSMPublisher publisher = new WSMPublisher(10, false, brokerEpr); } @org.junit.Test public final void testWSMPublisherConstructor2() { try { WSMPublisher publisher = new WSMPublisher(10, false, "http://invalid/broker/address", "TestTopic1"); } catch (IOException e) { // fail("Test failed"); } } @org.junit.Test public final void testWSMPublisherConstructor3() { try { EndpointReference epr = new EndpointReference("http://invalid/broker/address"); WSMPublisher publisher = new WSMPublisher(10, false, epr.getAddress()); } catch (Exception e) { e.printStackTrace(); // fail(); } } @org.junit.Test public final void testWSMPublisherConstructor4() { try { EndpointReference epr = new EndpointReference("http://invalid/broker/address"); // According to addressing format. String eprFormat = "<BrokerEPR><wsa:Address xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">%s</wsa:Address></BrokerEPR>"; String str = String.format(eprFormat, "http://invalid/broker/address"); WSMPublisher publisher = new WSMPublisher(10, false, str, true); } catch (Exception e) { e.printStackTrace(); // fail(); } } @org.junit.Test public final void testWSMPublisherConstructor5() { // try { // // EndpointReference epr = new EndpointReference( // "http://invalid/broker/address"); // // AnnotationProps annotationProps = AnnotationProps.newProps( // AnnotationConsts.ExperimentID, "TestexperId1"); // annotationProps.set(AnnotationConsts.ServiceLocation, // "testServiceAddress"); // // ConstructorProps props = ConstructorProps.newProps(); // props.set(ConstructorConsts.BROKER_EPR, epr.getAddress()); // props.set(ConstructorConsts.ENABLE_ASYNC_PUBLISH, "false"); // props.set(ConstructorConsts.ENABLE_BATCH_PROVENANCE, "false"); // props.set(ConstructorConsts.ANNOTATIONS, annotationProps); // // Notifier notifier = NotifierFactory.createGenericNotifier(); // // } catch (Exception e) { // e.printStackTrace(); // fail(); // } } }
31.575
137
0.651623
98e56b47674afca38f1628c84e6568dfaa1b16e8
1,139
package com.bitwait.bitrade.service; import com.bitwait.bitrade.constant.BooleanEnum; import com.bitwait.bitrade.constant.PromotionRewardType; import com.bitwait.bitrade.service.Base.TopBaseService; import com.bitwait.bitrade.dao.RewardPromotionSettingDao; import com.bitwait.bitrade.entity.RewardPromotionSetting; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author ragan QQ:2098401701 E-mail:bitwait@qq.com * @date 2020年03月08日 */ @Service public class RewardPromotionSettingService extends TopBaseService<RewardPromotionSetting,RewardPromotionSettingDao> { @Override @Autowired public void setDao(RewardPromotionSettingDao dao) { super.setDao(dao); } public RewardPromotionSetting findByType(PromotionRewardType type){ return dao.findByStatusAndType(BooleanEnum.IS_TRUE, type); } @Override public RewardPromotionSetting save(RewardPromotionSetting setting){ return dao.save(setting); } public void deletes(long[] ids){ for(long id : ids){ delete(id); } } }
27.780488
118
0.753292
3e8ba5d5e3e68cfcd87f08aa6996429057f971d0
693
package io.improbable.keanu.vertices.generic.nonprobabilistic.operators.binary; import io.improbable.keanu.vertices.Vertex; import io.improbable.keanu.vertices.generic.nonprobabilistic.NonProbabilistic; public abstract class BinaryOpVertex<A, B, C> extends NonProbabilistic<C> { protected final Vertex<A> a; protected final Vertex<B> b; public BinaryOpVertex(Vertex<A> a, Vertex<B> b) { this.a = a; this.b = b; setParents(a, b); } @Override public C sample() { return op(a.sample(), b.sample()); } public C getDerivedValue() { return op(a.getValue(), b.getValue()); } protected abstract C op(A a, B b); }
23.896552
79
0.658009
3e46ae60a3963f137b03ed330d327bd0cfa6a23c
1,563
package com.cpucode.pattern.behavior.delegate.mvc; import com.cpucode.pattern.behavior.delegate.mvc.controllers.MemberController; import com.cpucode.pattern.behavior.delegate.mvc.controllers.OrderController; import com.cpucode.pattern.behavior.delegate.mvc.controllers.SystemController; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 相当于是项目经理的角色 * * @author : cpucode * @date : 2021/5/30 * @time : 21:08 * @github : https://github.com/CPU-Code * @csdn : https://blog.csdn.net/qq_44226094 */ public class DispatcherServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { doDispatch(req, resp); } catch (Exception e) { e.printStackTrace(); } } private void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception{ String uri = request.getRequestURI(); String mid = request.getParameter("mid"); if ("getMemberById".equals(uri)){ new MemberController().getMemberById(mid); }else if("getOrderById".equals(uri)){ new OrderController().getOrderById(mid); }else if("logout".equals(uri)){ new SystemController().logout(); }else { response.getWriter().write("404 not found!!"); } } }
31.26
103
0.6865
e500f63427e772f6fdc57ad72185d756ab5b1b7e
644
package com.redislabs.lettusearch.aggregate.reducer; import static com.redislabs.lettusearch.protocol.CommandKeyword.QUANTILE; import com.redislabs.lettusearch.protocol.RediSearchCommandArgs; import lombok.Builder; import lombok.Getter; import lombok.Setter; public @Getter @Setter class Quantile extends AbstractPropertyReducer { private double quantile; @Builder private Quantile(String as, String property) { super(as, property); } @Override protected <K, V> void buildFunction(RediSearchCommandArgs<K, V> args, String property) { args.add(QUANTILE); args.add(2); args.addProperty(property); args.add(quantile); } }
22.206897
89
0.781056
2e56976baa4efc1b95249be087b230bbe8d5d396
6,939
/** * Copyright 2014 Tampere University of Technology, Pori Department * * 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 core.tut.pori.context; import org.apache.log4j.Logger; import org.springframework.security.core.session.SessionInformation; import org.springframework.security.core.session.SessionRegistry; import core.tut.pori.users.UserIdentity; /** * Accessible interface to active Sessions within the web application (service) context. * * This class can be used to register new sessions and retrieve information for a particular session. * The session information is provided for all services, though the session management is generally handled internally and modifying the active sessions may cause undefined behavior. * * One should not initialize this handler directly, as an instantiated version is available from ServiceInitializer. */ public class SessionHandler { private static final Logger LOGGER = Logger.getLogger(SessionHandler.class); private static SessionHandler _handler = new SessionHandler(); private SessionHandlerPrivate _handlerPrivate = null; /** * * @param handler */ private static synchronized void setHandler(SessionHandlerPrivate handler){ if(handler == null){ LOGGER.debug("Removing handler..."); }else if(_handler._handlerPrivate != null){ LOGGER.warn("Replacing previous handler..."); } _handler.setHandlerPrivate(handler); } /** * * @return the session handler */ public static SessionHandler getSessionHandler(){ return _handler; } /** * */ private SessionHandler(){ // nothing needed } /** * @param sessionId * @return session information * @see org.springframework.security.core.session.SessionRegistry#getSessionInformation(java.lang.String) */ public SessionInformation getSessionInformation(String sessionId) { if(_handlerPrivate == null){ LOGGER.debug("Session registry not available."); return null; }else{ LOGGER.debug("Retrieving session information for sessionId: "+sessionId); return _handlerPrivate.getSessionRegistry().getSessionInformation(sessionId); // in principle we should synchronize and check if registry is available, but in practice it will never NOT be available } } /** * @param sessionId * @param userId * @see org.springframework.security.core.session.SessionRegistry#registerNewSession(java.lang.String, java.lang.Object) * @throws IllegalStateException if registry is not available */ public void registerNewSession(String sessionId, UserIdentity userId) throws IllegalStateException{ if(_handlerPrivate == null){ throw new IllegalStateException("Session registry not available."); } LOGGER.debug("Registering new session for sessionId: "+sessionId+", userId: "+userId.getUserId()); _handlerPrivate.getSessionRegistry().registerNewSession(sessionId, userId); // in principle we should synchronize and check if registry is available, but in practice it will never NOT be available } /** * This is essentially the same as calling LoginHandler.authentice() and registerNewSession() * * @param sessionId * @param userId * @throws IllegalStateException */ public void registerAndAuthenticate(String sessionId, UserIdentity userId) throws IllegalStateException{ LoginHandler.authenticate(userId); registerNewSession(sessionId, userId); } /** * @param sessionId * @see org.springframework.security.core.session.SessionRegistry#removeSessionInformation(java.lang.String) */ public void removeSessionInformation(String sessionId) { if(_handlerPrivate == null){ LOGGER.debug("Session registry not available."); }else{ LOGGER.debug("Removing session information for sessionId: "+sessionId); _handlerPrivate.getSessionRegistry().removeSessionInformation(sessionId); // in principle we should synchronize and check if registry is available, but in practice it will never NOT be available } } /** * Note: this is NOT synchronized, which means that it may be possible for the user to re-login whilst the operation is in progress, if this is called for user account removal, * remember to FIRST remove the account to make sure user cannot re-login * * @param userId */ public void removeSessionInformation(UserIdentity userId){ if(_handlerPrivate == null){ // in principle we should synchronize and check if registry is available, but in practice it will never NOT be available LOGGER.debug("Session registry not available."); }else{ LOGGER.debug("Removing session information for userId: "+userId.getUserId()); SessionRegistry registry = _handlerPrivate.getSessionRegistry(); for(Object principal : registry.getAllPrincipals()){ // check all principals, note that simply asking for all sessions for the given userId object (principal) may not work as there might be slight differences between the passed object and the one known by the system, which may fool the equals check if(principal.getClass() != UserIdentity.class){ continue; } UserIdentity pIdentity = (UserIdentity) principal; if(UserIdentity.equals(userId, (UserIdentity) principal)){ for(SessionInformation sessionInformation : registry.getAllSessions(pIdentity, true)){ _handlerPrivate.getSessionRegistry().removeSessionInformation(sessionInformation.getSessionId()); } // for session information } // if equals } // for } // else } /** * @param handlerPrivate the handlerPrivate to set */ private void setHandlerPrivate(SessionHandlerPrivate handlerPrivate) { _handlerPrivate = handlerPrivate; } /** * Private instance of session handler. * * Created as a bean. */ private static class SessionHandlerPrivate{ private SessionRegistry _sessionRegistry = null; /** * * @param sessionRegistry */ @SuppressWarnings("unused") public SessionHandlerPrivate(SessionRegistry sessionRegistry){ _sessionRegistry = sessionRegistry; } /** * Called by bean initialization */ @SuppressWarnings("unused") public void initialized(){ LOGGER.debug("Initialized."); setHandler(this); } /** * Called when bean is destroyed */ @SuppressWarnings("unused") public void destroyed(){ LOGGER.debug("Destroyed."); setHandler(null); } /** * @return the sessionRegistry */ public SessionRegistry getSessionRegistry() { return _sessionRegistry; } } // class SessionHandlerPrivate }
35.584615
302
0.749388
48b66cc976b47143e86afca44cbedbf24f1e9683
753
package org.firstinspires.ftc.teamcode.Recording; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.util.ElapsedTime; public class RecordingThread extends Thread { private HardwareMap map; private BlackBox.Recorder recorder; private ElapsedTime recordTimer; public RecordingThread(BlackBox.Recorder recorder, HardwareMap map) { this.map = map; this.recorder = recorder; } public void run() { if (recordTimer == null) { recordTimer = new ElapsedTime(); recordTimer.reset(); } try { this.recorder.recordAllDevices(recordTimer.time()); } catch (Exception e) { e.printStackTrace(); } } }
25.965517
73
0.645418
b4275e6a338eb92e6b811c82d5669140880d86b0
982
package conditions; import gameEngine.environments.RuntimeEnvironment; import units.Unit; public class CheckAttributeCondition implements ICondition{ private String myAttributeToCheck; private double myLowerBound; private double myUpperBound; public CheckAttributeCondition(String attribute, double lower, double upper){ myAttributeToCheck = attribute; myLowerBound = lower; myUpperBound = upper; } @Override public boolean checkCondition(Unit actor,RuntimeEnvironment re) { // TODO Implement storing attributes in a map in Unit double currentValue = actor.getAttribute(myAttributeToCheck); if (currentValue >= myLowerBound && currentValue <= myUpperBound){ return actor.getStringAttribute("Type").equals("Tower"); } return !actor.getStringAttribute("Type").equals("Tower"); } public CheckAttributeCondition clone(){ CheckAttributeCondition cac = new CheckAttributeCondition(myAttributeToCheck,myLowerBound,myUpperBound); return cac; } }
28.882353
106
0.788187
4da8a6e504223045a310a8d63ca856fad736c3a3
1,824
package uk.ac.ebi.quickgo.ontology.service.converter; import uk.ac.ebi.quickgo.common.converter.FlatFieldBuilder; import uk.ac.ebi.quickgo.common.converter.FlatFieldLeaf; import uk.ac.ebi.quickgo.ontology.model.OBOTerm; import java.util.Optional; import org.junit.Before; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * Tests the behaviour of the {@link CreditsFieldConverter} class. */ public class CreditsFieldConverterTest { private CreditsFieldConverter converter; @Before public void setUp() throws Exception { converter = new CreditsFieldConverter(); } @Test public void convertsValidTextBasedCredit() throws Exception { String code = "BHF"; String url = "http://www.ucl.ac.uk/cardiovasculargeneontology/"; String creditText = createCreditText(code, url); Optional<OBOTerm.Credit> expectedCreditOpt = converter.apply(creditText); assertThat(expectedCreditOpt.isPresent(), is(true)); OBOTerm.Credit expectedCredit = expectedCreditOpt.get(); assertThat(expectedCredit.code, is(code)); assertThat(expectedCredit.url, is(url)); } @Test public void returnsEmptyOptionalWhenTextBasedCreditHasWrongNumberOfFields() throws Exception { String wrongTextFormatCredit = "Wrong format"; Optional<OBOTerm.Credit> expectedCreditOpt = converter.apply(wrongTextFormatCredit); assertThat(expectedCreditOpt.isPresent(), is(false)); } private String createCreditText(String code, String url) { return FlatFieldBuilder.newFlatField() .addField(FlatFieldLeaf.newFlatFieldLeaf(code)) .addField(FlatFieldLeaf.newFlatFieldLeaf(url)) .buildString(); } }
32
98
0.718202
574d4ef1bf0ea3ca88b4abeff4cd04bf699d9895
840
package nl.knokko.server.chat; import java.util.ArrayList; import java.util.List; import nl.knokko.server.connection.UserSocketConnection; public class ChatChannel { private List<UserSocketConnection> members; public ChatChannel() { members = new ArrayList<UserSocketConnection>(); } public void broadcastMessage(String message){ for(UserSocketConnection user : members) user.getSpeaker().sendChatMessage(message); } public void addMember(UserSocketConnection member){ members.add(member); broadcastMessage(member.getData().getUsername() + " joined this channel."); for(int i = 0; i < 20; i++) broadcastMessage("spam " + i); } public boolean isMember(UserSocketConnection user){ return members.contains(user); } public void removeMember(UserSocketConnection member){ members.remove(member); } }
23.333333
77
0.74881
7a03d284e9d23444145cae67eed814e3cdf92516
1,997
import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.paint.Color; /** * This class represents the NextLevel Scene, which is reached whenever the player beats a level. * From here, the player can start the next level. The constructor for the class takes in the * next level as a parameter, which is how the class knows what level to go to next. It also * knows when to advance to the BossBattle Scene. * * @author João Kiakumbo Sebatião (JKiakumbo) * @version 1.0 */ public class NextLevel implements SceneInterface { private SceneManager sceneManager; private Scene nextLevelScene; private Group root; private int level; /** * Constructor for NextLevel class * @param sceneManager SceneManager currently being used * @param level the next level */ public NextLevel(SceneManager sceneManager, int level) { this.sceneManager = sceneManager; this.level = level; } /** * Returns the NextLevel Scene */ @Override public Scene init(int width, int height) { root = new Group(); nextLevelScene = new Scene(root, width, height, Color.AZURE); addNextLevelButton(); return nextLevelScene; } private void addNextLevelButton() { String text = isNextLevelBoss() ? "Go to boss level" : "Go to level " + level; Button nextLevelButton = UIGenerator.createButton(text, 50, 50); nextLevelButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if (isNextLevelBoss()) { sceneManager.goToBossBattleScene(sceneManager); } else { sceneManager.goToBattleScene(sceneManager, level); } } }); root.getChildren().add(nextLevelButton); } private boolean isNextLevelBoss() { return level >= Battle.TOTAL_LEVELS ? true : false; } }
28.942029
97
0.68653
50653a44d44c65b0d0f8fee04473f54db99ad195
856
package com.acmerobotics.relicrecovery.opmodes.test; import com.acmerobotics.library.localization.Pose2d; import com.acmerobotics.library.path.TrajectoryBuilder; import com.acmerobotics.relicrecovery.subsystems.Robot; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; @Autonomous public class LinearPathTest extends LinearOpMode { @Override public void runOpMode() throws InterruptedException { Robot robot = new Robot(this); robot.drive.enablePositionEstimation(); robot.start(); waitForStart(); robot.drive.followTrajectory( robot.drive.trajectoryBuilder(new Pose2d(0, 0, 0)) .lineToPose(new Pose2d(72, 0, Math.PI)) .build()); robot.drive.waitForTrajectoryFollower(); } }
32.923077
66
0.714953
18a4e85ace5631d0362ecfe5717245ac6494cca6
666
package pers.tavish.ex.chapter2.elementarysorts.creativeproblems; import edu.princeton.cs.algs4.Transaction; import pers.tavish.code.chapter2.elementarysorts.Selection; public class SortTransaction { public static void main(String[] args) { Transaction[] a = new Transaction[4]; a[0] = new Transaction("Turing 6/17/1990 644.08"); a[1] = new Transaction("Tarjan 3/26/2002 4121.85"); a[2] = new Transaction("Knuth 6/14/1999 288.34"); a[3] = new Transaction("Dijkstra 8/22/2007 2678.40"); Selection.sort(a); for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } }
31.714286
65
0.626126
940e1f5190d3a2a487a2a096a750ae319b0dcc4a
781
package com.spring.regist; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanNameGenerator; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.type.AnnotationMetadata; //自己注册一个bean public class MyRegisterBean implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) { RootBeanDefinition beanDefinition=new RootBeanDefinition(Mybean.class); registry.registerBeanDefinition("rainbow",beanDefinition); } }
35.5
112
0.855314
8a0398c602667b17882ef7edeb767141cb7357a9
1,662
package com.dylanthesoldier.apprepofx.model.global; import com.dylanthesoldier.apprepofx.controllers.main.MainViewController; import com.dylanthesoldier.apprepofx.controllers.settings.AppSettings; import com.dylanthesoldier.apprepofx.controllers.settings.SettingsViewController; import com.dylanthesoldier.apprepofx.model.pkg.PackageLoader; import com.dylanthesoldier.assistlibfx.Dialogs; import com.dylanthesoldier.assistlibfx.PathsChecker; import javafx.stage.Stage; import java.io.IOException; /** * Created by c-dmoore on 10/24/2016. */ public class Initializer { public static void init(Stage stage) throws IOException { // --- Load all the Singleton Classes --- R.stage = stage; R.packageLoader = PackageLoader.createInstance(); AppSettings.getInstance().loadDefaultSettingsFile(); checkPropertiesFile(); checkForFolders(); // --- Create instance to preload settings & has to be called after loading the properties file above. --- SettingsViewController.createInstance().setPreviousNode(MainViewController.createInstance()).setStage(R.stage); } private static void checkPropertiesFile(){ AppSettings.properties.put(AppSettings.LAST_USED_DIRECTORY, AppSettings.PACKAGES_DIRECTORY); } private static void checkForFolders() { PathsChecker.getPathChecksList().add(new PathsChecker.Checks("cache", true)); PathsChecker.getPathChecksList().add(new PathsChecker.Checks("pkgs", true)); PathsChecker.performPathChecks(e -> Dialogs.createErrorDialog(e, true, AppSettings.getInstance().isDebugModeEnabled()) ); } }
36.933333
119
0.743682
3ddf1ea75071f937bf13280c11b217e8ff8f4835
1,733
package net.optifine.gui; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.settings.GameSettings; import net.optifine.Lang; import java.awt.*; import java.util.ArrayList; import java.util.List; public class TooltipProviderOptions implements TooltipProvider { public Rectangle getTooltipBounds(GuiScreen guiScreen, int x, int y) { int i = guiScreen.width / 2 - 150; int j = guiScreen.height / 6 - 7; if (y <= j + 98) { j += 105; } int k = i + 150 + 150; int l = j + 84 + 10; return new Rectangle(i, j, k - i, l - j); } public boolean isRenderBorder() { return false; } public String[] getTooltipLines(GuiButton btn, int width) { if (!(btn instanceof IOptionControl)) { return null; } else { IOptionControl ioptioncontrol = (IOptionControl) btn; GameSettings.Options gamesettings$options = ioptioncontrol.getOption(); String[] astring = getTooltipLines(gamesettings$options.getEnumString()); return astring; } } public static String[] getTooltipLines(String key) { List<String> list = new ArrayList(); for (int i = 0; i < 10; ++i) { String s = key + ".tooltip." + (i + 1); String s1 = Lang.get(s, (String) null); if (s1 == null) { break; } list.add(s1); } if (list.size() <= 0) { return null; } else { String[] astring = (String[]) ((String[]) list.toArray(new String[list.size()])); return astring; } } }
27.507937
93
0.559146
65575e6b5009d256108ed6cd4a6f84c921f0de7b
435
package net.technolords.micro.camel.processor; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RedisProcessor implements Processor { private final Logger LOGGER = LoggerFactory.getLogger(getClass()); @Override public void process(Exchange exchange) throws Exception { LOGGER.info("Todo: not implemented yet..."); } }
27.1875
70
0.756322
76f4ac1e4624a418ff9bf8d52ef87396403b6414
5,605
/* * ElementList.java July 2006 * * Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net> * * 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.simpleframework.xml; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Retention; /** * The <code>ElementList</code> annotation represents a method or * field that is a <code>Collection</code> for storing entries. The * collection object deserialized is typically of the same type as * the field. However, a <code>class</code> attribute can be used to * override the field type, however the type must be assignable. * <pre> * * &lt;list class="java.util.ArrayList"&gt; * &lt;entry name="one"/&gt; * &lt;entry name="two"/&gt; * &lt;entry name="three"/&gt; * &lt;/list&gt; * * </pre> * If a <code>class</code> attribute is not provided and the type or * the field or method is abstract, a suitable match is searched for * from the collections available from the Java collections framework. * This annotation can also compose an inline list of XML elements. * An inline list contains no parent or containing element. * <pre> * * &lt;entry name="one"/&gt; * &lt;entry name="two"/&gt; * &lt;entry name="three"/&gt; * * </pre> * The above XML is an example of the output for an inline list of * XML elements. In such a list the annotated field or method must * not be given a name. Instead the name is acquired from the name of * the entry type. For example if the <code>type</code> attribute of * this was set to an object <code>example.Entry</code> then the name * of the entry list would be taken as the root name of the object * as taken from the <code>Root</code> annotation for that object. * * @author Niall Gallagher */ @Retention(RetentionPolicy.RUNTIME) public @interface ElementList { /** * This represents the name of the XML element. Annotated fields * can optionally provide the name of the element. If no name is * provided then the name of the annotated field or method will * be used in its place. The name is provided if the field or * method name is not suitable as an XML element name. Also, if * the list is inline then this must not be specified. * * @return the name of the XML element this represents */ String name() default ""; /** * This is used to provide a name of the XML element representing * the entry within the list. An entry name is optional and is * used when the name needs to be overridden. This also ensures * that entry, regardless of type has the same root name. * * @return this returns the entry XML element for each value */ String entry() default ""; /** * Represents the type of object the element list contains. This * type is used to deserialize the XML elements from the list. * The object typically represents the deserialized type, but can * represent a subclass of the type deserialized as determined * by the <code>class</code> attribute value for the list. If * this is not specified then the type can be determined from the * generic parameter of the annotated <code>Collection</code>. * * @return the type of the element deserialized from the XML */ Class type() default void.class; /** * This is used to determine whether the element data is written * in a CDATA block or not. If this is set to true then the text * is written within a CDATA block, by default the text is output * as escaped XML. Typically this is useful when this annotation * is applied to an array of primitives, such as strings. * * @return true if entries are to be wrapped in a CDATA block */ boolean data() default false; /** * Determines whether the element is required within the XML * document. Any field marked as not required will not have its * value set when the object is deserialized. If an object is to * be serialized only a null attribute will not appear as XML. * * @return true if the element is required, false otherwise */ boolean required() default true; /** * Determines whether the element list is inlined with respect * to the parent XML element. An inlined element list does not * contain an enclosing element. It is simple a sequence of * elements that appear one after another within an element. * As such an inline element list must not have a name. * * @return this returns true if the element list is inline */ boolean inline() default false; /** * This is used to determine if an optional field or method can * remain null if it does not exist. If this is false then the * optional element is given an empty list. This is a convenience * attribute which avoids having to check if the element is null * before providing it with a suitable default instance. * * @return false if an optional element is always instantiated */ boolean empty() default true; }
39.751773
70
0.693845
3820e533fceab02d2177ac2dda0308ddd4be4a64
4,977
package org.apache.maven.doxia.siterenderer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlDivision; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlHeading2; import com.gargoylesoftware.htmlunit.html.HtmlListItem; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlParagraph; import com.gargoylesoftware.htmlunit.html.HtmlSection; import com.gargoylesoftware.htmlunit.html.HtmlUnorderedList; import java.util.Iterator; /** * * @author ltheussl */ public class MultipleBlockVerifier extends AbstractVerifier { /** {@inheritDoc} */ public void verify( String file ) throws Exception { HtmlPage page = htmlPage( file ); assertNotNull( page ); HtmlElement element = page.getHtmlElementById( "contentBox" ); assertNotNull( element ); HtmlDivision division = (HtmlDivision) element; assertNotNull( division ); Iterator<HtmlElement> elementIterator = division.getHtmlElementDescendants().iterator(); // ---------------------------------------------------------------------- // Verify link // ---------------------------------------------------------------------- HtmlSection section = (HtmlSection) elementIterator.next(); assertNotNull( section ); HtmlHeading2 h2 = (HtmlHeading2) elementIterator.next(); assertNotNull( h2 ); assertEquals( "section name", h2.asText().trim() ); HtmlAnchor a = (HtmlAnchor) elementIterator.next(); assertNotNull( a ); assertEquals( "section_name", a.getAttribute( "name" ) ); // ---------------------------------------------------------------------- // Paragraph // ---------------------------------------------------------------------- HtmlParagraph p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); assertEquals( "text", p.asText().trim() ); // ---------------------------------------------------------------------- // Unordered list // ---------------------------------------------------------------------- HtmlUnorderedList ul = (HtmlUnorderedList) elementIterator.next(); assertNotNull( ul ); HtmlListItem li = (HtmlListItem) elementIterator.next(); assertNotNull( li ); assertEquals( "list1", li.getFirstChild().asText().trim() ); // ---------------------------------------------------------------------- // Paragraph // ---------------------------------------------------------------------- p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); assertEquals( "text2", p.asText().trim() ); // ---------------------------------------------------------------------- // Unordered list // ---------------------------------------------------------------------- ul = (HtmlUnorderedList) elementIterator.next(); assertNotNull( ul ); li = (HtmlListItem) elementIterator.next(); assertNotNull( li ); assertEquals( "list1", li.getFirstChild().asText().trim() ); // ---------------------------------------------------------------------- // Paragraph // ---------------------------------------------------------------------- p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); assertEquals( "text3", p.asText().trim() ); // ---------------------------------------------------------------------- // Unordered list // ---------------------------------------------------------------------- ul = (HtmlUnorderedList) elementIterator.next(); assertNotNull( ul ); li = (HtmlListItem) elementIterator.next(); assertNotNull( li ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); assertEquals( "list1", p.getFirstChild().asText().trim() ); assertFalse( elementIterator.hasNext() ); } }
37.421053
96
0.518385
49ab3c163f8b42391eae0a6b3217dd88d26cc781
1,089
package io.resourcepool.generator; import io.resourcepool.model.Language; /** * Text Generator Filter. * Use this class to specify filters for your content generator * @author Loïc Ortola */ public class Query { public final int count; public final Language[] languages; public Query(int count, Language... languages) { this.count = count > 0 ? count : 1; this.languages = (languages == null || languages.length == 0) ? Language.values() : languages; } public static Builder builder() { return new Builder(); } public static class Builder { private int count; private Language[] languages; private Builder() { } public Builder count(int count) { if (count <= 0) { throw new IllegalArgumentException("Count must be greater than zero"); } this.count = count; return this; } public Builder languages(Language... languages) { this.languages = languages; return this; } public Query build() { return new Query(count, languages); } } }
21.78
98
0.628099
674ede2c8740fa25d036b2e54aa6c5dbc9f6d408
43,247
package com.yilian.mall.ui.fragment; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import com.orhanobut.logger.Logger; import com.yilian.loginmodule.LeFenPhoneLoginActivity; import com.yilian.mall.R; import com.yilian.mall.adapter.RedDateGridAdapter; import com.yilian.mall.adapter.RedPacketFragmentAdapter; import com.yilian.mall.ui.OpenRedPackageActivity; import com.yilian.mall.ui.RedExplainDialog; import com.yilian.mall.ui.RedIndexDialog; import com.yilian.mall.ui.RedPacketDialog2; import com.yilian.mall.umeng.IconModel; import com.yilian.mall.umeng.ShareUtile; import com.yilian.mall.umeng.UmengDialog; import com.yilian.mall.umeng.UmengGloble; import com.yilian.mall.utils.DateUtils; import com.yilian.mall.utils.MoneyUtil; import com.yilian.mall.utils.Toast; import com.yilian.mall.widgets.NoScrollGridView; import com.yilian.mylibrary.AppManager; import com.yilian.mylibrary.BannerViewGlideUtil; import com.yilian.mylibrary.CheckServiceReturnEntityUtil; import com.yilian.mylibrary.CommonUtils; import com.yilian.mylibrary.Constants; import com.yilian.mylibrary.JumpToOtherPage; import com.yilian.mylibrary.NoDoubleClickListener; import com.yilian.mylibrary.PreferenceUtils; import com.yilian.mylibrary.RxUtil; import com.yilian.mylibrary.ScreenUtils; import com.yilian.mylibrary.ThreadUtil; import com.yilian.mylibrary.WebImageUtil; import com.yilian.mylibrary.event.RefreshRedPacketStatus; import com.yilian.networkingmodule.entity.RedPacketDateEntity; import com.yilian.networkingmodule.entity.RedPacketFragmentHeadEntity; import com.yilian.networkingmodule.entity.RedPacketOneKeyRemoveEntity; import com.yilian.networkingmodule.entity.RemoveRedRecordEntity; import com.yilian.networkingmodule.httpresult.HttpResultBean; import com.yilian.networkingmodule.retrofitutil.RetrofitUtils2; import com.youth.banner.Banner; import com.youth.banner.BannerConfig; import com.youth.banner.listener.OnBannerListener; import java.util.ArrayList; import io.reactivex.functions.Consumer; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * 奖励的fragment * * @author Ray_L_Pain * @date 2017/11/22 0022 */ public class RedPacketFragment extends JPBaseFragment implements BaseQuickAdapter.RequestLoadMoreListener, RefreshRedPacketStatus { public boolean isRefresh = false; /** * 获取用户奖券 */ public float userIntegral; @ViewInject(R.id.tv_title) TextView tvTitle; @ViewInject(R.id.tv_right) TextView tvRight; @ViewInject(R.id.iv_back) ImageView ivBack; @ViewInject(R.id.iv_return_top) ImageView iv_return_top; @ViewInject(R.id.swipe_refresh_layout) SwipeRefreshLayout swipeRefreshLayout; @ViewInject(R.id.recycler_view) RecyclerView recyclerView; @ViewInject(R.id.main_layout) RelativeLayout mainLayout; @ViewInject(R.id.not_login_layout) LinearLayout notLoginLayout; @ViewInject(R.id.tv_no_data) TextView tvNotLogin; private View rootView, emptyView, errorView, headerView, footerView; private FrameLayout frameLayout; private TextView tvRefresh, tvFrameTitle, tvFrameMoney, tvFrameDefeat, tvFrameBtn, tvRedIndex, tvAllDay, tvMonth, tvNotGet, tvGetBtn; private ImageView ivLeft, ivRight; private Banner banner; private NoScrollGridView dateGridView; private LinearLayout getAllLayout; private int page = 0; private RedPacketFragmentAdapter adapter; private ArrayList<RemoveRedRecordEntity.DataBean> list = new ArrayList<>(); //页面第一次加载标识 private boolean isFirst = true; //数据第一次加载标识 private boolean getFirstPageDataFlag = true; private int screenWidth; private RedDateGridAdapter dateGridAdapter; private int year, month; private int getAllRedNum; private String getAllRedMoney; private int getAllRedNotNum; private String getAllRedNotMoney; /** * 奖励分享 */ private UmengDialog mShareDialog; private String shareTitle, shareContent, shareImg, shareUrl; /** * 一键拆取奖励 */ private String shareRedMoney, shareRedNum, shareRedTime, shareRedPhoto, shareRedName; // 实际的分享数据 private String inFactShareRedMoney, inFactShareRedNum, inFactShareRedTime, inFactShareRedPhoto, inFactShareRedName; @Override public void setUserVisibleHint(boolean isVisibleToUser) { if (isVisibleToUser && isFirst) { ThreadUtil.getThreadPollProxy().execute(new Runnable() { @Override public void run() { try { Thread.sleep(1500); if (null != getActivity()) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (swipeRefreshLayout != null) { swipeRefreshLayout.setRefreshing(true); } isFirst = false; getFirstPageData(); } }); } } catch (InterruptedException e) { e.printStackTrace(); } } }); } super.setUserVisibleHint(isVisibleToUser); } @Override protected void loadData() { } @Override protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (rootView == null) { rootView = LayoutInflater.from(mContext).inflate(R.layout.activity_red_packet, null); } ViewUtils.inject(this, rootView); initView(); initListener(); return rootView; } @Override public void onResume() { super.onResume(); isRefresh = PreferenceUtils.readBoolConfig(Constants.REFRESH_RED_FRAGMENT, mContext, false); if (isRefresh) { Logger.i("2017年11月28日 15:38:18-走了onResume"); getFirstPageData(); isRefresh = false; PreferenceUtils.writeBoolConfig(Constants.REFRESH_RED_FRAGMENT, isRefresh, mContext); } } private void initView() { RxUtil.clicks(ivBack, new Consumer() { @Override public void accept(Object o) throws Exception { FragmentActivity activity = getActivity(); //刷新奖励标识 PreferenceUtils.writeBoolConfig(Constants.REFRESH_RED_FRAGMENT, true, mContext); if (activity != null) { activity.finish(); } else { AppManager.getInstance().killActivity(OpenRedPackageActivity.class); } } }); screenWidth = ScreenUtils.getScreenWidth(mContext); tvRight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(mContext, RedExplainDialog.class)); } }); if (emptyView == null) { emptyView = View.inflate(mContext, R.layout.library_module_no_data, null); } if (errorView == null) { errorView = View.inflate(mContext, R.layout.library_module_load_error2, null); tvRefresh = (TextView) errorView.findViewById(R.id.tv_refresh); tvRefresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { swipeRefreshLayout.setRefreshing(true); getFirstPageData(); } }); } if (footerView == null) { footerView = View.inflate(mContext, R.layout.red_foot, null); } if (headerView == null) { headerView = View.inflate(mContext, R.layout.header_red_packet, null); frameLayout = (FrameLayout) headerView.findViewById(R.id.frame_layout); tvFrameTitle = (TextView) headerView.findViewById(R.id.tv_frame_title); tvFrameMoney = (TextView) headerView.findViewById(R.id.tv_frame_money); tvFrameDefeat = (TextView) headerView.findViewById(R.id.tv_defeat); tvFrameBtn = (TextView) headerView.findViewById(R.id.tv_frame_btn); banner = (Banner) headerView.findViewById(R.id.banner); tvRedIndex = (TextView) headerView.findViewById(R.id.tv_red_index); ivLeft = (ImageView) headerView.findViewById(R.id.iv_left); ivRight = (ImageView) headerView.findViewById(R.id.iv_right); tvMonth = (TextView) headerView.findViewById(R.id.tv_month); tvAllDay = (TextView) headerView.findViewById(R.id.tv_all_day); dateGridView = (NoScrollGridView) headerView.findViewById(R.id.grid_view_date); dateGridView.setFocusable(false); dateGridView.setFocusableInTouchMode(false); getAllLayout = (LinearLayout) headerView.findViewById(R.id.layout_get); tvNotGet = (TextView) headerView.findViewById(R.id.tv_not_get); tvGetBtn = (TextView) headerView.findViewById(R.id.tv_get_btn); LinearLayout.LayoutParams params1 = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); params1.width = screenWidth; params1.height = (int) ((794 * 0.1) * screenWidth / (1080 * 0.1)); FrameLayout.LayoutParams params2 = (FrameLayout.LayoutParams) tvFrameTitle.getLayoutParams(); FrameLayout.LayoutParams params3 = (FrameLayout.LayoutParams) tvFrameMoney.getLayoutParams(); FrameLayout.LayoutParams params4 = (FrameLayout.LayoutParams) tvFrameBtn.getLayoutParams(); LinearLayout.LayoutParams params5 = (LinearLayout.LayoutParams) banner.getLayoutParams(); // params5.height = (int) ((306 * 0.1) * screenWidth / (1012 * 0.1)); params5.height = (screenWidth * 100) / 345; Logger.i("banner width:" + params5.width + " height:" + params5.height); FrameLayout.LayoutParams params6 = (FrameLayout.LayoutParams) tvFrameDefeat.getLayoutParams(); switch (screenWidth) { case 720: params2.setMargins(0, 167, 0, 0); params3.setMargins(0, 233, 0, 0); params6.setMargins(0, 320, 0, 0); params4.setMargins(0, 367, 0, 0); break; case 1080: params2.setMargins(0, 250, 0, 0); params3.setMargins(0, 350, 0, 0); params6.setMargins(0, 480, 0, 0); params4.setMargins(0, 550, 0, 0); break; case 1440: params2.setMargins(0, 333, 0, 0); params3.setMargins(0, 467, 0, 0); params6.setMargins(0, 640, 0, 0); params4.setMargins(0, 733, 0, 0); break; default: break; } } LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext); recyclerView.setLayoutManager(linearLayoutManager); if (adapter == null) { adapter = new RedPacketFragmentAdapter(R.layout.item_red_packet_list, mAppCompatActivity); } recyclerView.setAdapter(adapter); swipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.color_red)); tvNotLogin.setText("请登录后查看"); tvNotLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(mContext, LeFenPhoneLoginActivity.class)); } }); } private void initListener() { recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { int scrollDy = 0; @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { scrollDy += dy; if (scrollDy > ScreenUtils.getScreenHeight(mContext) * 3) { iv_return_top.setVisibility(View.VISIBLE); } else { iv_return_top.setVisibility(View.GONE); } super.onScrolled(recyclerView, dx, dy); } }); iv_return_top.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { recyclerView.smoothScrollToPosition(0); } }); adapter.setOnLoadMoreListener(this, recyclerView); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshData(); } }); } @Override public void setOnRefreshRedPacketStatus() { // * 拆取奖励时,若奖励状态异常则刷新奖励数据 getDateRecord(year, month); } /** * 获取某月的奖励数据 * * @param year * @param month */ private void getDateRecord(int year, int month) { Logger.i("ray-" + year); Logger.i("ray-" + month); RetrofitUtils2.getInstance(mContext).getRedDate(String.valueOf(year), String.valueOf(month), new Callback<RedPacketDateEntity>() { @Override public void onResponse(Call<RedPacketDateEntity> call, Response<RedPacketDateEntity> response) { HttpResultBean body = response.body(); if (CheckServiceReturnEntityUtil.checkServiceReturnEntity(mContext, body)) { if (CommonUtils.serivceReturnCode(mContext, body.code, body.msg)) { RedPacketDateEntity entity = response.body(); switch (entity.code) { case 1: getAllRedNum = entity.unClaimedNum; getAllRedMoney = MoneyUtil.getLeXiangBiNoZero(entity.unClaimedAmount); getAllRedNotNum = entity.unActivateNum; getAllRedNotMoney = MoneyUtil.getLeXiangBiNoZero(entity.unActivateAmount); userIntegral = Float.parseFloat(MoneyUtil.getLeXiangBiNoZero(entity.userIntegral)); tvMonth.setText(entity.monthStr); tvAllDay.setText("当前已累计领取" + entity.claimedNum + "天"); int notGetNum = entity.unClaimedNum; if (notGetNum > 4) { getAllLayout.setVisibility(View.VISIBLE); tvNotGet.setText("您有" + entity.unClaimedNum + "个未拆取的奖励"); tvGetBtn.setOnClickListener(new NoDoubleClickListener() { @Override public void onNoDoubleClick(View v) { if (getAllRedNotNum > 0) { AlertDialog builder = new AlertDialog.Builder(mAppCompatActivity).create(); builder.setMessage("您有" + String.valueOf(getAllRedNum) + "个未拆奖励,共" + getAllRedMoney + "。其中包含" + String.valueOf(getAllRedNotNum) + "个失效奖励,继续一键拆取需要消耗" + getAllRedNotMoney + "奖券激活,是否继续一键拆取?"); builder.setButton(DialogInterface.BUTTON_NEGATIVE, "再想想", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setButton(DialogInterface.BUTTON_POSITIVE, "继续", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (userIntegral < Float.parseFloat(getAllRedNotMoney)) { showIntegralLack(); } else { getAllPacket("2"); } dialog.dismiss(); } }); builder.show(); builder.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(mAppCompatActivity.getResources().getColor(R.color.color_red)); builder.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(mAppCompatActivity.getResources().getColor(R.color.color_333)); } else { getAllPacket("1"); } } }); } else { getAllLayout.setVisibility(View.INVISIBLE); } ArrayList<RedPacketDateEntity.ListArrBean> newList = entity.listArr; int firstSize = newList.size(); Logger.i("2017年11月24日 10:57:26-" + firstSize); RedPacketDateEntity.ListArrBean firstBean = newList.get(0); String fakerTime = firstBean.packetTime; String fakerExist = "2"; RedPacketDateEntity.ListArrBean fakeBean = new RedPacketDateEntity.ListArrBean(fakerTime, fakerExist); Logger.i("2017年11月24日 10:57:26-" + fakeBean.toString()); String date = firstBean.packetTime; int week = DateUtils.getWeekByStamp(Long.parseLong(date) * 1000) - 1; Logger.i("2017年11月24日 10:57:26-week-" + date); Logger.i("2017年11月24日 10:57:26-week-" + week); switch (week) { case 1: Logger.i("2017年11月24日 10:57:26-" + "周一"); break; case 2: Logger.i("2017年11月24日 10:57:26-" + "周二"); newList.add(0, fakeBean); break; case 3: Logger.i("2017年11月24日 10:57:26-" + "周三"); newList.add(0, fakeBean); newList.add(1, fakeBean); break; case 4: Logger.i("2017年11月24日 10:57:26-" + "周四"); newList.add(0, fakeBean); newList.add(1, fakeBean); newList.add(2, fakeBean); break; case 5: Logger.i("2017年11月24日 10:57:26-" + "周五"); newList.add(0, fakeBean); newList.add(1, fakeBean); newList.add(2, fakeBean); newList.add(3, fakeBean); break; case 6: Logger.i("2017年11月24日 10:57:26-" + "周六"); newList.add(0, fakeBean); newList.add(1, fakeBean); newList.add(2, fakeBean); newList.add(3, fakeBean); newList.add(4, fakeBean); break; case 0: Logger.i("2017年11月24日 10:57:26-" + "周日"); newList.add(0, fakeBean); newList.add(1, fakeBean); newList.add(2, fakeBean); newList.add(3, fakeBean); newList.add(4, fakeBean); newList.add(5, fakeBean); break; default: break; } int lastSize = newList.size(); int diffSize = lastSize - firstSize - 1; Logger.i("2017年11月24日 10:57:26-" + newList.size()); Logger.i("2017年11月24日 10:57:26-" + newList.toString()); Logger.i("2017年11月24日 10:57:26-" + diffSize); dateGridView.setVisibility(View.VISIBLE); dateGridAdapter = new RedDateGridAdapter(mAppCompatActivity, newList, diffSize, userIntegral, RedPacketFragment.this); dateGridView.setAdapter(dateGridAdapter); break; default: break; } } } swipeRefreshLayout.setRefreshing(false); } @Override public void onFailure(Call<RedPacketDateEntity> call, Throwable t) { dateGridView.setVisibility(View.GONE); swipeRefreshLayout.setRefreshing(false); } }); } /** * 奖券不足时dialog */ private void showIntegralLack() { AlertDialog builder = new AlertDialog.Builder(mAppCompatActivity).create(); builder.setMessage("当前奖券不足,无法激活所有失效奖励,是否优先拆取未失效奖励?"); builder.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { getAllPacket("1"); dialog.dismiss(); } }); builder.show(); builder.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(mAppCompatActivity.getResources().getColor(R.color.color_red)); builder.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(mAppCompatActivity.getResources().getColor(R.color.color_333)); } private void getAllPacket(String type) { startMyDialog(); RetrofitUtils2.getInstance(mContext).oneKeyRemoveRedPacket(type, new Callback<RedPacketOneKeyRemoveEntity>() { @Override public void onResponse(Call<RedPacketOneKeyRemoveEntity> call, Response<RedPacketOneKeyRemoveEntity> response) { stopMyDialog(); HttpResultBean body = response.body(); if (CheckServiceReturnEntityUtil.checkServiceReturnEntity(mContext, body)) { if (CommonUtils.serivceReturnCode(mContext, body.code, body.msg)) { RedPacketOneKeyRemoveEntity entity = response.body(); switch (entity.code) { case 1: shareRedMoney = entity.packetAmount; shareRedNum = entity.packetNum; shareRedTime = entity.serverTime; Intent intent = new Intent(getActivity(), RedPacketDialog2.class); intent.putExtra("red_id", ""); intent.putExtra("red_money", MoneyUtil.getLeXiangBiNoZero(shareRedMoney)); intent.putExtra("red_from", "all"); startActivity(intent); break; default: break; } } } } @Override public void onFailure(Call<RedPacketOneKeyRemoveEntity> call, Throwable t) { stopMyDialog(); showToast(R.string.net_work_not_available); } }); } private void refreshData() { getFirstPageDataFlag = true; getFirstPageData(); adapter.setEnableLoadMore(false); } private void getFirstPageData() { startMyDialog(); page = 0; getData(); } private void getNextPageData() { page++; getData(); } private void getData() { RetrofitUtils2.getInstance(mContext).removeRedPacketReocrds(String.valueOf(page), "30", new Callback<RemoveRedRecordEntity>() { @Override public void onResponse(Call<RemoveRedRecordEntity> call, Response<RemoveRedRecordEntity> response) { HttpResultBean body = response.body(); if (CheckServiceReturnEntityUtil.checkServiceReturnEntity(mContext, body)) { switch (body.code) { case -4: case -23: Toast.makeText(mContext, "登录状态失效,请重新登录.", Toast.LENGTH_SHORT).show(); PreferenceUtils.writeBoolConfig(Constants.SPKEY_STATE, false, mContext); PreferenceUtils.writeBoolConfig(Constants.REFRESH_USER_FRAGMENT, true, mContext); PreferenceUtils.writeBoolConfig(Constants.REFRESH_HOME_FRAGMENT, true, mContext); Intent intent = new Intent(mContext, LeFenPhoneLoginActivity.class); startActivity(intent); mainLayout.setVisibility(View.GONE); notLoginLayout.setVisibility(View.VISIBLE); break; default: mainLayout.setVisibility(View.VISIBLE); notLoginLayout.setVisibility(View.GONE); break; } if (CommonUtils.serivceReturnCode(mContext, body.code, body.msg)) { RemoveRedRecordEntity entity = response.body(); switch (response.body().code) { case 1: initHeaderView(); ArrayList<RemoveRedRecordEntity.DataBean> newList = entity.data; Logger.i("onResume:" + newList.size()); if (newList != null && newList.size() > 0) { if (page > 0) { adapter.addData(newList); } else { getFirstPageDataFlag = false; adapter.setNewData(newList); } if (newList.size() < Constants.PAGE_COUNT) { adapter.loadMoreEnd(); } else { adapter.loadMoreComplete(); } } else { if (page == 0) { adapter.setNewData(newList); adapter.loadMoreEnd(); initFootView(); } } break; default: adapter.setEmptyView(emptyView); break; } } } netRequestEnd(); } @Override public void onFailure(Call<RemoveRedRecordEntity> call, Throwable t) { mainLayout.setVisibility(View.VISIBLE); notLoginLayout.setVisibility(View.GONE); if (page == 0) { adapter.setEmptyView(errorView); } else if (page > 0) { page--; if (adapter.getEmptyViewCount() > 0) { ((ViewGroup) adapter.getEmptyView()).removeAllViews(); } adapter.notifyDataSetChanged(); } adapter.loadMoreFail(); netRequestEnd(); showToast(R.string.system_busy); } }); } /** * 网络请求结束,各个控件恢复初始状态 */ private void netRequestEnd() { swipeRefreshLayout.setEnabled(true); swipeRefreshLayout.setRefreshing(false); adapter.setEnableLoadMore(true); stopMyDialog(); } @Override public void onLoadMoreRequested() { swipeRefreshLayout.setEnabled(false); getNextPageData(); } private void initFootView() { if (adapter.getFooterLayoutCount() > 0) { adapter.removeAllFooterView(); } adapter.addFooterView(footerView); adapter.notifyDataSetChanged(); } private void initHeaderView() { if (adapter.getFooterLayoutCount() > 0) { adapter.removeAllFooterView(); } if (adapter.getHeaderLayoutCount() > 0) { adapter.removeAllHeaderView(); } adapter.addHeaderView(headerView); adapter.notifyDataSetChanged(); /** * 头部数据 */ getHeadData(); /** * 日历数据 */ year = DateUtils.getYear(); month = DateUtils.getMonth(); getDateRecord(year, month); tvRedIndex.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, RedIndexDialog.class); startActivity(intent); } }); ivLeft.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (month == 1) { month = 12; year--; } else { month--; } swipeRefreshLayout.setRefreshing(true); getDateRecord(year, month); } }); ivRight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (month == 12) { month = 1; year++; } else { month++; } swipeRefreshLayout.setRefreshing(true); getDateRecord(year, month); } }); } private void getHeadData() { RetrofitUtils2.getInstance(mContext).getRedHead(new Callback<RedPacketFragmentHeadEntity>() { @Override public void onResponse(Call<RedPacketFragmentHeadEntity> call, Response<RedPacketFragmentHeadEntity> response) { HttpResultBean body = response.body(); if (CheckServiceReturnEntityUtil.checkServiceReturnEntity(mContext, body)) { if (CommonUtils.serivceReturnCode(mContext, body.code, body.msg)) { RedPacketFragmentHeadEntity entity = response.body(); switch (entity.code) { case 1: // 分享内容 RedPacketFragmentHeadEntity.ShareBean share = entity.share; shareContent = share.content; shareImg = share.imgUrl; shareTitle = share.title; shareUrl = share.url; inFactShareRedTime = entity.packetInfo.applyAt; inFactShareRedMoney = entity.packetInfo.amount; inFactShareRedName = entity.name; inFactShareRedPhoto = entity.photo; if (TextUtils.isEmpty(inFactShareRedPhoto)) { inFactShareRedPhoto = "https://img.yilian.lefenmall.com/app/images/touxiang.png"; } tvFrameTitle.setVisibility(View.VISIBLE); tvFrameTitle.setText("今日奖励"); tvFrameMoney.setVisibility(View.VISIBLE); tvFrameBtn.setVisibility(View.VISIBLE); if ("0".equals(entity.packetExist)) { tvFrameMoney.setText("???"); tvFrameDefeat.setVisibility(View.GONE); tvFrameBtn.setText("今日无奖励"); tvFrameBtn.setBackgroundResource(R.mipmap.red_packet_fragment_btn); tvFrameBtn.setAlpha(0.6f); } else { String status = entity.packetInfo.status; if (!TextUtils.isEmpty(status)) { switch (status) { case "0": tvFrameMoney.setText("???"); tvFrameDefeat.setVisibility(View.GONE); tvFrameBtn.setBackgroundResource(R.mipmap.red_packet_fragment_btn); tvFrameBtn.setText("立刻拆奖励"); tvFrameBtn.setAlpha(1); break; case "1": tvFrameMoney.setText(MoneyUtil.getLeXiangBiNoZero(entity.packetInfo.amount)); tvFrameDefeat.setVisibility(View.VISIBLE); tvFrameDefeat.setText(Html.fromHtml("<font color=\"#CA6400\"><small>奖励打败了全国 </small></font><font color=\"#F72D42\"><big>" + entity.packetInfo.percent + "%" + "</big></font><font color=\"#CA6400\"><small>的益粉</small></font>")); tvFrameBtn.setBackgroundResource(R.mipmap.red_packet_fragment_btn2); tvFrameBtn.setText("炫耀一下"); tvFrameBtn.setAlpha(1); break; default: break; } } } ArrayList<RedPacketFragmentHeadEntity.Banner> bannerList = entity.banner; banner.setVisibility(View.VISIBLE); ArrayList<String> imageList = new ArrayList<String>(); int size = bannerList.size(); for (int i = 0; i < size; i++) { String image = bannerList.get(i).image; imageList.add(WebImageUtil.getInstance().getWebImageUrlNOSuffix(image)); } banner.setImages(imageList) .setBannerStyle(BannerConfig.CIRCLE_INDICATOR) .setImageLoader(new BannerViewGlideUtil()) .setIndicatorGravity(BannerConfig.CENTER) .setOnBannerListener(new OnBannerListener() { @Override public void OnBannerClick(int position) { RedPacketFragmentHeadEntity.Banner bean = bannerList.get(position); JumpToOtherPage.getInstance(mContext).jumpToOtherPage(bean.type, bean.content); } }).start(); tvFrameBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (tvFrameBtn.getText().toString().trim()) { case "立刻拆奖励": Intent intent = new Intent(getActivity(), RedPacketDialog2.class); intent.putExtra("red_id", entity.packetInfo.id); intent.putExtra("red_money", MoneyUtil.getLeXiangBiNoZero(entity.packetInfo.amount)); intent.putExtra("red_from", "one"); startActivity(intent); break; case "炫耀一下": shareRedPacket(); break; default: break; } } }); break; default: break; } } } } @Override public void onFailure(Call<RedPacketFragmentHeadEntity> call, Throwable t) { showToast(R.string.net_work_not_available); } }); } private void shareRedPacket() { // shareTitle = "快来拆奖励吧~"; // shareContent = "我刚刚在益联益家拆得一个" + MoneyUtil.getLeXiangBiNoZero(inFactShareRedMoney) + "奖励,每天都有,快来拆开你的吧~"; // shareImg = "https://img.yilian.lefenmall.com/app/images/chb.png"; // shareUrl = Ip.getWechatURL(mContext) + "m/activity/sharePacket/sharePacket.php?gain_money=" + MoneyUtil.getLeXiangBiNoZero(inFactShareRedMoney) + // "&gain_time=" + com.yilian.luckypurchase.utils.DateUtils.timeStampToStr6(Long.parseLong(inFactShareRedTime)) + // "&user_img=" + WebImageUtil.getInstance().getWebImageUrlWithSuffix(inFactShareRedPhoto) + "&user_name=" + inFactShareRedName + "&sign=" + PreferenceUtils.readStrConfig(Constants.SPKEY_PHONE, mContext); Logger.i("2017年11月26日 12:30:55-" + shareRedMoney); Logger.i("2017年11月26日 12:30:55-" + shareRedTime); Logger.i("2017年11月26日 12:30:55-" + inFactShareRedName); Logger.i("2017年11月26日 12:30:55-" + WebImageUtil.getInstance().getWebImageUrlWithSuffix(inFactShareRedPhoto)); Logger.i("2017年11月26日 12:30:55-" + shareImg); Logger.i("2017年11月26日 12:30:55-" + shareUrl); if (TextUtils.isEmpty(shareUrl)) { getHeadData(); showToast(R.string.service_exception); return; } if (mShareDialog == null) { mShareDialog = new UmengDialog(mAppCompatActivity, AnimationUtils.loadAnimation(getActivity(), R.anim.anim_wellcome_bottom), R.style.DialogControl, new UmengGloble().getAllIconModels()); mShareDialog.setItemLister(new UmengDialog.OnListItemClickListener() { @Override public void OnItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3, Object arg4) { new ShareUtile( mAppCompatActivity, ((IconModel) arg4).getType(), shareTitle, shareContent, shareImg, shareUrl, Constants.RED_SHARE) .share(); } }); } // 依附的activity对象被回收时会报错,目前依附的activity使用存储下来的变量,暂未发现崩溃,以防万一添加catch抓取 try { mShareDialog.show(); } catch (Exception e) { e.getStackTrace(); } } }
47.161396
273
0.49978
3004fe46e12353ba1b3415bd4cac74e692787c64
742
/* * Copyright (c) 2018. JeongHa, Cho */ package head.first.design.pattern.rule.singleton.general; /** * Created by cho_jeong_ha on 2018-03-27 오후 3:49 * Blog : https://jungha-cho.github.io/ * Github : https://github.com/JungHa-Cho * Email : ppzxc8487@gmail.com */ public class OldSingleton2 { /** * static으로 선언되 전역 변수로 사용될 인스턴스 */ private static OldSingleton2 uniqueInstance; /** * Singleton을 위해 private으로 외부 생성을 막음 */ private OldSingleton2() { } /** * 고전 singleton의 getInstance * * @return 유일무이 객체 */ public static OldSingleton2 getInstance() { // static 변수만 있을뿐, 객체 할당 검사 if (uniqueInstance == null) { uniqueInstance = new OldSingleton2(); } return uniqueInstance; } }
20.054054
57
0.6469
e2fdeb1cbe87fb00a3ec828098aeab01e3c18505
397
package array11; public class Array11 { //Dado um Array numérico "nums" e um "index" (valor 0), retorne o número de vezes em que o "11" aparece no Array dado. //Fazer recursivamente. public int array11(int[] nums, int index) { if (index >= nums.length) return 0; if (nums[index] == 11) return array11(nums, index+1) + 1; return array11(nums,index+1); } }
30.538462
122
0.629723
613145dc6a933dafb3245294dc5c578588527d41
2,186
package com.fbx; import java.io.Serializable; public class CameraData implements Serializable { // 摄像头ID private int cameraId; // 设备序列号(用于播放) private String cameraSns; // 设备描述,标题 private String cameraTitle; // 设备快照资源地址 private String snapshotUrl; // 设备状态 private Boolean online; // 设备号 private int cameraNo; // 店铺ID private int shopId; public CameraData(String cameraSns) { this.cameraSns = cameraSns; this.online = true; } public CameraData(int cameraId, String cameraSns, int cameraNo, String cameraTitle, String snapshotUrl, Boolean isOnline,int shopId) { this.cameraSns = cameraSns; this.cameraTitle = cameraTitle; this.snapshotUrl = snapshotUrl; this.online = isOnline; this.cameraNo = cameraNo; this.cameraId = cameraId; this.shopId = shopId; } public String getCameraSns() { return cameraSns; } public void setCameraSns(String cameraSns) { this.cameraSns = cameraSns; } public String getCameraTitle() { return cameraTitle; } public void setCameraTitle(String cameraTitle) { this.cameraTitle = cameraTitle; } public String getSnapshotUrl() { return snapshotUrl; } public void setSnapshotUrl(String snapshotUrl) { this.snapshotUrl = snapshotUrl; } public Boolean getOnline() { return online; } public int getCameraId() { return cameraId; } public void setCameraId(int cameraId) { this.cameraId = cameraId; } public int getShopId() { return shopId; } public void setShopId(int shopId) { this.shopId = shopId; } public void setCameraNo(int cameraNo) { this.cameraNo = cameraNo; } public void setOnline(Boolean online) { this.online = online; } public int getCameraNo() { return cameraNo; } public void getCameraNo(int cameraNo) { this.cameraNo = cameraNo; } }
22.080808
139
0.587832
8df123a872620eeb44da3f9bb005a4a171f6cb46
6,861
/******************************************************************************* * Copyright 2014 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * 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 gov.nasa.ensemble.core.rcp; import gov.nasa.ensemble.common.CommonPlugin; import gov.nasa.ensemble.common.EnsembleProperties; import gov.nasa.ensemble.common.authentication.AuthenticationUtil; import gov.nasa.ensemble.common.authentication.Authenticator; import gov.nasa.ensemble.common.extension.DynamicExtensionUtils; import gov.nasa.ensemble.common.mission.MissionExtender; import gov.nasa.ensemble.common.mission.MissionExtender.ConstructionException; import java.net.PasswordAuthentication; import java.util.Properties; import org.apache.http.auth.Credentials; import org.apache.log4j.Logger; import org.eclipse.core.runtime.Platform; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.swt.graphics.DeviceData; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.application.WorkbenchAdvisor; public class EnsembleApplication implements IApplication { private static final String APACHE_SERVER_USER_PROPERTY = "apache.server.user"; private static final String APACHE_SERVER_PASS_PROPERTY = "apache.server.pass"; private static Credentials credentials; Logger trace = Logger.getLogger(EnsembleApplication.class); @Override public Object start(IApplicationContext context) throws Exception { // // Comment out check until the missing // if (!checkWorkspaceLock(new Shell(PlatformUI.createDisplay(), SWT.ON_TOP))) { // Platform.endSplash(); // return IApplication.EXIT_OK; // } String productName = "Ensemble"; if (Platform.getProduct() != null) productName = Platform.getProduct().getName(); Display.setAppName(productName); Authenticator login = AuthenticationUtil.getAuthenticator(); boolean isAuthenticated = false; if (login != null) { // may need these credentials later credentials = login.getCredentials(); isAuthenticated = login.isAuthenticated(); } else { // Setup the authenticator that gets us through the password check on the website java.net.Authenticator.setDefault(new java.net.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { Properties properties = CommonPlugin.getDefault().getEnsembleProperties(); String user = properties.getProperty(APACHE_SERVER_USER_PROPERTY, ""); String pass = properties.getProperty(APACHE_SERVER_PASS_PROPERTY, ""); return new PasswordAuthentication(user, pass.toCharArray()); } }); isAuthenticated = true; } Display display = null; String sleakEnabled = EnsembleProperties.getProperty("sleak.enabled"); if (sleakEnabled != null && Boolean.valueOf(sleakEnabled)){ DeviceData data = new DeviceData(); data.tracking = true; display = new Display(data); Sleak sleak = new Sleak(); sleak.open(); } else { display = Display.getDefault(); } PlatformUI.createDisplay(); try { if (isAuthenticated) { WorkbenchAdvisor workbenchAdvisor; try { workbenchAdvisor = MissionExtender.construct(EnsembleWorkbenchAdvisor.class); } catch (ConstructionException e) { trace.warn("couldn't instantiate mission-specific EnsembleWorkbenchAdvisor"); workbenchAdvisor = new EnsembleWorkbenchAdvisor() { @Override public String getInitialWindowPerspectiveId() { return null; } }; } DynamicExtensionUtils.removeIgnoredExtensions(); int returnCode = PlatformUI.createAndRunWorkbench(display, workbenchAdvisor); if (returnCode == PlatformUI.RETURN_RESTART) { return IApplication.EXIT_RESTART; } return IApplication.EXIT_OK; } // authentication failed context.applicationRunning(); return IApplication.EXIT_OK; } finally { display.dispose(); } } // protected boolean checkWorkspaceLock(Shell shell) { // Location workspaceLocation = Platform.getInstanceLocation(); // IOException exception = null; // try { // if (workspaceLocation.lock()) { // return true; // } // } catch (IOException e) { // exception = e; // } // String appName = Platform.getProduct().getName(); // String message = appName + " cannot be started while another instance is running. Switch to the running instance or close it and restart the application again"; // if (exception != null) { // trace.error(message, exception); // dumpFrameworkProperties(); // MessageDialog.openInformation(shell, "Cannot start " + appName, exception.getMessage()); // } else { // MessageDialog.openInformation(shell, "Cannot start " + appName, message); // } // return false; // } // // @SuppressWarnings("restriction") // private void dumpFrameworkProperties() { // Properties properties = FrameworkProperties.getProperties(); // int maxKeyLength = 0; // for (Object key : properties.keySet()) { // maxKeyLength = Math.max(key.toString().length(), maxKeyLength); // } // // for (Object key : properties.keySet()) { // int keyLength = key.toString().length(); // StringBuffer buffer = new StringBuffer(); // buffer.append(key); // for (int i=0; i<maxKeyLength - keyLength; i++) { // buffer.append(' '); // } // String value = properties.getProperty((String) key); // System.out.println(buffer.toString()+'|'+value); // } // } @Override public void stop() { // Location workspaceLocation = Platform.getInstanceLocation(); // workspaceLocation.release(); final IWorkbench workbench; try { workbench = PlatformUI.getWorkbench(); } catch (IllegalStateException e) { // already done (or not started) return; } final Display display = workbench.getDisplay(); if (!display.isDisposed()) { display.syncExec(new Runnable() { @Override public void run() { if (!display.isDisposed()) { workbench.close(); } } }); } } /** * * @return The master username/password key */ public static Credentials getCredentials() { return credentials; } }
34.134328
164
0.707186
9917878eb7b8d37716372a12963e1db64dddc14a
1,398
package com.wutong.weixin.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * @author wutong * @date 2018/4/27 */ @Data @EqualsAndHashCode(callSuper = false) @AllArgsConstructor @NoArgsConstructor @ApiModel(description = "获取微信用户信息并更新") public class UserInfoModel { @ApiModelProperty(required = true , value = "头像url地址",position = 10) @NotBlank(message = "{avatarUrl.notnull}") private String avatarUrl; @ApiModelProperty(required = true , value = "微信昵称",position = 11) @NotBlank(message = "{nickName.notnull}") private String nickName; @ApiModelProperty(required = true , value = "城市",position = 12) @NotBlank(message = "{city.notnull}") private String city; @ApiModelProperty(required = true , value = "国家",position = 14) @NotBlank(message = "{country.notnull}") private String country; @ApiModelProperty(required = true , value = "性别",position = 16) @NotNull(message = "{gender.notnull}") private Integer gender; @ApiModelProperty(required = true , value = "省份",position = 18) @NotBlank(message = "{province.notnull}") private String province; }
29.744681
72
0.722461
8b13e92b7b81102fddfe8b7e03735eab105034e2
3,528
package com.paypal.sellers.bankaccountextract.service.impl; import com.hyperwallet.clientsdk.model.HyperwalletBankAccount; import com.mirakl.client.core.exception.MiraklApiException; import com.mirakl.client.mmp.operator.core.MiraklMarketplacePlatformOperatorApiClient; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShop; import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdatedShops; import com.mirakl.client.mmp.operator.request.shop.MiraklUpdateShopsRequest; import com.mirakl.client.mmp.request.additionalfield.MiraklRequestAdditionalFieldValue; import com.paypal.infrastructure.mail.MailNotificationUtil; import com.paypal.sellers.bankaccountextract.service.MiraklBankAccountExtractService; import com.paypal.sellers.infrastructure.utils.MiraklLoggingErrorsUtil; import com.paypal.sellers.sellersextract.model.SellerModel; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.builder.ToStringBuilder; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import static com.paypal.sellers.sellersextract.model.SellerModelConstants.HYPERWALLET_BANK_ACCOUNT_TOKEN; @Slf4j @Service public class MiraklBankAccountExtractServiceImpl implements MiraklBankAccountExtractService { private final MiraklMarketplacePlatformOperatorApiClient miraklOperatorClient; private final MailNotificationUtil sellerMailNotificationUtil; private static final String ERROR_MESSAGE_PREFIX = "There was an error, please check the logs for further " + "information:\n"; public MiraklBankAccountExtractServiceImpl(final MiraklMarketplacePlatformOperatorApiClient miraklOperatorClient, final MailNotificationUtil sellerMailNotificationUtil) { this.miraklOperatorClient = miraklOperatorClient; this.sellerMailNotificationUtil = sellerMailNotificationUtil; } /** * {@inheritDoc} */ @Override public void updateBankAccountToken(final SellerModel sellerModel, final HyperwalletBankAccount hyperwalletBankAccount) { final MiraklUpdateShop miraklUpdateShop = new MiraklUpdateShop(); final String shopId = sellerModel.getClientUserId(); miraklUpdateShop.setShopId(Long.valueOf(shopId)); final var userTokenCustomField = new MiraklRequestAdditionalFieldValue.MiraklSimpleRequestAdditionalFieldValue(); userTokenCustomField.setCode(HYPERWALLET_BANK_ACCOUNT_TOKEN); userTokenCustomField.setValue(hyperwalletBankAccount.getToken()); miraklUpdateShop.setAdditionalFieldValues(List.of(userTokenCustomField)); final MiraklUpdateShopsRequest request = new MiraklUpdateShopsRequest(List.of(miraklUpdateShop)); log.debug("Mirakl Update shop request: [{}]", ToStringBuilder.reflectionToString(request)); log.info("Updating bank account token for shop [{}]", shopId); try { final MiraklUpdatedShops miraklUpdatedShops = miraklOperatorClient.updateShops(request); Optional.ofNullable(miraklUpdatedShops) .ifPresent(miraklUpdatedShopsResponse -> log.debug("Mirakl Update shop response: [{}]", ToStringBuilder.reflectionToString(miraklUpdatedShops))); log.info("Bank account token updated for shop [{}]", shopId); } catch (final MiraklApiException ex) { log.error("Something went wrong updating information of shop [{}]", shopId); sellerMailNotificationUtil.sendPlainTextEmail("Issue detected updating bank token in Mirakl", String.format(ERROR_MESSAGE_PREFIX + "Something went wrong updating bank token of shop [%s]%n%s", shopId, MiraklLoggingErrorsUtil.stringify(ex))); } } }
48.328767
115
0.827664
86ec35d9928504e83cc81709573116718aa36c70
7,491
package org.sagebionetworks.bridge.models.upload; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.google.common.collect.ImmutableList; import nl.jqno.equalsverifier.EqualsVerifier; import org.testng.annotations.Test; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.json.JsonUtils; @SuppressWarnings("ConstantConditions") public class UploadFieldDefinitionTest { @Test public void testBuilder() { UploadFieldDefinition fieldDef = new UploadFieldDefinition.Builder().withName("test-field") .withType(UploadFieldType.ATTACHMENT_BLOB).build(); assertEquals(fieldDef.getName(), "test-field"); assertTrue(fieldDef.isRequired()); assertEquals(fieldDef.getType(), UploadFieldType.ATTACHMENT_BLOB); } @Test public void testRequiredTrue() { UploadFieldDefinition fieldDef = new UploadFieldDefinition.Builder().withName("test-field") .withRequired(true).withType(UploadFieldType.ATTACHMENT_BLOB).build(); assertEquals(fieldDef.getName(), "test-field"); assertTrue(fieldDef.isRequired()); assertEquals(fieldDef.getType(), UploadFieldType.ATTACHMENT_BLOB); } @Test public void testRequiredFalse() { UploadFieldDefinition fieldDef = new UploadFieldDefinition.Builder().withName("test-field") .withRequired(false).withType(UploadFieldType.ATTACHMENT_BLOB).build(); assertEquals(fieldDef.getName(), "test-field"); assertFalse(fieldDef.isRequired()); assertEquals(fieldDef.getType(), UploadFieldType.ATTACHMENT_BLOB); } @Test public void testMultiChoiceAnswerList() { // set up original list List<String> originalAnswerList = new ArrayList<>(); originalAnswerList.add("first"); originalAnswerList.add("second"); // build and validate List<String> expectedAnswerList = ImmutableList.of("first", "second"); UploadFieldDefinition fieldDef = new UploadFieldDefinition.Builder().withName("multi-choice-field") .withType(UploadFieldType.MULTI_CHOICE).withMultiChoiceAnswerList(originalAnswerList).build(); assertEquals(fieldDef.getMultiChoiceAnswerList(), expectedAnswerList); // modify original list, verify that field def stays the same originalAnswerList.add("third"); assertEquals(fieldDef.getMultiChoiceAnswerList(), expectedAnswerList); } @Test public void testMultiChoiceAnswerVarargs() { UploadFieldDefinition fieldDef = new UploadFieldDefinition.Builder().withName("multi-choice-field") .withType(UploadFieldType.MULTI_CHOICE).withMultiChoiceAnswerList("aa", "bb", "cc").build(); assertEquals(fieldDef.getMultiChoiceAnswerList(), ImmutableList.of("aa", "bb", "cc")); } @Test public void testMultiChoiceAnswerListNull() { // Fields that are not multi_choice usually won't specify this, but we expect it to be, by default, an empty // list instead of a null list. UploadFieldDefinition fieldDef1 = new UploadFieldDefinition.Builder().withName("test-field") .withType(UploadFieldType.INT).build(); assertTrue(fieldDef1.getMultiChoiceAnswerList().isEmpty()); // Explicitly set it to null, and it still comes up as an empty list. UploadFieldDefinition fieldDef2 = new UploadFieldDefinition.Builder().withName("test-field") .withType(UploadFieldType.INT).withMultiChoiceAnswerList((List<String>) null).build(); assertTrue(fieldDef2.getMultiChoiceAnswerList().isEmpty()); } @Test public void testOptionalFields() { List<String> multiChoiceAnswerList = ImmutableList.of("foo", "bar", "baz"); UploadFieldDefinition fieldDef = new UploadFieldDefinition.Builder().withAllowOtherChoices(true) .withFileExtension(".test").withMimeType("text/plain") .withMaxLength(128).withMultiChoiceAnswerList(multiChoiceAnswerList).withName("optional-stuff") .withRequired(false).withType(UploadFieldType.STRING).withUnboundedText(true).build(); assertTrue(fieldDef.getAllowOtherChoices()); assertEquals(fieldDef.getFileExtension(), ".test"); assertEquals(fieldDef.getMimeType(), "text/plain"); assertEquals(fieldDef.getMaxLength().intValue(), 128); assertEquals(fieldDef.getMultiChoiceAnswerList(), multiChoiceAnswerList); assertEquals(fieldDef.getName(), "optional-stuff"); assertFalse(fieldDef.isRequired()); assertEquals(fieldDef.getType(), UploadFieldType.STRING); assertTrue(fieldDef.isUnboundedText()); // Also test copy constructor. UploadFieldDefinition copy = new UploadFieldDefinition.Builder().copyOf(fieldDef).build(); assertEquals(copy, fieldDef); } @Test public void testSerialization() throws Exception { // start with JSON String jsonText = "{\n" + " \"allowOtherChoices\":true,\n" + " \"fileExtension\":\".json\",\n" + " \"mimeType\":\"text/json\",\n" + " \"maxLength\":24,\n" + " \"multiChoiceAnswerList\":[\"asdf\", \"jkl\"],\n" + " \"name\":\"test-field\",\n" + " \"required\":false,\n" + " \"type\":\"INT\",\n" + " \"unboundedText\":true\n" + "}"; // convert to POJO List<String> expectedMultiChoiceAnswerList = ImmutableList.of("asdf", "jkl"); UploadFieldDefinition fieldDef = BridgeObjectMapper.get().readValue(jsonText, UploadFieldDefinition.class); assertTrue(fieldDef.getAllowOtherChoices()); assertEquals(fieldDef.getFileExtension(), ".json"); assertEquals(fieldDef.getMimeType(), "text/json"); assertEquals(fieldDef.getMaxLength().intValue(), 24); assertEquals(fieldDef.getMultiChoiceAnswerList(), expectedMultiChoiceAnswerList); assertEquals(fieldDef.getName(), "test-field"); assertFalse(fieldDef.isRequired()); assertEquals(fieldDef.getType(), UploadFieldType.INT); assertTrue(fieldDef.isUnboundedText()); // convert back to JSON String convertedJson = BridgeObjectMapper.get().writeValueAsString(fieldDef); // then convert to a map so we can validate the raw JSON Map<String, Object> jsonMap = BridgeObjectMapper.get().readValue(convertedJson, JsonUtils.TYPE_REF_RAW_MAP); assertEquals(jsonMap.size(), 9); assertTrue((boolean) jsonMap.get("allowOtherChoices")); assertEquals(jsonMap.get("fileExtension"), ".json"); assertEquals(jsonMap.get("mimeType"), "text/json"); assertEquals(jsonMap.get("maxLength"), 24); assertEquals(jsonMap.get("multiChoiceAnswerList"), expectedMultiChoiceAnswerList); assertEquals(jsonMap.get("name"), "test-field"); assertFalse((boolean) jsonMap.get("required")); assertEquals(jsonMap.get("type"), "int"); assertTrue((boolean) jsonMap.get("unboundedText")); } @Test public void equalsVerifier() { EqualsVerifier.forClass(UploadFieldDefinition.class).allFieldsShouldBeUsed().verify(); } }
46.81875
116
0.678014
be07b99236f7e444b68319707b8acfd73558acff
6,171
package com.github.zywx.xzh.http; import java.io.File; import java.io.IOException; import java.util.Map.Entry; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; /** * http 工具类 * * @author fsnail.wang@gmail.com * @date 2018/3/14 上午10:15 */ public class XzhHttpClient { private static Logger LOGGER = Logger.getLogger(XzhHttpClient.class); private static final String ENCODING = "utf-8"; /** * post curl * * @param request 请求实体 * @return 响应实体 */ public static XzhResponse post(XzhRequest request) { XzhResponse xzhResponse = null; try { String url; xzhResponse = new XzhResponse(); if (request.getParams().isEmpty()) { url = request.getUri().toString(); } else { url = String.format("%s?%s", request.getUri().toString(), request.getParamStr()); } String result = ""; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); int timeout = request.getConfig().getSocketTimeoutMillis(); int connTime = request.getConfig().getConnectionTimeoutMillis(); RequestConfig.Builder custom = RequestConfig.custom(); RequestConfig requestConfig = custom.setSocketTimeout(timeout).setConnectTimeout(connTime).build(); httpPost.setConfig(requestConfig); if (request.getHeaders() != null) { for (Entry<String, String> entry : request.getHeaders().entrySet()) { httpPost.setHeader(entry.getKey(), entry.getValue()); } } // 参数处理并放到请求对象中 if (request.getBodyFormat().equals(BodyFormatEnum.FORM_KV)) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); if (request.getFormParams() != null) { for (Entry<String, Object> entry : request.getFormParams().entrySet()) { String paramKey = entry.getKey(); Object value = entry.getValue(); if (value instanceof File) { FileBody fileBody = new FileBody((File) value); builder.addPart(paramKey, fileBody); } else { StringBody name = new StringBody(value.toString(), ContentType.TEXT_PLAIN.withCharset(ENCODING)); builder.addPart(paramKey, name); } } } HttpEntity entity = builder.build(); httpPost.setEntity(entity); } else if (request.getBodyFormat().equals(BodyFormatEnum.RAW_JSON)) { httpPost.setEntity(new StringEntity(request.getBodyStr())); } // 发送请求,获取结果(同步阻塞) CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity, ENCODING); } EntityUtils.consume(entity); int statusCode = response.getStatusLine().getStatusCode(); xzhResponse.setStatus(statusCode); xzhResponse.setBody(result); response.close(); } catch (IOException e) { LOGGER.error(e); } return xzhResponse; } /** * get curl * * @param request 请求实体 * @return 响应实体 */ public static XzhResponse get(XzhRequest request) { XzhResponse xzhResponse = null; try { String url; xzhResponse = new XzhResponse(); if (request.getParams().isEmpty()) { url = request.getUri().toString(); } else { url = String.format("%s?%s", request.getUri().toString(), request.getParamStr()); } String result = ""; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); // 设置请求和传输超时时间 int timeout = request.getConfig().getSocketTimeoutMillis(); int connTime = request.getConfig().getConnectionTimeoutMillis(); RequestConfig.Builder custom = RequestConfig.custom(); RequestConfig requestConfig = custom.setSocketTimeout(timeout).setConnectTimeout(connTime).build(); httpGet.setConfig(requestConfig); if (request.getHeaders() != null) { for (Entry<String, String> entry : request.getHeaders().entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); } } CloseableHttpResponse response = httpClient.execute(httpGet); // 获取结果实体 HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity, ENCODING); } EntityUtils.consume(entity); int statusCode = response.getStatusLine().getStatusCode(); xzhResponse.setStatus(statusCode); xzhResponse.setBody(result); response.close(); } catch (IOException e) { LOGGER.error(e); } return xzhResponse; } }
38.811321
111
0.586291
33ee632c1d42e5b3d76052f64924e670caf71fa5
542
package gov.hhs.onc.dcdt.crypto.certs; import gov.hhs.onc.dcdt.crypto.CryptographyException; public class CertificateException extends CryptographyException { private final static long serialVersionUID = 0L; public CertificateException() { super(); } public CertificateException(Throwable cause) { super(cause); } public CertificateException(String message) { super(message); } public CertificateException(String message, Throwable cause) { super(message, cause); } }
22.583333
66
0.697417
2ae6bedde9002ed2790b5a89edd2d7d132fa5af6
1,174
package com.github.dynamicextensionsalfresco.gradle.internal; import com.github.dynamicextensionsalfresco.gradle.internal.rest.RestClient; import com.github.dynamicextensionsalfresco.gradle.internal.rest.RestClientOptions; import com.github.dynamicextensionsalfresco.gradle.internal.rest.RestClientPostFileOptions; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; /** * Client for performing operations against the REST API */ public class BundleService { private final RestClient client; private String apiPath; public BundleService(RestClient client) { this(client, "/dynamic-extensions/api"); } public BundleService(RestClient client, String apiPath) { this.client = client; this.apiPath = apiPath; } public Object installBundle(File file) throws IOException { if (!file.exists()) { throw new FileNotFoundException(file.getPath()); } if(!file.getName().endsWith(".jar")) { throw new IllegalArgumentException("Not a JAR file: "+file.getAbsolutePath()); } return client.postFile(new RestClientPostFileOptions(new RestClientOptions(apiPath+"/bundles", "application/java-archive"), file)); } }
30.894737
133
0.778535
416bf034c7ee040f337b009d03c041891aad5695
2,443
package org.asciidoctor.extension; import java.util.List; import org.asciidoctor.internal.RubyObjectWrapper; import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyClass; import org.jruby.runtime.builtin.IRubyObject; public class ReaderImpl extends RubyObjectWrapper implements Reader { public ReaderImpl(IRubyObject rubyNode) { super(rubyNode); } static ReaderImpl createReader(Ruby runtime, List<String> lines) { RubyArray rubyLines = runtime.newArray(lines.size()); for (String line : lines) { rubyLines.add(runtime.newString(line)); } RubyClass readerClass = runtime.getModule("Asciidoctor").getClass("Reader"); return new ReaderImpl(readerClass.callMethod("new", rubyLines)); } @Override @Deprecated public int getLineno() { return getLineNumber(); } @Override public int getLineNumber() { return getInt("lineno"); } public String getFile() { IRubyObject rObj = getRubyProperty("file"); return rObj.toString(); } public String getDir() { IRubyObject rObj = getRubyProperty("dir"); return rObj.toString(); } @Override public boolean hasMoreLines() { return getBoolean("has_more_lines?"); } @Override public boolean isNextLineEmpty() { return getBoolean("next_line_empty?"); } @Override public String read() { return getString("read"); } @Override public List<String> readLines() { return getList("read_lines", String.class); } @Override public String readLine() { return getString("read_line"); } @Override public List<String> lines() { return getList("lines", String.class); } @Override public void restoreLine(String line) { getRubyProperty("unshift_line", line); } @Override public void restoreLines(List<String> lines) { getRubyProperty("unshift_lines", lines); } @Override public String peekLine() { return getString("peek_line"); } @Override public List<String> peekLines(int lineCount) { return getList("peek_lines", String.class, lineCount); } @Override public boolean advance() { return getBoolean("advance"); } @Override public void terminate() { getRubyProperty("terminate"); } }
22.412844
84
0.633238
9d436577b63e12541231297d5dbbacaab4e8e570
3,135
/* ~~ The OpenProjectFiles is part of BusinessProfit. ~~ * * The BusinessProfit's classes and any part of the code * cannot be copied/distributed without * the permission of Sotiris Doudis * * Github - RiflemanSD - https://github.com/RiflemanSD * * Copyright © 2016 Sotiris Doudis | All rights reserved * * License for BusinessProfit project - in GREEK language * * Οποιοσδήποτε μπορεί να χρησιμοποιήσει το πρόγραμμα για προσωπική του χρήση. * Αλλά απαγoρεύεται η πώληση ή διακίνηση του προγράμματος σε τρίτους. * * Aπαγορεύεται η αντιγραφή ή διακίνηση οποιοδήποτε μέρος του κώδικα χωρίς * την άδεια του δημιουργού. * Σε περίπτωση που θέλετε να χρεισημοποιήσετε κάποια κλάση ή μέρος του κώδικα. * Πρέπει να συμπεριλάβεται στο header της κλάσης τον δημιουργό και link στην * αυθεντική κλάση (στο github). * * ~~ Information about BusinessProfit project - in GREEK language ~~ * * Το BusinessProfit είναι ένα project για την αποθήκευση και επεξεργασία * των εσόδων/εξόδων μίας επιχείρησης με σκοπό να μπορεί ο επιχειρηματίας να καθορήσει * το καθαρό κέρδος της επιχείρησης. Καθώς και να κρατάει κάποια σημαντικά * στατιστικά στοιχεία για τον όγκο της εργασίας κτλ.. * * Το project δημιουργήθηκε από τον Σωτήρη Δούδη. Φοιτητή πληροφορικής του Α.Π.Θ * για προσωπική χρήση. Αλλά και για όποιον άλλον πιθανόν το χρειαστεί. * * Το project προγραμματίστηκε σε Java (https://www.java.com/en/download/). * Με χρήση του NetBeans IDE (https://netbeans.org/) * Για να το τρέξετε πρέπει να έχετε εγκαταστήσει την java. * * Ο καθένας μπορεί δωρεάν να χρησιμοποιήσει το project αυτό. Αλλά δεν επιτρέπεται * η αντιγραφή/διακήνηση του κώδικα, χωρίς την άδεια του Δημιουργού (Δείτε την License). * * Github - https://github.com/RiflemanSD/BusinessProfit * * * Copyright © 2016 Sotiris Doudis | All rights reserved */ package org.riflemansd.businessprofit.utils.autoupv; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** <h1>OpenProjectFiles</h1> * * <p></p> * * <p>Last Update: 30/01/2016</p> * <p>Author: <a href=https://github.com/RiflemanSD>RiflemanSD</a></p> * * <p>Copyright © 2016 Sotiris Doudis | All rights reserved</p> * * @version 1.0.7 * @author RiflemanSD */ public class OpenProjectFiles { /* java -Xmx2048M -Xms2048M -jar TableExamples.jar PAUSE */ public static void main(String[] args) { try { Desktop.getDesktop().open((new File("src")).getAbsoluteFile().getParentFile()); } catch (IOException ex) { Logger.getLogger(OpenProjectFiles.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("End..."); } public static void openFile(String fileName) { try { Desktop.getDesktop().open(new File(fileName)); } catch (IOException ex) { Logger.getLogger(OpenProjectFiles.class.getName()).log(Level.SEVERE, null, ex); } } }
35.224719
92
0.681659
0df3d7d7921c8768dd3a2f49754e43c06185386c
6,521
package com.xzhou.book.net; import com.xzhou.book.MyApp; import com.xzhou.book.models.Entities; import com.xzhou.book.models.HtmlParse; import com.xzhou.book.models.HtmlParseFactory; import com.xzhou.book.models.SearchModel; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * File Description: * Author: zhouxian * Create Date: 20-5-9 * Change List: */ public class AutoParseNetBook { private static final ExecutorService sPool = Executors.newCachedThreadPool(); private static boolean sIsParsing; private static List<Integer> sParseTypeList; private static final List<Callback> sCallbacks = new ArrayList<>(); private static ItemCallback sItemCallback; public static void stopParse() { sIsParsing = false; } public interface Callback { void onParseState(boolean state, boolean success, String message); } public interface ItemCallback { void onParseState(SearchModel.SearchBook book); } public static void setItemCallback(ItemCallback callback) { sItemCallback = callback; } public static void addCallback(Callback callback) { if (!sCallbacks.contains(callback)) { sCallbacks.add(callback); } } public static void removeCallback(Callback callback) { sCallbacks.remove(callback); } private static void notifyCallback(final boolean state, final boolean success, final String message) { MyApp.runUI(new Runnable() { @Override public void run() { for (Callback callback : sCallbacks) { callback.onParseState(state, success, message); } } }); } public static void tryParseBook(final SearchModel.SearchBook searchBook) { searchBook.isParsing = true; if (sItemCallback != null) { sItemCallback.onParseState(searchBook); } sPool.execute(() -> { if (sParseTypeList == null) { sParseTypeList = new ArrayList<>(6); sParseTypeList.add(SearchModel.ParseType.PARSE_TYPE_1); sParseTypeList.add(SearchModel.ParseType.PARSE_TYPE_2); sParseTypeList.add(SearchModel.ParseType.PARSE_TYPE_3); sParseTypeList.add(SearchModel.ParseType.PARSE_TYPE_4); sParseTypeList.add(SearchModel.ParseType.PARSE_TYPE_5); sParseTypeList.add(SearchModel.ParseType.PARSE_TYPE_6); } boolean success = false; for (int type : sParseTypeList) { HtmlParse parse = HtmlParseFactory.getHtmlParse(type); if (parse != null) { List<Entities.Chapters> list = parse.parseChapters(searchBook.readUrl); if (list != null && list.size() > 0) { Entities.Chapters chapters = list.get(0); Entities.ChapterRead read = parse.parseChapterRead(chapters.link); if (read != null && read.chapter != null && read.chapter.body != null && read.chapter.body.length() > 200) { SearchModel.HostType hostType = new SearchModel.HostType(); hostType.host = searchBook.sourceHost; hostType.parseType = type; SearchModel.saveHostType(hostType); success = true; break; } } } } searchBook.parseText = success ? "解析成功" : "解析失败"; searchBook.isParsing = false; if (sItemCallback != null) { sItemCallback.onParseState(searchBook); } }); } public static void tryParseBook(final String bookName, final String readUrl, final String sourceHost) { sIsParsing = true; notifyCallback(true, false, "解析《" + bookName + "》(" + sourceHost + ")"); sPool.execute(new Runnable() { @Override public void run() { if (sParseTypeList == null) { sParseTypeList = new ArrayList<>(6); sParseTypeList.add(SearchModel.ParseType.PARSE_TYPE_1); sParseTypeList.add(SearchModel.ParseType.PARSE_TYPE_2); sParseTypeList.add(SearchModel.ParseType.PARSE_TYPE_3); sParseTypeList.add(SearchModel.ParseType.PARSE_TYPE_4); sParseTypeList.add(SearchModel.ParseType.PARSE_TYPE_5); sParseTypeList.add(SearchModel.ParseType.PARSE_TYPE_6); } boolean success = false; for (int type : sParseTypeList) { if (!sIsParsing) { break; } HtmlParse parse = HtmlParseFactory.getHtmlParse(type); if (parse != null) { List<Entities.Chapters> list = parse.parseChapters(readUrl); if (list != null && list.size() > 0) { Entities.Chapters chapters = list.get(0); if (!sIsParsing) { break; } Entities.ChapterRead read = parse.parseChapterRead(chapters.link); if (read != null && read.chapter != null && read.chapter.body != null && read.chapter.body.length() > 200) { success = true; SearchModel.HostType hostType = new SearchModel.HostType(); hostType.host = sourceHost; hostType.parseType = type; SearchModel.saveHostType(hostType); break; } } } } String msg; if (!sIsParsing && !success) { msg = "解析中断"; } else if (success) { msg = "解析成功"; } else { msg = "解析失败,该书籍暂不支持本地阅读"; } notifyCallback(false, success, msg); } }); } }
39.762195
107
0.527066
fc20aaeee110cb869416a246f4f50beb7ab05ab3
23,789
package io.toolisticon.aptk.tools; import io.toolisticon.aptk.tools.annotationutilstestclasses.ClassArrayAttributeAnnotation; import io.toolisticon.aptk.tools.annotationutilstestclasses.ClassAttributeAnnotation; import io.toolisticon.aptk.tools.annotationutilstestclasses.DefaultValueAnnotation; import io.toolisticon.aptk.tools.annotationutilstestclasses.NoAttributeAnnotation; import io.toolisticon.aptk.tools.corematcher.AptkCoreMatchers; import io.toolisticon.aptk.tools.fluentfilter.FluentElementFilter; import io.toolisticon.cute.CompileTestBuilder; import io.toolisticon.cute.JavaFileObjectUtils; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import java.util.Arrays; import java.util.List; /** * Integration test for {@link ElementUtils}. * <p/> * Test is executed at compile time of a test class. */ public class AnnotationUtilsTest { private CompileTestBuilder.UnitTestBuilder unitTestBuilder = CompileTestBuilder .unitTest() .useSource(JavaFileObjectUtils.readFromResource("/AnnotationClassAttributeTestClass.java")); @Before public void init() { MessagerUtils.setPrintMessageCodes(true); } // ----------------------------------- // Single class attribute // ----------------------------------- @Test public void annotationUtilsTest_classAttribute_emptyValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(AptkCoreMatchers.BY_ANNOTATION).filterByAllOf(ClassAttributeAnnotation.class) .applyFilter(AptkCoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(AptkCoreMatchers.BY_NAME).filterByOneOf("test_classAttribute_empty") .getResult().get(0); // shouldn't find nonexisting MatcherAssert.assertThat(AnnotationUtils.getClassAttributeFromAnnotationAsFqn(testElement, ClassAttributeAnnotation.class), Matchers.nullValue()); } }) .compilationShouldSucceed() .executeTest(); } @Test public void annotationUtilsTest_classAttribute_StringClassValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(AptkCoreMatchers.BY_ANNOTATION).filterByAllOf(ClassAttributeAnnotation.class) .applyFilter(AptkCoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(AptkCoreMatchers.BY_NAME).filterByOneOf("test_classAttribute_atDefaultValue") .getResult().get(0); // shouldn't find nonexisting MatcherAssert.assertThat(AnnotationUtils.getClassAttributeFromAnnotationAsFqn(testElement, ClassAttributeAnnotation.class), Matchers.equalTo(String.class.getCanonicalName())); } }) .compilationShouldSucceed() .executeTest(); } @Test public void annotationUtilsTest_classAttributeWithExplicitAttributeName_LongClassValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(AptkCoreMatchers.BY_ANNOTATION).filterByAllOf(ClassAttributeAnnotation.class) .applyFilter(AptkCoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(AptkCoreMatchers.BY_NAME).filterByOneOf("test_classAttribute_atNamedAttribute") .getResult().get(0); // shouldn't find nonexisting MatcherAssert.assertThat(AnnotationUtils.getClassAttributeFromAnnotationAsFqn(testElement, ClassAttributeAnnotation.class, "classAttribute"), Matchers.equalTo(Long.class.getCanonicalName())); } }) .compilationShouldSucceed() .executeTest(); } // ----------------------------------- // array class attribute // ----------------------------------- @Test public void annotationUtilsTest_arrayClassAttribute_emptyValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(AptkCoreMatchers.BY_ANNOTATION).filterByAllOf(ClassArrayAttributeAnnotation.class) .applyFilter(AptkCoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(AptkCoreMatchers.BY_NAME).filterByOneOf("test_classArrayAttribute_empty") .getResult().get(0); // shouldn't find nonexisting MatcherAssert.assertThat(AnnotationUtils.getClassArrayAttributeFromAnnotationAsFqn(testElement, ClassArrayAttributeAnnotation.class), Matchers.arrayWithSize(0)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void annotationUtilsTest_arrayClassAttribute_StringDoubleFloatValues() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(AptkCoreMatchers.BY_ANNOTATION).filterByAllOf(ClassArrayAttributeAnnotation.class) .applyFilter(AptkCoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(AptkCoreMatchers.BY_NAME).filterByOneOf("test_classArrayAttribute_atDefaultValue") .getResult().get(0); // shouldn't find nonexisting MatcherAssert.assertThat(Arrays.asList(AnnotationUtils.getClassArrayAttributeFromAnnotationAsFqn(testElement, ClassArrayAttributeAnnotation.class)), Matchers.contains(String.class.getCanonicalName(), Double.class.getCanonicalName(), Float.class.getCanonicalName())); } }) .compilationShouldSucceed() .executeTest(); } @Test public void annotationUtilsTest_arrayClassAttributeWithExplicitAttributeName_LongIntegerValues() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(AptkCoreMatchers.BY_ANNOTATION).filterByAllOf(ClassArrayAttributeAnnotation.class) .applyFilter(AptkCoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(AptkCoreMatchers.BY_NAME).filterByOneOf("test_classArrayAttribute_atNamedAttribute") .getResult().get(0); // shouldn't find nonexisting MatcherAssert.assertThat(Arrays.asList(AnnotationUtils.getClassArrayAttributeFromAnnotationAsFqn(testElement, ClassArrayAttributeAnnotation.class, "classArrayAttribute")), Matchers.contains(Long.class.getCanonicalName(), Integer.class.getCanonicalName())); } }) .compilationShouldSucceed() .executeTest(); } @Test public void annotationUtilsTest_arrayClassAttributeWithExplicitAttributeName_LongIntegerAnnotationClassAttributeTestClassValues() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(AptkCoreMatchers.BY_ANNOTATION).filterByAllOf(ClassArrayAttributeAnnotation.class) .applyFilter(AptkCoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(AptkCoreMatchers.BY_NAME).filterByOneOf("test_classArrayAttribute_atNamedAttribute_withUncompiledClass") .getResult().get(0); // shouldn't find nonexisting MatcherAssert.assertThat(Arrays.asList(AnnotationUtils.getClassArrayAttributeFromAnnotationAsFqn(testElement, ClassArrayAttributeAnnotation.class, "classArrayAttribute")), Matchers.contains(Long.class.getCanonicalName(), Integer.class.getCanonicalName(), "io.toolisticon.annotationprocessor.AnnotationClassAttributeTestClass")); } }) .compilationShouldSucceed() .executeTest(); } // -------------------------------------------- // -- getAnnotationValueOfAttribute // -------------------------------------------- @Test public void annotationUtilsTest_getAnnotationValueOfAttribute_getImplicitlySetAnnotationValueMustReturnNull() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { // precondition AnnotationMirror annotationMirror = AnnotationUtils.getAnnotationMirror(element, DefaultValueAnnotation.class); MatcherAssert.assertThat(annotationMirror, Matchers.notNullValue()); // test AnnotationValue value = AnnotationUtils.getAnnotationValueOfAttribute(annotationMirror); // shouldn't find nonexisting MatcherAssert.assertThat(value, Matchers.nullValue()); } }) .compilationShouldSucceed() .executeTest(); } // -------------------------------------------- // -- getAnnotationValueOfAttributeWithDefaults // -------------------------------------------- @Test public void annotationUtilsTest_getAnnotationValueOfAttributeWithDefaults_getImplicitlySetAnnotationValue_defaultValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { // precondition AnnotationMirror annotationMirror = AnnotationUtils.getAnnotationMirror(element, DefaultValueAnnotation.class); MatcherAssert.assertThat(annotationMirror, Matchers.notNullValue()); // test AnnotationValue value = AnnotationUtils.getAnnotationValueOfAttributeWithDefaults(annotationMirror); // shouldn't find nonexisting MatcherAssert.assertThat((Long) value.getValue(), Matchers.is(5L)); } }) .compilationShouldSucceed() .executeTest(); } // -------------------------------------------- // -- getMandatoryAttributeValueNames // -------------------------------------------- @Test public void annotationUtilsTest_getMandatoryAttributeValueNames_getMandatoryAttributeValueNames() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { // precondition AnnotationMirror annotationMirror = AnnotationUtils.getAnnotationMirror(element, DefaultValueAnnotation.class); MatcherAssert.assertThat(annotationMirror, Matchers.notNullValue()); String[] names = AnnotationUtils.getMandatoryAttributeValueNames(annotationMirror); // shouldn't find nonexisting MatcherAssert.assertThat(Arrays.asList(names), Matchers.contains("mandatoryValue")); } }) .compilationShouldSucceed() .executeTest(); } // -------------------------------------------- // -- getOptionalAttributeValueNames // -------------------------------------------- @Test public void annotationUtilsTest_getOptionalAttributeValueNames_getOptionalAttributeValueNames() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { // precondition AnnotationMirror annotationMirror = AnnotationUtils.getAnnotationMirror(element, DefaultValueAnnotation.class); MatcherAssert.assertThat(annotationMirror, Matchers.notNullValue()); // test String[] names = AnnotationUtils.getOptionalAttributeValueNames(annotationMirror); // shouldn't find nonexisting MatcherAssert.assertThat(Arrays.asList(names), Matchers.contains("value")); } }) .compilationShouldSucceed() .executeTest(); } // -------------------------------------------- // -- getElementForAnnotationMirror // -------------------------------------------- @Test public void getElementForAnnotationMirror_getElement() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { // precondition AnnotationMirror annotationMirror = AnnotationUtils.getAnnotationMirror(element, DefaultValueAnnotation.class); MatcherAssert.assertThat(annotationMirror, Matchers.notNullValue()); // test TypeElement result = (TypeElement) AnnotationUtils.getElementForAnnotationMirror(annotationMirror); MatcherAssert.assertThat(result, Matchers.notNullValue()); MatcherAssert.assertThat(result.toString(), Matchers.is(DefaultValueAnnotation.class.getCanonicalName())); } }) .compilationShouldSucceed() .executeTest(); } // -------------------------------------------- // -- getClassAttributeFromAnnotationAsTypeMirror // -- and // -- getClassAttributeFromAnnotationAsFqn // -------------------------------------------- @ClassAttributeAnnotation(value = String.class, classAttribute = Long.class) static class ClassAttributeTestcase_WithCorrectClassAttribute { } @DefaultValueAnnotation(mandatoryValue = 3L) @NoAttributeAnnotation static class ClassAttributeTestcase_NonClassAttribute { } @Test public void getClassAttributeFromAnnotationAsTypeMirror_shouldGetClassAttributeSuccefully() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { // precondition TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(ClassAttributeTestcase_WithCorrectClassAttribute.class); MatcherAssert.assertThat("PRECONDITION : TypeElement must exist", typeElement, Matchers.notNullValue()); // test - for value TypeMirror result = AnnotationUtils.getClassAttributeFromAnnotationAsTypeMirror(typeElement, ClassAttributeAnnotation.class); MatcherAssert.assertThat(result, Matchers.notNullValue()); MatcherAssert.assertThat("Type must match String : ", TypeUtils.TypeComparison.isTypeEqual(result, String.class)); // test - for value result = AnnotationUtils.getClassAttributeFromAnnotationAsTypeMirror(typeElement, ClassAttributeAnnotation.class, "classAttribute"); MatcherAssert.assertThat(result, Matchers.notNullValue()); MatcherAssert.assertThat("Type must match Long : ", TypeUtils.TypeComparison.isTypeEqual(result, Long.class)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void getClassAttributeFromAnnotationAsTypeMirror_shouldReturnNullForNonMatchingClassAttributes() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { // precondition TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(ClassAttributeTestcase_WithCorrectClassAttribute.class); MatcherAssert.assertThat("PRECONDITION : TypeElement must exist", typeElement, Matchers.notNullValue()); // test - no class based attribute TypeMirror result = AnnotationUtils.getClassAttributeFromAnnotationAsTypeMirror(typeElement, DefaultValueAnnotation.class); MatcherAssert.assertThat(result, Matchers.nullValue()); // test - no class based attribute result = AnnotationUtils.getClassAttributeFromAnnotationAsTypeMirror(typeElement, DefaultValueAnnotation.class, "mandatoryValue"); MatcherAssert.assertThat(result, Matchers.nullValue()); // test - annotation not found result = AnnotationUtils.getClassAttributeFromAnnotationAsTypeMirror(typeElement, ClassArrayAttributeAnnotation.class); MatcherAssert.assertThat(result, Matchers.nullValue()); // test - annotation doesn't take attributes result = AnnotationUtils.getClassAttributeFromAnnotationAsTypeMirror(typeElement, NoAttributeAnnotation.class); MatcherAssert.assertThat(result, Matchers.nullValue()); } }) .compilationShouldSucceed() .executeTest(); } @Test public void getClassAttributeFromAnnotationAsFqn_shouldGetClassAttributeSuccefully() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { // precondition TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(ClassAttributeTestcase_WithCorrectClassAttribute.class); MatcherAssert.assertThat("PRECONDITION : TypeElement must exist", typeElement, Matchers.notNullValue()); // test - for value String result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(typeElement, ClassAttributeAnnotation.class); MatcherAssert.assertThat(result, Matchers.notNullValue()); MatcherAssert.assertThat("Type must match String : ", String.class.getCanonicalName().equals(result)); // test - for value result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(typeElement, ClassAttributeAnnotation.class, "classAttribute"); MatcherAssert.assertThat(result, Matchers.notNullValue()); MatcherAssert.assertThat("Type must match Long : ", Long.class.getCanonicalName().equals(result)); // test - for value result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(AnnotationUtils.getAnnotationMirror(typeElement, ClassAttributeAnnotation.class)); MatcherAssert.assertThat(result, Matchers.notNullValue()); MatcherAssert.assertThat("Type must match String : ", String.class.getCanonicalName().equals(result)); // test - for value result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(AnnotationUtils.getAnnotationMirror(typeElement, ClassAttributeAnnotation.class), "classAttribute"); MatcherAssert.assertThat(result, Matchers.notNullValue()); MatcherAssert.assertThat("Type must match Long : ", Long.class.getCanonicalName().equals(result)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void getClassAttributeFromAnnotationAsFqn_shouldReturnNullForNonMatchingClassAttributes() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { // precondition TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(ClassAttributeTestcase_WithCorrectClassAttribute.class); MatcherAssert.assertThat("PRECONDITION : TypeElement must exist", typeElement, Matchers.notNullValue()); // test - no class based attribute String result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(typeElement, DefaultValueAnnotation.class); MatcherAssert.assertThat(result, Matchers.nullValue()); // test - no class based attribute result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(typeElement, DefaultValueAnnotation.class, "mandatoryValue"); MatcherAssert.assertThat(result, Matchers.nullValue()); // test - annotation not found result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(typeElement, ClassArrayAttributeAnnotation.class); MatcherAssert.assertThat(result, Matchers.nullValue()); // test - annotation doesn't take attributes result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(typeElement, NoAttributeAnnotation.class); MatcherAssert.assertThat(result, Matchers.nullValue()); } }) .compilationShouldSucceed() .executeTest(); } }
44.217472
344
0.658372
f1245de9b2cc48308d0d11a0aac9d355b627bf8c
588
//,temp,WindowsSecureContainerExecutor.java,602,617,temp,WindowsSecureContainerExecutor.java,573,584 //,3 public class xxx { @Override protected String[] getRunCommand(String command, String groupId, String userName, Path pidFile, Configuration conf) { File f = new File(command); if (LOG.isDebugEnabled()) { LOG.debug(String.format("getRunCommand: %s exists:%b", command, f.exists())); } return new String[] { Shell.getWinUtilsPath(), "task", "createAsUser", groupId, userName, pidFile.toString(), "cmd /c " + command }; } };
34.588235
100
0.666667
d77361b5caa75002ef5b042f01167ac7f2cb2d03
1,704
package pkg.deepCurse.nopalmo.command.commands.general; import java.util.HashMap; import pkg.deepCurse.nopalmo.command.CommandInterface.GuildCommandInterface; import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global; import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Guild; import pkg.deepCurse.nopalmo.manager.Argument; import pkg.deepCurse.nopalmo.manager.GuildCommandBlob; public class Prefix implements GuildCommandInterface { @Override public String[] getCommandCalls() { return new String[] { "prefix", }; } @Override public HelpPage getHelpPage() { return HelpPage.General; } @Override public void runGuildCommand(GuildCommandBlob blob, HashMap<String, Argument> argumentList) throws Exception { if (argumentList.get("prefix") != null) { // System.out.println(argumentList.get("prefix").getWildCardString()); Guild.Prefix.setPrefix( blob.getEvent().getGuild().getIdLong(), argumentList.get("prefix").getWildCardString()); blob.getEvent().getChannel().sendMessage("Set prefix to " + argumentList.get("prefix").getWildCardString()).queue(); } else { Guild.Prefix.setPrefix( blob.getEvent().getGuild().getIdLong(), Global.prefix); blob.getEvent().getChannel().sendMessage("Reset prefix to default").queue(); } } @Override public HashMap<String, Argument> getArguments() { HashMap<String, Argument> args = new HashMap<String, Argument>(); args.put("prefix", new Argument("prefix").setPosition(0).setIsWildcard(true)); return args; } @Override public String getUsage() { return Global.prefix + getCommandName() + " <prefix>"; } @Override public String getHelp() { return "Sets a prefix for your guild"; } }
28.881356
119
0.741197
b8f3bcd253456492def708ca057a5190d7e5c2c8
7,091
package org.andromda.cartridges.bpm4struts; import org.andromda.core.profile.Profile; /** * Contains the BPM4Struts profile. * * @author Wouter Zoons */ public final class Bpm4StrutsProfile { /** * The Profile instance from which we retrieve the mapped profile names. */ private static final Profile PROFILE = Profile.instance(); /* ----------------- Stereotypes -------------------- */ /** FRONT_END_EXCEPTION */ public static final String STEREOTYPE_EXCEPTION = PROFILE.get("FRONT_END_EXCEPTION"); /* ----------------- Tagged Values -------------------- */ /** ACTION_TYPE */ public static final String TAGGEDVALUE_ACTION_TYPE = PROFILE.get("ACTION_TYPE"); /** ACTION_RESETTABLE */ public static final String TAGGEDVALUE_ACTION_RESETTABLE = PROFILE.get("ACTION_RESETTABLE"); /** ACTION_SUCCESS_MESSAGE */ public static final String TAGGEDVALUE_ACTION_SUCCESS_MESSAGE = PROFILE.get("ACTION_SUCCESS_MESSAGE"); /** ACTION_WARNING_MESSAGE */ public static final String TAGGEDVALUE_ACTION_WARNING_MESSAGE = PROFILE.get("ACTION_WARNING_MESSAGE"); /** ACTION_FORM_SCOPE */ public static final String TAGGEDVALUE_ACTION_FORM_SCOPE = PROFILE.get("ACTION_FORM_SCOPE"); /** ACTION_FORM_KEY */ public static final String TAGGEDVALUE_ACTION_FORM_KEY = PROFILE.get("ACTION_FORM_KEY"); /** ACTION_TABLELINK */ public static final String TAGGEDVALUE_ACTION_TABLELINK = PROFILE.get("ACTION_TABLELINK"); /** INPUT_COLUMN_COUNT */ public static final String TAGGEDVALUE_INPUT_COLUMN_COUNT = PROFILE.get("INPUT_COLUMN_COUNT"); /** INPUT_ROW_COUNT */ public static final String TAGGEDVALUE_INPUT_ROW_COUNT = PROFILE.get("INPUT_ROW_COUNT"); /** INPUT_REQUIRED */ public static final String TAGGEDVALUE_INPUT_REQUIRED = PROFILE.get("INPUT_REQUIRED"); /** INPUT_READONLY */ public static final String TAGGEDVALUE_INPUT_READONLY = PROFILE.get("INPUT_READONLY"); /** INPUT_FORMAT */ public static final String TAGGEDVALUE_INPUT_FORMAT = PROFILE.get("INPUT_FORMAT"); /** INPUT_TYPE */ public static final String TAGGEDVALUE_INPUT_TYPE = PROFILE.get("INPUT_TYPE"); /** INPUT_MULTIBOX */ public static final String TAGGEDVALUE_INPUT_MULTIBOX = PROFILE.get("INPUT_MULTIBOX"); /** INPUT_RADIO */ public static final String TAGGEDVALUE_INPUT_RADIO = PROFILE.get("INPUT_RADIO"); /** INPUT_VALIDWHEN */ public static final String TAGGEDVALUE_INPUT_VALIDWHEN = PROFILE.get("INPUT_VALIDWHEN"); /** INPUT_VALIDATORS */ public static final String TAGGEDVALUE_INPUT_VALIDATORS = PROFILE.get("INPUT_VALIDATORS"); /** INPUT_CALENDAR */ public static final String TAGGEDVALUE_INPUT_CALENDAR = PROFILE.get("INPUT_CALENDAR"); /** INPUT_RESET */ public static final String TAGGEDVALUE_INPUT_RESET = PROFILE.get("INPUT_RESET"); /** TABLE_COLUMNS */ public static final String TAGGEDVALUE_TABLE_COLUMNS = PROFILE.get("TABLE_COLUMNS"); /** TABLE_MAXROWS */ public static final String TAGGEDVALUE_TABLE_MAXROWS = PROFILE.get("TABLE_MAXROWS"); /** TABLE_EXPORT */ public static final String TAGGEDVALUE_TABLE_EXPORT = PROFILE.get("TABLE_EXPORT"); /** TABLE_SORTABLE */ public static final String TAGGEDVALUE_TABLE_SORTABLE = PROFILE.get("TABLE_SORTABLE"); /** TABLE_DECORATOR */ public static final String TAGGEDVALUE_TABLE_DECORATOR = PROFILE.get("TABLE_DECORATOR"); /** EXCEPTION_TYPE */ public static final String TAGGEDVALUE_EXCEPTION_TYPE = PROFILE.get("EXCEPTION_TYPE"); /** ACTION_REDIRECT */ public static final String TAGGEDVALUE_ACTION_REDIRECT = PROFILE.get("ACTION_REDIRECT"); /* ----------------- Data Types -------------------- */ /** CHARACTER_TYPE */ public static final String CHARACTER_TYPE_NAME = PROFILE.get("CHARACTER_TYPE"); /** BYTE_TYPE */ public static final String BYTE_TYPE_NAME = PROFILE.get("BYTE_TYPE"); /** SHORT_TYPE */ public static final String SHORT_TYPE_NAME = PROFILE.get("SHORT_TYPE"); /** INTEGER_TYPE */ public static final String INTEGER_TYPE_NAME = PROFILE.get("INTEGER_TYPE"); /** LONG_TYPE */ public static final String LONG_TYPE_NAME = PROFILE.get("LONG_TYPE"); /** FLOAT_TYPE */ public static final String FLOAT_TYPE_NAME = PROFILE.get("FLOAT_TYPE"); /** DOUBLE_TYPE */ public static final String DOUBLE_TYPE_NAME = PROFILE.get("DOUBLE_TYPE"); /** URL_TYPE */ public static final String URL_TYPE_NAME = PROFILE.get("URL_TYPE"); /** TIME_TYPE */ public static final String TIME_TYPE_NAME = PROFILE.get("TIME_TYPE"); /* ----------------- Default Values ------------------- */ /** true */ public static final String TAGGEDVALUE_INPUT_DEFAULT_REQUIRED = "true"; /** java.lang.Exception */ public static final String TAGGEDVALUE_EXCEPTION_DEFAULT_TYPE = "java.lang.Exception"; /** form */ public static final String TAGGEDVALUE_ACTION_FORM_DEFAULT_KEY = "form"; /** hyperlink */ public static final String TAGGEDVALUE_ACTION_TYPE_HYPERLINK = "hyperlink"; /** form */ public static final String TAGGEDVALUE_ACTION_TYPE_FORM = "form"; /** image */ public static final String TAGGEDVALUE_ACTION_TYPE_IMAGE = "image"; /** table */ public static final String TAGGEDVALUE_ACTION_TYPE_TABLE = "table"; /** TAGGEDVALUE_ACTION_TYPE_FORM */ public static final String TAGGEDVALUE_ACTION_DEFAULT_TYPE = TAGGEDVALUE_ACTION_TYPE_FORM; /** text */ public static final String TAGGEDVALUE_INPUT_TYPE_TEXT = "text"; /** plaintext */ public static final String TAGGEDVALUE_INPUT_TYPE_PLAINTEXT = "plaintext"; /** textarea */ public static final String TAGGEDVALUE_INPUT_TYPE_TEXTAREA = "textarea"; /** radio */ public static final String TAGGEDVALUE_INPUT_TYPE_RADIO = "radio"; /** checkbox */ public static final String TAGGEDVALUE_INPUT_TYPE_CHECKBOX = "checkbox"; /** hidden */ public static final String TAGGEDVALUE_INPUT_TYPE_HIDDEN = "hidden"; /** select */ public static final String TAGGEDVALUE_INPUT_TYPE_SELECT = "select"; /** password */ public static final String TAGGEDVALUE_INPUT_TYPE_PASSWORD = "password"; /** multibox */ public static final String TAGGEDVALUE_INPUT_TYPE_MULTIBOX = "multibox"; /** link */ public static final String TAGGEDVALUE_INPUT_TYPE_LINK = "link"; /** file */ public static final String TAGGEDVALUE_INPUT_TYPE_FILE = "file"; /** 3 */ public static final int TAGGEDVALUE_INPUT_TYPE_OPTION_DEFAULT_COUNT = 3; /** 15 */ public static final int TAGGEDVALUE_TABLE_MAXROWS_DEFAULT_COUNT = 15; /** true */ public static final boolean TAGGEDVALUE_TABLE_SORTABLE_DEFAULT_VALUE = true; /** true */ public static final boolean TAGGEDVALUE_TABLE_EXPORTABLE_DEFAULT_VALUE = true; private Bpm4StrutsProfile() { } }
48.238095
107
0.69426
af1622fe4e52302a7eb75d7ff27da2baf8bc4e22
4,451
/******************************************************************************* * Copyright 2018 General Electric Company * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 *******************************************************************************/ package org.eclipse.keti.acceptance.test.zone.admin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.springframework.web.client.HttpClientErrorException; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.eclipse.keti.acs.rest.BaseResource; import org.eclipse.keti.acs.rest.Zone; import org.eclipse.keti.test.utils.ACSITSetUpFactory; import org.eclipse.keti.test.utils.ACSTestUtil; import org.eclipse.keti.test.utils.PolicyHelper; import org.eclipse.keti.test.utils.PrivilegeHelper; @Test @ContextConfiguration("classpath:integration-test-spring-context.xml") public class DefaultZoneAuthorizationIT extends AbstractTestNGSpringContextTests { @Autowired private PrivilegeHelper privilegeHelper; @Autowired private ACSITSetUpFactory acsitSetUpFactory; private String zone2Name; @BeforeClass public void setup() throws Exception { this.acsitSetUpFactory.setUp(); this.zone2Name = this.acsitSetUpFactory.getZone2().getName(); } @AfterClass public void cleanup() { this.acsitSetUpFactory.destroy(); } /** * 1. Create a token from zone issuer with scopes for accessing: a. zone specific resources, AND b. * acs.zones.admin * * 2. Try to access a zone specific resource . This should work 3. Try to access /v1/zone - THIS SHOULD FAIL * * @throws Exception */ public void testAccessGlobalResourceWithZoneIssuer() throws Exception { OAuth2RestTemplate zone2AcsTemplate = this.acsitSetUpFactory.getAcsZone2AdminRestTemplate(); HttpHeaders zoneTwoHeaders = ACSTestUtil.httpHeaders(); zoneTwoHeaders.set(PolicyHelper.PREDIX_ZONE_ID, this.zone2Name); // Write a resource to zone2. This should work ResponseEntity<Object> responseEntity = this.privilegeHelper.postResources(zone2AcsTemplate, this.acsitSetUpFactory.getAcsUrl(), zoneTwoHeaders, new BaseResource("/sites/sanramon")); Assert.assertEquals(responseEntity.getStatusCode(), HttpStatus.NO_CONTENT); // Try to get global resource from global/baseUrl. This should FAIL try { zone2AcsTemplate.exchange(this.acsitSetUpFactory.getAcsUrl() + "/v1/zone/" + this.zone2Name, HttpMethod.GET, null, Zone.class); Assert.fail("Able to access non-zone specific resource with a zone specific issuer token!"); } catch (HttpClientErrorException e) { // expected } // Try to get global resource from zone2Url. This should FAIL try { zone2AcsTemplate.exchange(this.acsitSetUpFactory.getAcsUrl() + "/v1/zone/" + this.zone2Name, HttpMethod.GET, new HttpEntity<>(zoneTwoHeaders), Zone.class); Assert.fail("Able to access non-zone specific resource from a zone specific URL, " + "with a zone specific issuer token!"); } catch (InvalidRequestException e) { // expected } } }
41.212963
120
0.706807
90896e74a609055c5922b8118255e3fef487281a
5,104
package org.bouncycastle.math.ec.custom.sec; import java.math.BigInteger; import org.bouncycastle.math.ec.ECFieldElement; import org.bouncycastle.math.raw.Mod; import org.bouncycastle.math.raw.Nat192; import org.bouncycastle.util.Arrays; public class SecP192K1FieldElement extends ECFieldElement { public static final BigInteger Q; protected int[] x; public SecP192K1FieldElement(BigInteger var1) { if (var1 != null && var1.signum() >= 0 && var1.compareTo(Q) < 0) { this.x = SecP192K1Field.fromBigInteger(var1); } else { throw new IllegalArgumentException("x value invalid for SecP192K1FieldElement"); } } public SecP192K1FieldElement() { this.x = Nat192.create(); } protected SecP192K1FieldElement(int[] var1) { this.x = var1; } public boolean isZero() { return Nat192.isZero(this.x); } public boolean isOne() { return Nat192.isOne(this.x); } public boolean testBitZero() { return Nat192.getBit(this.x, 0) == 1; } public BigInteger toBigInteger() { return Nat192.toBigInteger(this.x); } public String getFieldName() { return "SecP192K1Field"; } public int getFieldSize() { return Q.bitLength(); } public ECFieldElement add(ECFieldElement var1) { int[] var2 = Nat192.create(); SecP192K1Field.add(this.x, ((SecP192K1FieldElement)var1).x, var2); return new SecP192K1FieldElement(var2); } public ECFieldElement addOne() { int[] var1 = Nat192.create(); SecP192K1Field.addOne(this.x, var1); return new SecP192K1FieldElement(var1); } public ECFieldElement subtract(ECFieldElement var1) { int[] var2 = Nat192.create(); SecP192K1Field.subtract(this.x, ((SecP192K1FieldElement)var1).x, var2); return new SecP192K1FieldElement(var2); } public ECFieldElement multiply(ECFieldElement var1) { int[] var2 = Nat192.create(); SecP192K1Field.multiply(this.x, ((SecP192K1FieldElement)var1).x, var2); return new SecP192K1FieldElement(var2); } public ECFieldElement divide(ECFieldElement var1) { int[] var2 = Nat192.create(); Mod.invert(SecP192K1Field.P, ((SecP192K1FieldElement)var1).x, var2); SecP192K1Field.multiply(var2, this.x, var2); return new SecP192K1FieldElement(var2); } public ECFieldElement negate() { int[] var1 = Nat192.create(); SecP192K1Field.negate(this.x, var1); return new SecP192K1FieldElement(var1); } public ECFieldElement square() { int[] var1 = Nat192.create(); SecP192K1Field.square(this.x, var1); return new SecP192K1FieldElement(var1); } public ECFieldElement invert() { int[] var1 = Nat192.create(); Mod.invert(SecP192K1Field.P, this.x, var1); return new SecP192K1FieldElement(var1); } public ECFieldElement sqrt() { int[] var1 = this.x; if (!Nat192.isZero(var1) && !Nat192.isOne(var1)) { int[] var2 = Nat192.create(); SecP192K1Field.square(var1, var2); SecP192K1Field.multiply(var2, var1, var2); int[] var3 = Nat192.create(); SecP192K1Field.square(var2, var3); SecP192K1Field.multiply(var3, var1, var3); int[] var4 = Nat192.create(); SecP192K1Field.squareN(var3, 3, var4); SecP192K1Field.multiply(var4, var3, var4); SecP192K1Field.squareN(var4, 2, var4); SecP192K1Field.multiply(var4, var2, var4); SecP192K1Field.squareN(var4, 8, var2); SecP192K1Field.multiply(var2, var4, var2); SecP192K1Field.squareN(var2, 3, var4); SecP192K1Field.multiply(var4, var3, var4); int[] var8 = Nat192.create(); SecP192K1Field.squareN(var4, 16, var8); SecP192K1Field.multiply(var8, var2, var8); SecP192K1Field.squareN(var8, 35, var2); SecP192K1Field.multiply(var2, var8, var2); SecP192K1Field.squareN(var2, 70, var8); SecP192K1Field.multiply(var8, var2, var8); SecP192K1Field.squareN(var8, 19, var2); SecP192K1Field.multiply(var2, var4, var2); SecP192K1Field.squareN(var2, 20, var2); SecP192K1Field.multiply(var2, var4, var2); SecP192K1Field.squareN(var2, 4, var2); SecP192K1Field.multiply(var2, var3, var2); SecP192K1Field.squareN(var2, 6, var2); SecP192K1Field.multiply(var2, var3, var2); SecP192K1Field.square(var2, var2); SecP192K1Field.square(var2, var3); return Nat192.eq(var1, var3) ? new SecP192K1FieldElement(var2) : null; } else { return this; } } public boolean equals(Object var1) { if (var1 == this) { return true; } else if (!(var1 instanceof SecP192K1FieldElement)) { return false; } else { SecP192K1FieldElement var2 = (SecP192K1FieldElement)var1; return Nat192.eq(this.x, var2.x); } } public int hashCode() { return Q.hashCode() ^ Arrays.hashCode((int[])this.x, 0, 6); } static { Q = SecP192K1Curve.q; } }
31.506173
89
0.642045
f9f0ddf5f919d62483a0653dc8d43fb3b638a222
233
package com.example.programmer.womensafety; /** * Created by Programmer on 12/14/2017. */ interface AccelerometerListener { public void onAccelerationChanged(float x,float y,float z); public void onShake(float force); }
21.181818
63
0.742489
2e8c53c214cca338cec2f9ef138727d8ae955208
567
package d1.project.docsmgr.view; import javafx.scene.control.Dialog; import javafx.scene.control.ProgressBar; import javafx.stage.StageStyle; import java.util.List; public class ProgressDialog { public ProgressDialog(List<String> files) { Dialog dialog = new Dialog(); dialog.setTitle("删除进度"); dialog.setHeaderText("删除文件中...(" + files.size() + ")"); ProgressBar bar = new ProgressBar(); dialog.getDialogPane().setContent(bar); dialog.initStyle(StageStyle.UNDECORATED); dialog.showAndWait(); } }
22.68
63
0.673721
858840a99e7806d2f9daf573c2b0c2b7a67ebc2b
636
package com.alphago365.octopus.model; import com.alphago365.octopus.model.audit.DateAudit; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @EqualsAndHashCode(callSuper = false) @Entity @Table(name = "providers") @Data @NoArgsConstructor public class Provider extends DateAudit { @Id private Integer id; private String name; public Provider(Integer id, String name) { this.id = id; this.name = name; } public String toString() { return name; } }
19.272727
52
0.721698
ca7c1d5a72794fc1b39f4acac4030690a641c7a7
64,069
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.fasterxml.jackson.core.io; public final class NumberOutput { public NumberOutput() { // 0 0:aload_0 // 1 1:invokespecial #97 <Method void Object()> // 2 4:return } private static int _full3(int i, byte abyte0[], int j) { i = TRIPLET_TO_CHARS[i]; // 0 0:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 1 3:iload_0 // 2 4:iaload // 3 5:istore_0 int k = j + 1; // 4 6:iload_2 // 5 7:iconst_1 // 6 8:iadd // 7 9:istore_3 abyte0[j] = (byte)(i >> 16); // 8 10:aload_1 // 9 11:iload_2 // 10 12:iload_0 // 11 13:bipush 16 // 12 15:ishr // 13 16:int2byte // 14 17:bastore j = k + 1; // 15 18:iload_3 // 16 19:iconst_1 // 17 20:iadd // 18 21:istore_2 abyte0[k] = (byte)(i >> 8); // 19 22:aload_1 // 20 23:iload_3 // 21 24:iload_0 // 22 25:bipush 8 // 23 27:ishr // 24 28:int2byte // 25 29:bastore abyte0[j] = (byte)i; // 26 30:aload_1 // 27 31:iload_2 // 28 32:iload_0 // 29 33:int2byte // 30 34:bastore return j + 1; // 31 35:iload_2 // 32 36:iconst_1 // 33 37:iadd // 34 38:ireturn } private static int _full3(int i, char ac[], int j) { i = TRIPLET_TO_CHARS[i]; // 0 0:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 1 3:iload_0 // 2 4:iaload // 3 5:istore_0 int k = j + 1; // 4 6:iload_2 // 5 7:iconst_1 // 6 8:iadd // 7 9:istore_3 ac[j] = (char)(i >> 16); // 8 10:aload_1 // 9 11:iload_2 // 10 12:iload_0 // 11 13:bipush 16 // 12 15:ishr // 13 16:int2char // 14 17:castore j = k + 1; // 15 18:iload_3 // 16 19:iconst_1 // 17 20:iadd // 18 21:istore_2 ac[k] = (char)(i >> 8 & 0x7f); // 19 22:aload_1 // 20 23:iload_3 // 21 24:iload_0 // 22 25:bipush 8 // 23 27:ishr // 24 28:bipush 127 // 25 30:iand // 26 31:int2char // 27 32:castore ac[j] = (char)(i & 0x7f); // 28 33:aload_1 // 29 34:iload_2 // 30 35:iload_0 // 31 36:bipush 127 // 32 38:iand // 33 39:int2char // 34 40:castore return j + 1; // 35 41:iload_2 // 36 42:iconst_1 // 37 43:iadd // 38 44:ireturn } private static int _leading3(int i, byte abyte0[], int j) { int l = TRIPLET_TO_CHARS[i]; // 0 0:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 1 3:iload_0 // 2 4:iaload // 3 5:istore 4 int k = j; // 4 7:iload_2 // 5 8:istore_3 if(i > 9) //* 6 9:iload_0 //* 7 10:bipush 9 //* 8 12:icmple 52 { if(i > 99) //* 9 15:iload_0 //* 10 16:bipush 99 //* 11 18:icmple 37 { i = j + 1; // 12 21:iload_2 // 13 22:iconst_1 // 14 23:iadd // 15 24:istore_0 abyte0[j] = (byte)(l >> 16); // 16 25:aload_1 // 17 26:iload_2 // 18 27:iload 4 // 19 29:bipush 16 // 20 31:ishr // 21 32:int2byte // 22 33:bastore } else //* 23 34:goto 39 { i = j; // 24 37:iload_2 // 25 38:istore_0 } k = i + 1; // 26 39:iload_0 // 27 40:iconst_1 // 28 41:iadd // 29 42:istore_3 abyte0[i] = (byte)(l >> 8); // 30 43:aload_1 // 31 44:iload_0 // 32 45:iload 4 // 33 47:bipush 8 // 34 49:ishr // 35 50:int2byte // 36 51:bastore } abyte0[k] = (byte)l; // 37 52:aload_1 // 38 53:iload_3 // 39 54:iload 4 // 40 56:int2byte // 41 57:bastore return k + 1; // 42 58:iload_3 // 43 59:iconst_1 // 44 60:iadd // 45 61:ireturn } private static int _leading3(int i, char ac[], int j) { int l = TRIPLET_TO_CHARS[i]; // 0 0:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 1 3:iload_0 // 2 4:iaload // 3 5:istore 4 int k = j; // 4 7:iload_2 // 5 8:istore_3 if(i > 9) //* 6 9:iload_0 //* 7 10:bipush 9 //* 8 12:icmple 55 { if(i > 99) //* 9 15:iload_0 //* 10 16:bipush 99 //* 11 18:icmple 37 { i = j + 1; // 12 21:iload_2 // 13 22:iconst_1 // 14 23:iadd // 15 24:istore_0 ac[j] = (char)(l >> 16); // 16 25:aload_1 // 17 26:iload_2 // 18 27:iload 4 // 19 29:bipush 16 // 20 31:ishr // 21 32:int2char // 22 33:castore } else //* 23 34:goto 39 { i = j; // 24 37:iload_2 // 25 38:istore_0 } k = i + 1; // 26 39:iload_0 // 27 40:iconst_1 // 28 41:iadd // 29 42:istore_3 ac[i] = (char)(l >> 8 & 0x7f); // 30 43:aload_1 // 31 44:iload_0 // 32 45:iload 4 // 33 47:bipush 8 // 34 49:ishr // 35 50:bipush 127 // 36 52:iand // 37 53:int2char // 38 54:castore } ac[k] = (char)(l & 0x7f); // 39 55:aload_1 // 40 56:iload_3 // 41 57:iload 4 // 42 59:bipush 127 // 43 61:iand // 44 62:int2char // 45 63:castore return k + 1; // 46 64:iload_3 // 47 65:iconst_1 // 48 66:iadd // 49 67:ireturn } private static int _outputFullBillion(int i, byte abyte0[], int j) { int k = i / 1000; // 0 0:iload_0 // 1 1:sipush 1000 // 2 4:idiv // 3 5:istore_3 int l = k / 1000; // 4 6:iload_3 // 5 7:sipush 1000 // 6 10:idiv // 7 11:istore 4 int i1 = TRIPLET_TO_CHARS[l]; // 8 13:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 9 16:iload 4 // 10 18:iaload // 11 19:istore 5 int j1 = j + 1; // 12 21:iload_2 // 13 22:iconst_1 // 14 23:iadd // 15 24:istore 6 abyte0[j] = (byte)(i1 >> 16); // 16 26:aload_1 // 17 27:iload_2 // 18 28:iload 5 // 19 30:bipush 16 // 20 32:ishr // 21 33:int2byte // 22 34:bastore int k1 = j1 + 1; // 23 35:iload 6 // 24 37:iconst_1 // 25 38:iadd // 26 39:istore 7 abyte0[j1] = (byte)(i1 >> 8); // 27 41:aload_1 // 28 42:iload 6 // 29 44:iload 5 // 30 46:bipush 8 // 31 48:ishr // 32 49:int2byte // 33 50:bastore j = k1 + 1; // 34 51:iload 7 // 35 53:iconst_1 // 36 54:iadd // 37 55:istore_2 abyte0[k1] = (byte)i1; // 38 56:aload_1 // 39 57:iload 7 // 40 59:iload 5 // 41 61:int2byte // 42 62:bastore l = TRIPLET_TO_CHARS[k - l * 1000]; // 43 63:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 44 66:iload_3 // 45 67:iload 4 // 46 69:sipush 1000 // 47 72:imul // 48 73:isub // 49 74:iaload // 50 75:istore 4 i1 = j + 1; // 51 77:iload_2 // 52 78:iconst_1 // 53 79:iadd // 54 80:istore 5 abyte0[j] = (byte)(l >> 16); // 55 82:aload_1 // 56 83:iload_2 // 57 84:iload 4 // 58 86:bipush 16 // 59 88:ishr // 60 89:int2byte // 61 90:bastore j1 = i1 + 1; // 62 91:iload 5 // 63 93:iconst_1 // 64 94:iadd // 65 95:istore 6 abyte0[i1] = (byte)(l >> 8); // 66 97:aload_1 // 67 98:iload 5 // 68 100:iload 4 // 69 102:bipush 8 // 70 104:ishr // 71 105:int2byte // 72 106:bastore j = j1 + 1; // 73 107:iload 6 // 74 109:iconst_1 // 75 110:iadd // 76 111:istore_2 abyte0[j1] = (byte)l; // 77 112:aload_1 // 78 113:iload 6 // 79 115:iload 4 // 80 117:int2byte // 81 118:bastore i = TRIPLET_TO_CHARS[i - k * 1000]; // 82 119:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 83 122:iload_0 // 84 123:iload_3 // 85 124:sipush 1000 // 86 127:imul // 87 128:isub // 88 129:iaload // 89 130:istore_0 k = j + 1; // 90 131:iload_2 // 91 132:iconst_1 // 92 133:iadd // 93 134:istore_3 abyte0[j] = (byte)(i >> 16); // 94 135:aload_1 // 95 136:iload_2 // 96 137:iload_0 // 97 138:bipush 16 // 98 140:ishr // 99 141:int2byte // 100 142:bastore j = k + 1; // 101 143:iload_3 // 102 144:iconst_1 // 103 145:iadd // 104 146:istore_2 abyte0[k] = (byte)(i >> 8); // 105 147:aload_1 // 106 148:iload_3 // 107 149:iload_0 // 108 150:bipush 8 // 109 152:ishr // 110 153:int2byte // 111 154:bastore abyte0[j] = (byte)i; // 112 155:aload_1 // 113 156:iload_2 // 114 157:iload_0 // 115 158:int2byte // 116 159:bastore return j + 1; // 117 160:iload_2 // 118 161:iconst_1 // 119 162:iadd // 120 163:ireturn } private static int _outputFullBillion(int i, char ac[], int j) { int k = i / 1000; // 0 0:iload_0 // 1 1:sipush 1000 // 2 4:idiv // 3 5:istore_3 int l = k / 1000; // 4 6:iload_3 // 5 7:sipush 1000 // 6 10:idiv // 7 11:istore 4 int i1 = TRIPLET_TO_CHARS[l]; // 8 13:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 9 16:iload 4 // 10 18:iaload // 11 19:istore 5 int j1 = j + 1; // 12 21:iload_2 // 13 22:iconst_1 // 14 23:iadd // 15 24:istore 6 ac[j] = (char)(i1 >> 16); // 16 26:aload_1 // 17 27:iload_2 // 18 28:iload 5 // 19 30:bipush 16 // 20 32:ishr // 21 33:int2char // 22 34:castore int k1 = j1 + 1; // 23 35:iload 6 // 24 37:iconst_1 // 25 38:iadd // 26 39:istore 7 ac[j1] = (char)(i1 >> 8 & 0x7f); // 27 41:aload_1 // 28 42:iload 6 // 29 44:iload 5 // 30 46:bipush 8 // 31 48:ishr // 32 49:bipush 127 // 33 51:iand // 34 52:int2char // 35 53:castore j = k1 + 1; // 36 54:iload 7 // 37 56:iconst_1 // 38 57:iadd // 39 58:istore_2 ac[k1] = (char)(i1 & 0x7f); // 40 59:aload_1 // 41 60:iload 7 // 42 62:iload 5 // 43 64:bipush 127 // 44 66:iand // 45 67:int2char // 46 68:castore l = TRIPLET_TO_CHARS[k - l * 1000]; // 47 69:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 48 72:iload_3 // 49 73:iload 4 // 50 75:sipush 1000 // 51 78:imul // 52 79:isub // 53 80:iaload // 54 81:istore 4 i1 = j + 1; // 55 83:iload_2 // 56 84:iconst_1 // 57 85:iadd // 58 86:istore 5 ac[j] = (char)(l >> 16); // 59 88:aload_1 // 60 89:iload_2 // 61 90:iload 4 // 62 92:bipush 16 // 63 94:ishr // 64 95:int2char // 65 96:castore j1 = i1 + 1; // 66 97:iload 5 // 67 99:iconst_1 // 68 100:iadd // 69 101:istore 6 ac[i1] = (char)(l >> 8 & 0x7f); // 70 103:aload_1 // 71 104:iload 5 // 72 106:iload 4 // 73 108:bipush 8 // 74 110:ishr // 75 111:bipush 127 // 76 113:iand // 77 114:int2char // 78 115:castore j = j1 + 1; // 79 116:iload 6 // 80 118:iconst_1 // 81 119:iadd // 82 120:istore_2 ac[j1] = (char)(l & 0x7f); // 83 121:aload_1 // 84 122:iload 6 // 85 124:iload 4 // 86 126:bipush 127 // 87 128:iand // 88 129:int2char // 89 130:castore i = TRIPLET_TO_CHARS[i - k * 1000]; // 90 131:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 91 134:iload_0 // 92 135:iload_3 // 93 136:sipush 1000 // 94 139:imul // 95 140:isub // 96 141:iaload // 97 142:istore_0 k = j + 1; // 98 143:iload_2 // 99 144:iconst_1 // 100 145:iadd // 101 146:istore_3 ac[j] = (char)(i >> 16); // 102 147:aload_1 // 103 148:iload_2 // 104 149:iload_0 // 105 150:bipush 16 // 106 152:ishr // 107 153:int2char // 108 154:castore j = k + 1; // 109 155:iload_3 // 110 156:iconst_1 // 111 157:iadd // 112 158:istore_2 ac[k] = (char)(i >> 8 & 0x7f); // 113 159:aload_1 // 114 160:iload_3 // 115 161:iload_0 // 116 162:bipush 8 // 117 164:ishr // 118 165:bipush 127 // 119 167:iand // 120 168:int2char // 121 169:castore ac[j] = (char)(i & 0x7f); // 122 170:aload_1 // 123 171:iload_2 // 124 172:iload_0 // 125 173:bipush 127 // 126 175:iand // 127 176:int2char // 128 177:castore return j + 1; // 129 178:iload_2 // 130 179:iconst_1 // 131 180:iadd // 132 181:ireturn } private static int _outputSmallestI(byte abyte0[], int i) { int k = SMALLEST_INT.length(); // 0 0:getstatic #38 <Field String SMALLEST_INT> // 1 3:invokevirtual #108 <Method int String.length()> // 2 6:istore_3 for(int j = 0; j < k;) //* 3 7:iconst_0 //* 4 8:istore_2 //* 5 9:iload_2 //* 6 10:iload_3 //* 7 11:icmpge 36 { abyte0[i] = (byte)SMALLEST_INT.charAt(j); // 8 14:aload_0 // 9 15:iload_1 // 10 16:getstatic #38 <Field String SMALLEST_INT> // 11 19:iload_2 // 12 20:invokevirtual #112 <Method char String.charAt(int)> // 13 23:int2byte // 14 24:bastore j++; // 15 25:iload_2 // 16 26:iconst_1 // 17 27:iadd // 18 28:istore_2 i++; // 19 29:iload_1 // 20 30:iconst_1 // 21 31:iadd // 22 32:istore_1 } //* 23 33:goto 9 return i; // 24 36:iload_1 // 25 37:ireturn } private static int _outputSmallestI(char ac[], int i) { int j = SMALLEST_INT.length(); // 0 0:getstatic #38 <Field String SMALLEST_INT> // 1 3:invokevirtual #108 <Method int String.length()> // 2 6:istore_2 SMALLEST_INT.getChars(0, j, ac, i); // 3 7:getstatic #38 <Field String SMALLEST_INT> // 4 10:iconst_0 // 5 11:iload_2 // 6 12:aload_0 // 7 13:iload_1 // 8 14:invokevirtual #117 <Method void String.getChars(int, int, char[], int)> return i + j; // 9 17:iload_1 // 10 18:iload_2 // 11 19:iadd // 12 20:ireturn } private static int _outputSmallestL(byte abyte0[], int i) { int k = SMALLEST_LONG.length(); // 0 0:getstatic #45 <Field String SMALLEST_LONG> // 1 3:invokevirtual #108 <Method int String.length()> // 2 6:istore_3 for(int j = 0; j < k;) //* 3 7:iconst_0 //* 4 8:istore_2 //* 5 9:iload_2 //* 6 10:iload_3 //* 7 11:icmpge 36 { abyte0[i] = (byte)SMALLEST_LONG.charAt(j); // 8 14:aload_0 // 9 15:iload_1 // 10 16:getstatic #45 <Field String SMALLEST_LONG> // 11 19:iload_2 // 12 20:invokevirtual #112 <Method char String.charAt(int)> // 13 23:int2byte // 14 24:bastore j++; // 15 25:iload_2 // 16 26:iconst_1 // 17 27:iadd // 18 28:istore_2 i++; // 19 29:iload_1 // 20 30:iconst_1 // 21 31:iadd // 22 32:istore_1 } //* 23 33:goto 9 return i; // 24 36:iload_1 // 25 37:ireturn } private static int _outputSmallestL(char ac[], int i) { int j = SMALLEST_LONG.length(); // 0 0:getstatic #45 <Field String SMALLEST_LONG> // 1 3:invokevirtual #108 <Method int String.length()> // 2 6:istore_2 SMALLEST_LONG.getChars(0, j, ac, i); // 3 7:getstatic #45 <Field String SMALLEST_LONG> // 4 10:iconst_0 // 5 11:iload_2 // 6 12:aload_0 // 7 13:iload_1 // 8 14:invokevirtual #117 <Method void String.getChars(int, int, char[], int)> return i + j; // 9 17:iload_1 // 10 18:iload_2 // 11 19:iadd // 12 20:ireturn } private static int _outputUptoBillion(int i, byte abyte0[], int j) { if(i < MILLION) //* 0 0:iload_0 //* 1 1:getstatic #121 <Field int MILLION> //* 2 4:icmpge 41 { if(i < 1000) //* 3 7:iload_0 //* 4 8:sipush 1000 //* 5 11:icmpge 21 { return _leading3(i, abyte0, j); // 6 14:iload_0 // 7 15:aload_1 // 8 16:iload_2 // 9 17:invokestatic #123 <Method int _leading3(int, byte[], int)> // 10 20:ireturn } else { int k = i / 1000; // 11 21:iload_0 // 12 22:sipush 1000 // 13 25:idiv // 14 26:istore_3 return _outputUptoMillion(abyte0, j, k, i - k * 1000); // 15 27:aload_1 // 16 28:iload_2 // 17 29:iload_3 // 18 30:iload_0 // 19 31:iload_3 // 20 32:sipush 1000 // 21 35:imul // 22 36:isub // 23 37:invokestatic #127 <Method int _outputUptoMillion(byte[], int, int, int)> // 24 40:ireturn } } else { int l = i / 1000; // 25 41:iload_0 // 26 42:sipush 1000 // 27 45:idiv // 28 46:istore_3 int j1 = l / 1000; // 29 47:iload_3 // 30 48:sipush 1000 // 31 51:idiv // 32 52:istore 5 int i1 = _leading3(j1, abyte0, j); // 33 54:iload 5 // 34 56:aload_1 // 35 57:iload_2 // 36 58:invokestatic #123 <Method int _leading3(int, byte[], int)> // 37 61:istore 4 j = TRIPLET_TO_CHARS[l - j1 * 1000]; // 38 63:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 39 66:iload_3 // 40 67:iload 5 // 41 69:sipush 1000 // 42 72:imul // 43 73:isub // 44 74:iaload // 45 75:istore_2 j1 = i1 + 1; // 46 76:iload 4 // 47 78:iconst_1 // 48 79:iadd // 49 80:istore 5 abyte0[i1] = (byte)(j >> 16); // 50 82:aload_1 // 51 83:iload 4 // 52 85:iload_2 // 53 86:bipush 16 // 54 88:ishr // 55 89:int2byte // 56 90:bastore int k1 = j1 + 1; // 57 91:iload 5 // 58 93:iconst_1 // 59 94:iadd // 60 95:istore 6 abyte0[j1] = (byte)(j >> 8); // 61 97:aload_1 // 62 98:iload 5 // 63 100:iload_2 // 64 101:bipush 8 // 65 103:ishr // 66 104:int2byte // 67 105:bastore i1 = k1 + 1; // 68 106:iload 6 // 69 108:iconst_1 // 70 109:iadd // 71 110:istore 4 abyte0[k1] = (byte)j; // 72 112:aload_1 // 73 113:iload 6 // 74 115:iload_2 // 75 116:int2byte // 76 117:bastore i = TRIPLET_TO_CHARS[i - l * 1000]; // 77 118:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 78 121:iload_0 // 79 122:iload_3 // 80 123:sipush 1000 // 81 126:imul // 82 127:isub // 83 128:iaload // 84 129:istore_0 j = i1 + 1; // 85 130:iload 4 // 86 132:iconst_1 // 87 133:iadd // 88 134:istore_2 abyte0[i1] = (byte)(i >> 16); // 89 135:aload_1 // 90 136:iload 4 // 91 138:iload_0 // 92 139:bipush 16 // 93 141:ishr // 94 142:int2byte // 95 143:bastore l = j + 1; // 96 144:iload_2 // 97 145:iconst_1 // 98 146:iadd // 99 147:istore_3 abyte0[j] = (byte)(i >> 8); // 100 148:aload_1 // 101 149:iload_2 // 102 150:iload_0 // 103 151:bipush 8 // 104 153:ishr // 105 154:int2byte // 106 155:bastore abyte0[l] = (byte)i; // 107 156:aload_1 // 108 157:iload_3 // 109 158:iload_0 // 110 159:int2byte // 111 160:bastore return l + 1; // 112 161:iload_3 // 113 162:iconst_1 // 114 163:iadd // 115 164:ireturn } } private static int _outputUptoBillion(int i, char ac[], int j) { if(i < MILLION) //* 0 0:iload_0 //* 1 1:getstatic #121 <Field int MILLION> //* 2 4:icmpge 41 { if(i < 1000) //* 3 7:iload_0 //* 4 8:sipush 1000 //* 5 11:icmpge 21 { return _leading3(i, ac, j); // 6 14:iload_0 // 7 15:aload_1 // 8 16:iload_2 // 9 17:invokestatic #129 <Method int _leading3(int, char[], int)> // 10 20:ireturn } else { int k = i / 1000; // 11 21:iload_0 // 12 22:sipush 1000 // 13 25:idiv // 14 26:istore_3 return _outputUptoMillion(ac, j, k, i - k * 1000); // 15 27:aload_1 // 16 28:iload_2 // 17 29:iload_3 // 18 30:iload_0 // 19 31:iload_3 // 20 32:sipush 1000 // 21 35:imul // 22 36:isub // 23 37:invokestatic #132 <Method int _outputUptoMillion(char[], int, int, int)> // 24 40:ireturn } } else { int l = i / 1000; // 25 41:iload_0 // 26 42:sipush 1000 // 27 45:idiv // 28 46:istore_3 int j1 = l / 1000; // 29 47:iload_3 // 30 48:sipush 1000 // 31 51:idiv // 32 52:istore 5 int i1 = _leading3(j1, ac, j); // 33 54:iload 5 // 34 56:aload_1 // 35 57:iload_2 // 36 58:invokestatic #129 <Method int _leading3(int, char[], int)> // 37 61:istore 4 j = TRIPLET_TO_CHARS[l - j1 * 1000]; // 38 63:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 39 66:iload_3 // 40 67:iload 5 // 41 69:sipush 1000 // 42 72:imul // 43 73:isub // 44 74:iaload // 45 75:istore_2 j1 = i1 + 1; // 46 76:iload 4 // 47 78:iconst_1 // 48 79:iadd // 49 80:istore 5 ac[i1] = (char)(j >> 16); // 50 82:aload_1 // 51 83:iload 4 // 52 85:iload_2 // 53 86:bipush 16 // 54 88:ishr // 55 89:int2char // 56 90:castore int k1 = j1 + 1; // 57 91:iload 5 // 58 93:iconst_1 // 59 94:iadd // 60 95:istore 6 ac[j1] = (char)(j >> 8 & 0x7f); // 61 97:aload_1 // 62 98:iload 5 // 63 100:iload_2 // 64 101:bipush 8 // 65 103:ishr // 66 104:bipush 127 // 67 106:iand // 68 107:int2char // 69 108:castore i1 = k1 + 1; // 70 109:iload 6 // 71 111:iconst_1 // 72 112:iadd // 73 113:istore 4 ac[k1] = (char)(j & 0x7f); // 74 115:aload_1 // 75 116:iload 6 // 76 118:iload_2 // 77 119:bipush 127 // 78 121:iand // 79 122:int2char // 80 123:castore i = TRIPLET_TO_CHARS[i - l * 1000]; // 81 124:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 82 127:iload_0 // 83 128:iload_3 // 84 129:sipush 1000 // 85 132:imul // 86 133:isub // 87 134:iaload // 88 135:istore_0 j = i1 + 1; // 89 136:iload 4 // 90 138:iconst_1 // 91 139:iadd // 92 140:istore_2 ac[i1] = (char)(i >> 16); // 93 141:aload_1 // 94 142:iload 4 // 95 144:iload_0 // 96 145:bipush 16 // 97 147:ishr // 98 148:int2char // 99 149:castore l = j + 1; // 100 150:iload_2 // 101 151:iconst_1 // 102 152:iadd // 103 153:istore_3 ac[j] = (char)(i >> 8 & 0x7f); // 104 154:aload_1 // 105 155:iload_2 // 106 156:iload_0 // 107 157:bipush 8 // 108 159:ishr // 109 160:bipush 127 // 110 162:iand // 111 163:int2char // 112 164:castore ac[l] = (char)(i & 0x7f); // 113 165:aload_1 // 114 166:iload_3 // 115 167:iload_0 // 116 168:bipush 127 // 117 170:iand // 118 171:int2char // 119 172:castore return l + 1; // 120 173:iload_3 // 121 174:iconst_1 // 122 175:iadd // 123 176:ireturn } } private static int _outputUptoMillion(byte abyte0[], int i, int j, int k) { int i1 = TRIPLET_TO_CHARS[j]; // 0 0:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 1 3:iload_2 // 2 4:iaload // 3 5:istore 5 int l = i; // 4 7:iload_1 // 5 8:istore 4 if(j > 9) //* 6 10:iload_2 //* 7 11:bipush 9 //* 8 13:icmple 55 { l = i; // 9 16:iload_1 // 10 17:istore 4 if(j > 99) //* 11 19:iload_2 //* 12 20:bipush 99 //* 13 22:icmple 39 { abyte0[i] = (byte)(i1 >> 16); // 14 25:aload_0 // 15 26:iload_1 // 16 27:iload 5 // 17 29:bipush 16 // 18 31:ishr // 19 32:int2byte // 20 33:bastore l = i + 1; // 21 34:iload_1 // 22 35:iconst_1 // 23 36:iadd // 24 37:istore 4 } abyte0[l] = (byte)(i1 >> 8); // 25 39:aload_0 // 26 40:iload 4 // 27 42:iload 5 // 28 44:bipush 8 // 29 46:ishr // 30 47:int2byte // 31 48:bastore l++; // 32 49:iload 4 // 33 51:iconst_1 // 34 52:iadd // 35 53:istore 4 } i = l + 1; // 36 55:iload 4 // 37 57:iconst_1 // 38 58:iadd // 39 59:istore_1 abyte0[l] = (byte)i1; // 40 60:aload_0 // 41 61:iload 4 // 42 63:iload 5 // 43 65:int2byte // 44 66:bastore j = TRIPLET_TO_CHARS[k]; // 45 67:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 46 70:iload_3 // 47 71:iaload // 48 72:istore_2 k = i + 1; // 49 73:iload_1 // 50 74:iconst_1 // 51 75:iadd // 52 76:istore_3 abyte0[i] = (byte)(j >> 16); // 53 77:aload_0 // 54 78:iload_1 // 55 79:iload_2 // 56 80:bipush 16 // 57 82:ishr // 58 83:int2byte // 59 84:bastore i = k + 1; // 60 85:iload_3 // 61 86:iconst_1 // 62 87:iadd // 63 88:istore_1 abyte0[k] = (byte)(j >> 8); // 64 89:aload_0 // 65 90:iload_3 // 66 91:iload_2 // 67 92:bipush 8 // 68 94:ishr // 69 95:int2byte // 70 96:bastore abyte0[i] = (byte)j; // 71 97:aload_0 // 72 98:iload_1 // 73 99:iload_2 // 74 100:int2byte // 75 101:bastore return i + 1; // 76 102:iload_1 // 77 103:iconst_1 // 78 104:iadd // 79 105:ireturn } private static int _outputUptoMillion(char ac[], int i, int j, int k) { int i1 = TRIPLET_TO_CHARS[j]; // 0 0:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 1 3:iload_2 // 2 4:iaload // 3 5:istore 5 int l = i; // 4 7:iload_1 // 5 8:istore 4 if(j > 9) //* 6 10:iload_2 //* 7 11:bipush 9 //* 8 13:icmple 58 { l = i; // 9 16:iload_1 // 10 17:istore 4 if(j > 99) //* 11 19:iload_2 //* 12 20:bipush 99 //* 13 22:icmple 39 { ac[i] = (char)(i1 >> 16); // 14 25:aload_0 // 15 26:iload_1 // 16 27:iload 5 // 17 29:bipush 16 // 18 31:ishr // 19 32:int2char // 20 33:castore l = i + 1; // 21 34:iload_1 // 22 35:iconst_1 // 23 36:iadd // 24 37:istore 4 } ac[l] = (char)(i1 >> 8 & 0x7f); // 25 39:aload_0 // 26 40:iload 4 // 27 42:iload 5 // 28 44:bipush 8 // 29 46:ishr // 30 47:bipush 127 // 31 49:iand // 32 50:int2char // 33 51:castore l++; // 34 52:iload 4 // 35 54:iconst_1 // 36 55:iadd // 37 56:istore 4 } i = l + 1; // 38 58:iload 4 // 39 60:iconst_1 // 40 61:iadd // 41 62:istore_1 ac[l] = (char)(i1 & 0x7f); // 42 63:aload_0 // 43 64:iload 4 // 44 66:iload 5 // 45 68:bipush 127 // 46 70:iand // 47 71:int2char // 48 72:castore j = TRIPLET_TO_CHARS[k]; // 49 73:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 50 76:iload_3 // 51 77:iaload // 52 78:istore_2 k = i + 1; // 53 79:iload_1 // 54 80:iconst_1 // 55 81:iadd // 56 82:istore_3 ac[i] = (char)(j >> 16); // 57 83:aload_0 // 58 84:iload_1 // 59 85:iload_2 // 60 86:bipush 16 // 61 88:ishr // 62 89:int2char // 63 90:castore i = k + 1; // 64 91:iload_3 // 65 92:iconst_1 // 66 93:iadd // 67 94:istore_1 ac[k] = (char)(j >> 8 & 0x7f); // 68 95:aload_0 // 69 96:iload_3 // 70 97:iload_2 // 71 98:bipush 8 // 72 100:ishr // 73 101:bipush 127 // 74 103:iand // 75 104:int2char // 76 105:castore ac[i] = (char)(j & 0x7f); // 77 106:aload_0 // 78 107:iload_1 // 79 108:iload_2 // 80 109:bipush 127 // 81 111:iand // 82 112:int2char // 83 113:castore return i + 1; // 84 114:iload_1 // 85 115:iconst_1 // 86 116:iadd // 87 117:ireturn } public static int outputInt(int i, byte abyte0[], int j) { int l = i; // 0 0:iload_0 // 1 1:istore 4 int k = j; // 2 3:iload_2 // 3 4:istore_3 if(i < 0) //* 4 5:iload_0 //* 5 6:ifge 34 { if(i == 0x80000000) //* 6 9:iload_0 //* 7 10:ldc1 #30 <Int 0x80000000> //* 8 12:icmpne 21 return _outputSmallestI(abyte0, j); // 9 15:aload_1 // 10 16:iload_2 // 11 17:invokestatic #135 <Method int _outputSmallestI(byte[], int)> // 12 20:ireturn abyte0[j] = 45; // 13 21:aload_1 // 14 22:iload_2 // 15 23:bipush 45 // 16 25:bastore l = -i; // 17 26:iload_0 // 18 27:ineg // 19 28:istore 4 k = j + 1; // 20 30:iload_2 // 21 31:iconst_1 // 22 32:iadd // 23 33:istore_3 } if(l < MILLION) //* 24 34:iload 4 //* 25 36:getstatic #121 <Field int MILLION> //* 26 39:icmpge 104 if(l < 1000) //* 27 42:iload 4 //* 28 44:sipush 1000 //* 29 47:icmpge 78 { if(l < 10) //* 30 50:iload 4 //* 31 52:bipush 10 //* 32 54:icmpge 70 { abyte0[k] = (byte)(48 + l); // 33 57:aload_1 // 34 58:iload_3 // 35 59:bipush 48 // 36 61:iload 4 // 37 63:iadd // 38 64:int2byte // 39 65:bastore return k + 1; // 40 66:iload_3 // 41 67:iconst_1 // 42 68:iadd // 43 69:ireturn } else { return _leading3(l, abyte0, k); // 44 70:iload 4 // 45 72:aload_1 // 46 73:iload_3 // 47 74:invokestatic #123 <Method int _leading3(int, byte[], int)> // 48 77:ireturn } } else { i = l / 1000; // 49 78:iload 4 // 50 80:sipush 1000 // 51 83:idiv // 52 84:istore_0 return _full3(l - i * 1000, abyte0, _leading3(i, abyte0, k)); // 53 85:iload 4 // 54 87:iload_0 // 55 88:sipush 1000 // 56 91:imul // 57 92:isub // 58 93:aload_1 // 59 94:iload_0 // 60 95:aload_1 // 61 96:iload_3 // 62 97:invokestatic #123 <Method int _leading3(int, byte[], int)> // 63 100:invokestatic #137 <Method int _full3(int, byte[], int)> // 64 103:ireturn } if(l >= BILLION) //* 65 104:iload 4 //* 66 106:getstatic #139 <Field int BILLION> //* 67 109:icmplt 160 { j = l - BILLION; // 68 112:iload 4 // 69 114:getstatic #139 <Field int BILLION> // 70 117:isub // 71 118:istore_2 if(j >= BILLION) //* 72 119:iload_2 //* 73 120:getstatic #139 <Field int BILLION> //* 74 123:icmplt 144 { j -= BILLION; // 75 126:iload_2 // 76 127:getstatic #139 <Field int BILLION> // 77 130:isub // 78 131:istore_2 i = k + 1; // 79 132:iload_3 // 80 133:iconst_1 // 81 134:iadd // 82 135:istore_0 abyte0[k] = 50; // 83 136:aload_1 // 84 137:iload_3 // 85 138:bipush 50 // 86 140:bastore } else //* 87 141:goto 153 { i = k + 1; // 88 144:iload_3 // 89 145:iconst_1 // 90 146:iadd // 91 147:istore_0 abyte0[k] = 49; // 92 148:aload_1 // 93 149:iload_3 // 94 150:bipush 49 // 95 152:bastore } return _outputFullBillion(j, abyte0, i); // 96 153:iload_2 // 97 154:aload_1 // 98 155:iload_0 // 99 156:invokestatic #141 <Method int _outputFullBillion(int, byte[], int)> // 100 159:ireturn } else { i = l / 1000; // 101 160:iload 4 // 102 162:sipush 1000 // 103 165:idiv // 104 166:istore_0 j = i / 1000; // 105 167:iload_0 // 106 168:sipush 1000 // 107 171:idiv // 108 172:istore_2 return _full3(l - i * 1000, abyte0, _full3(i - j * 1000, abyte0, _leading3(j, abyte0, k))); // 109 173:iload 4 // 110 175:iload_0 // 111 176:sipush 1000 // 112 179:imul // 113 180:isub // 114 181:aload_1 // 115 182:iload_0 // 116 183:iload_2 // 117 184:sipush 1000 // 118 187:imul // 119 188:isub // 120 189:aload_1 // 121 190:iload_2 // 122 191:aload_1 // 123 192:iload_3 // 124 193:invokestatic #123 <Method int _leading3(int, byte[], int)> // 125 196:invokestatic #137 <Method int _full3(int, byte[], int)> // 126 199:invokestatic #137 <Method int _full3(int, byte[], int)> // 127 202:ireturn } } public static int outputInt(int i, char ac[], int j) { int l = i; // 0 0:iload_0 // 1 1:istore 4 int k = j; // 2 3:iload_2 // 3 4:istore_3 if(i < 0) //* 4 5:iload_0 //* 5 6:ifge 34 { if(i == 0x80000000) //* 6 9:iload_0 //* 7 10:ldc1 #30 <Int 0x80000000> //* 8 12:icmpne 21 return _outputSmallestI(ac, j); // 9 15:aload_1 // 10 16:iload_2 // 11 17:invokestatic #143 <Method int _outputSmallestI(char[], int)> // 12 20:ireturn ac[j] = '-'; // 13 21:aload_1 // 14 22:iload_2 // 15 23:bipush 45 // 16 25:castore l = -i; // 17 26:iload_0 // 18 27:ineg // 19 28:istore 4 k = j + 1; // 20 30:iload_2 // 21 31:iconst_1 // 22 32:iadd // 23 33:istore_3 } if(l < MILLION) //* 24 34:iload 4 //* 25 36:getstatic #121 <Field int MILLION> //* 26 39:icmpge 104 if(l < 1000) //* 27 42:iload 4 //* 28 44:sipush 1000 //* 29 47:icmpge 78 { if(l < 10) //* 30 50:iload 4 //* 31 52:bipush 10 //* 32 54:icmpge 70 { ac[k] = (char)(48 + l); // 33 57:aload_1 // 34 58:iload_3 // 35 59:bipush 48 // 36 61:iload 4 // 37 63:iadd // 38 64:int2char // 39 65:castore return k + 1; // 40 66:iload_3 // 41 67:iconst_1 // 42 68:iadd // 43 69:ireturn } else { return _leading3(l, ac, k); // 44 70:iload 4 // 45 72:aload_1 // 46 73:iload_3 // 47 74:invokestatic #129 <Method int _leading3(int, char[], int)> // 48 77:ireturn } } else { i = l / 1000; // 49 78:iload 4 // 50 80:sipush 1000 // 51 83:idiv // 52 84:istore_0 return _full3(l - i * 1000, ac, _leading3(i, ac, k)); // 53 85:iload 4 // 54 87:iload_0 // 55 88:sipush 1000 // 56 91:imul // 57 92:isub // 58 93:aload_1 // 59 94:iload_0 // 60 95:aload_1 // 61 96:iload_3 // 62 97:invokestatic #129 <Method int _leading3(int, char[], int)> // 63 100:invokestatic #145 <Method int _full3(int, char[], int)> // 64 103:ireturn } if(l >= BILLION) //* 65 104:iload 4 //* 66 106:getstatic #139 <Field int BILLION> //* 67 109:icmplt 160 { j = l - BILLION; // 68 112:iload 4 // 69 114:getstatic #139 <Field int BILLION> // 70 117:isub // 71 118:istore_2 if(j >= BILLION) //* 72 119:iload_2 //* 73 120:getstatic #139 <Field int BILLION> //* 74 123:icmplt 144 { j -= BILLION; // 75 126:iload_2 // 76 127:getstatic #139 <Field int BILLION> // 77 130:isub // 78 131:istore_2 i = k + 1; // 79 132:iload_3 // 80 133:iconst_1 // 81 134:iadd // 82 135:istore_0 ac[k] = '2'; // 83 136:aload_1 // 84 137:iload_3 // 85 138:bipush 50 // 86 140:castore } else //* 87 141:goto 153 { i = k + 1; // 88 144:iload_3 // 89 145:iconst_1 // 90 146:iadd // 91 147:istore_0 ac[k] = '1'; // 92 148:aload_1 // 93 149:iload_3 // 94 150:bipush 49 // 95 152:castore } return _outputFullBillion(j, ac, i); // 96 153:iload_2 // 97 154:aload_1 // 98 155:iload_0 // 99 156:invokestatic #147 <Method int _outputFullBillion(int, char[], int)> // 100 159:ireturn } else { i = l / 1000; // 101 160:iload 4 // 102 162:sipush 1000 // 103 165:idiv // 104 166:istore_0 j = i / 1000; // 105 167:iload_0 // 106 168:sipush 1000 // 107 171:idiv // 108 172:istore_2 return _full3(l - i * 1000, ac, _full3(i - j * 1000, ac, _leading3(j, ac, k))); // 109 173:iload 4 // 110 175:iload_0 // 111 176:sipush 1000 // 112 179:imul // 113 180:isub // 114 181:aload_1 // 115 182:iload_0 // 116 183:iload_2 // 117 184:sipush 1000 // 118 187:imul // 119 188:isub // 120 189:aload_1 // 121 190:iload_2 // 122 191:aload_1 // 123 192:iload_3 // 124 193:invokestatic #129 <Method int _leading3(int, char[], int)> // 125 196:invokestatic #145 <Method int _full3(int, char[], int)> // 126 199:invokestatic #145 <Method int _full3(int, char[], int)> // 127 202:ireturn } } public static int outputLong(long l, byte abyte0[], int i) { int j; long l1; if(l < 0L) //* 0 0:lload_0 //* 1 1:lconst_0 //* 2 2:lcmp //* 3 3:ifge 53 { if(l > MIN_INT_AS_LONG) //* 4 6:lload_0 //* 5 7:getstatic #151 <Field long MIN_INT_AS_LONG> //* 6 10:lcmp //* 7 11:ifle 22 return outputInt((int)l, abyte0, i); // 8 14:lload_0 // 9 15:l2i // 10 16:aload_2 // 11 17:iload_3 // 12 18:invokestatic #153 <Method int outputInt(int, byte[], int)> // 13 21:ireturn if(l == 0x0L) //* 14 22:lload_0 //* 15 23:ldc2w #39 <Long 0x0L> //* 16 26:lcmp //* 17 27:ifne 36 return _outputSmallestL(abyte0, i); // 18 30:aload_2 // 19 31:iload_3 // 20 32:invokestatic #155 <Method int _outputSmallestL(byte[], int)> // 21 35:ireturn abyte0[i] = 45; // 22 36:aload_2 // 23 37:iload_3 // 24 38:bipush 45 // 25 40:bastore l1 = -l; // 26 41:lload_0 // 27 42:lneg // 28 43:lstore 5 j = i + 1; // 29 45:iload_3 // 30 46:iconst_1 // 31 47:iadd // 32 48:istore 4 } else //* 33 50:goto 75 { l1 = l; // 34 53:lload_0 // 35 54:lstore 5 j = i; // 36 56:iload_3 // 37 57:istore 4 if(l <= MAX_INT_AS_LONG) //* 38 59:lload_0 //* 39 60:getstatic #157 <Field long MAX_INT_AS_LONG> //* 40 63:lcmp //* 41 64:ifgt 75 return outputInt((int)l, abyte0, i); // 42 67:lload_0 // 43 68:l2i // 44 69:aload_2 // 45 70:iload_3 // 46 71:invokestatic #153 <Method int outputInt(int, byte[], int)> // 47 74:ireturn } l = l1 / BILLION_L; // 48 75:lload 5 // 49 77:getstatic #159 <Field long BILLION_L> // 50 80:ldiv // 51 81:lstore_0 long l2 = BILLION_L; // 52 82:getstatic #159 <Field long BILLION_L> // 53 85:lstore 7 if(l < BILLION_L) //* 54 87:lload_0 //* 55 88:getstatic #159 <Field long BILLION_L> //* 56 91:lcmp //* 57 92:ifge 107 { i = _outputUptoBillion((int)l, abyte0, j); // 58 95:lload_0 // 59 96:l2i // 60 97:aload_2 // 61 98:iload 4 // 62 100:invokestatic #161 <Method int _outputUptoBillion(int, byte[], int)> // 63 103:istore_3 } else //* 64 104:goto 143 { long l3 = l / BILLION_L; // 65 107:lload_0 // 66 108:getstatic #159 <Field long BILLION_L> // 67 111:ldiv // 68 112:lstore 9 long l4 = BILLION_L; // 69 114:getstatic #159 <Field long BILLION_L> // 70 117:lstore 11 i = _leading3((int)l3, abyte0, j); // 71 119:lload 9 // 72 121:l2i // 73 122:aload_2 // 74 123:iload 4 // 75 125:invokestatic #123 <Method int _leading3(int, byte[], int)> // 76 128:istore_3 i = _outputFullBillion((int)(l - l4 * l3), abyte0, i); // 77 129:lload_0 // 78 130:lload 11 // 79 132:lload 9 // 80 134:lmul // 81 135:lsub // 82 136:l2i // 83 137:aload_2 // 84 138:iload_3 // 85 139:invokestatic #141 <Method int _outputFullBillion(int, byte[], int)> // 86 142:istore_3 } return _outputFullBillion((int)(l1 - l2 * l), abyte0, i); // 87 143:lload 5 // 88 145:lload 7 // 89 147:lload_0 // 90 148:lmul // 91 149:lsub // 92 150:l2i // 93 151:aload_2 // 94 152:iload_3 // 95 153:invokestatic #141 <Method int _outputFullBillion(int, byte[], int)> // 96 156:ireturn } public static int outputLong(long l, char ac[], int i) { int j; long l1; if(l < 0L) //* 0 0:lload_0 //* 1 1:lconst_0 //* 2 2:lcmp //* 3 3:ifge 53 { if(l > MIN_INT_AS_LONG) //* 4 6:lload_0 //* 5 7:getstatic #151 <Field long MIN_INT_AS_LONG> //* 6 10:lcmp //* 7 11:ifle 22 return outputInt((int)l, ac, i); // 8 14:lload_0 // 9 15:l2i // 10 16:aload_2 // 11 17:iload_3 // 12 18:invokestatic #164 <Method int outputInt(int, char[], int)> // 13 21:ireturn if(l == 0x0L) //* 14 22:lload_0 //* 15 23:ldc2w #39 <Long 0x0L> //* 16 26:lcmp //* 17 27:ifne 36 return _outputSmallestL(ac, i); // 18 30:aload_2 // 19 31:iload_3 // 20 32:invokestatic #166 <Method int _outputSmallestL(char[], int)> // 21 35:ireturn ac[i] = '-'; // 22 36:aload_2 // 23 37:iload_3 // 24 38:bipush 45 // 25 40:castore l1 = -l; // 26 41:lload_0 // 27 42:lneg // 28 43:lstore 5 j = i + 1; // 29 45:iload_3 // 30 46:iconst_1 // 31 47:iadd // 32 48:istore 4 } else //* 33 50:goto 75 { l1 = l; // 34 53:lload_0 // 35 54:lstore 5 j = i; // 36 56:iload_3 // 37 57:istore 4 if(l <= MAX_INT_AS_LONG) //* 38 59:lload_0 //* 39 60:getstatic #157 <Field long MAX_INT_AS_LONG> //* 40 63:lcmp //* 41 64:ifgt 75 return outputInt((int)l, ac, i); // 42 67:lload_0 // 43 68:l2i // 44 69:aload_2 // 45 70:iload_3 // 46 71:invokestatic #164 <Method int outputInt(int, char[], int)> // 47 74:ireturn } l = l1 / BILLION_L; // 48 75:lload 5 // 49 77:getstatic #159 <Field long BILLION_L> // 50 80:ldiv // 51 81:lstore_0 long l2 = BILLION_L; // 52 82:getstatic #159 <Field long BILLION_L> // 53 85:lstore 7 if(l < BILLION_L) //* 54 87:lload_0 //* 55 88:getstatic #159 <Field long BILLION_L> //* 56 91:lcmp //* 57 92:ifge 107 { i = _outputUptoBillion((int)l, ac, j); // 58 95:lload_0 // 59 96:l2i // 60 97:aload_2 // 61 98:iload 4 // 62 100:invokestatic #168 <Method int _outputUptoBillion(int, char[], int)> // 63 103:istore_3 } else //* 64 104:goto 143 { long l3 = l / BILLION_L; // 65 107:lload_0 // 66 108:getstatic #159 <Field long BILLION_L> // 67 111:ldiv // 68 112:lstore 9 long l4 = BILLION_L; // 69 114:getstatic #159 <Field long BILLION_L> // 70 117:lstore 11 i = _leading3((int)l3, ac, j); // 71 119:lload 9 // 72 121:l2i // 73 122:aload_2 // 74 123:iload 4 // 75 125:invokestatic #129 <Method int _leading3(int, char[], int)> // 76 128:istore_3 i = _outputFullBillion((int)(l - l4 * l3), ac, i); // 77 129:lload_0 // 78 130:lload 11 // 79 132:lload 9 // 80 134:lmul // 81 135:lsub // 82 136:l2i // 83 137:aload_2 // 84 138:iload_3 // 85 139:invokestatic #147 <Method int _outputFullBillion(int, char[], int)> // 86 142:istore_3 } return _outputFullBillion((int)(l1 - l2 * l), ac, i); // 87 143:lload 5 // 88 145:lload 7 // 89 147:lload_0 // 90 148:lmul // 91 149:lsub // 92 150:l2i // 93 151:aload_2 // 94 152:iload_3 // 95 153:invokestatic #147 <Method int _outputFullBillion(int, char[], int)> // 96 156:ireturn } public static String toString(double d) { return Double.toString(d); // 0 0:dload_0 // 1 1:invokestatic #174 <Method String Double.toString(double)> // 2 4:areturn } public static String toString(float f) { return Float.toString(f); // 0 0:fload_0 // 1 1:invokestatic #179 <Method String Float.toString(float)> // 2 4:areturn } public static String toString(int i) { if(i < sSmallIntStrs.length) //* 0 0:iload_0 //* 1 1:getstatic #71 <Field String[] sSmallIntStrs> //* 2 4:arraylength //* 3 5:icmpge 37 { if(i >= 0) //* 4 8:iload_0 //* 5 9:iflt 18 return sSmallIntStrs[i]; // 6 12:getstatic #71 <Field String[] sSmallIntStrs> // 7 15:iload_0 // 8 16:aaload // 9 17:areturn int j = -i - 1; // 10 18:iload_0 // 11 19:ineg // 12 20:iconst_1 // 13 21:isub // 14 22:istore_1 if(j < sSmallIntStrs2.length) //* 15 23:iload_1 //* 16 24:getstatic #93 <Field String[] sSmallIntStrs2> //* 17 27:arraylength //* 18 28:icmpge 37 return sSmallIntStrs2[j]; // 19 31:getstatic #93 <Field String[] sSmallIntStrs2> // 20 34:iload_1 // 21 35:aaload // 22 36:areturn } return Integer.toString(i); // 23 37:iload_0 // 24 38:invokestatic #183 <Method String Integer.toString(int)> // 25 41:areturn } public static String toString(long l) { if(l <= 0x7fffffffL && l >= 0x80000000L) //* 0 0:lload_0 //* 1 1:ldc2w #13 <Long 0x7fffffffL> //* 2 4:lcmp //* 3 5:ifgt 22 //* 4 8:lload_0 //* 5 9:ldc2w #18 <Long 0x80000000L> //* 6 12:lcmp //* 7 13:iflt 22 return toString((int)l); // 8 16:lload_0 // 9 17:l2i // 10 18:invokestatic #184 <Method String toString(int)> // 11 21:areturn else return Long.toString(l); // 12 22:lload_0 // 13 23:invokestatic #188 <Method String Long.toString(long)> // 14 26:areturn } private static int BILLION = 0x3b9aca00; private static long BILLION_L = 0x3b9aca00L; private static long MAX_INT_AS_LONG = 0x7fffffffL; private static int MILLION = 0xf4240; private static long MIN_INT_AS_LONG = 0x80000000L; static final String SMALLEST_INT = String.valueOf(0x80000000); static final String SMALLEST_LONG = String.valueOf(0x0L); private static final int TRIPLET_TO_CHARS[]; private static final String sSmallIntStrs[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }; private static final String sSmallIntStrs2[] = { "-1", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9", "-10" }; static { // 0 0:ldc1 #30 <Int 0x80000000> // 1 2:invokestatic #36 <Method String String.valueOf(int)> // 2 5:putstatic #38 <Field String SMALLEST_INT> // 3 8:ldc2w #39 <Long 0x0L> // 4 11:invokestatic #43 <Method String String.valueOf(long)> // 5 14:putstatic #45 <Field String SMALLEST_LONG> TRIPLET_TO_CHARS = new int[1000]; // 6 17:sipush 1000 // 7 20:newarray int[] // 8 22:putstatic #47 <Field int[] TRIPLET_TO_CHARS> int j = 0; // 9 25:iconst_0 // 10 26:istore_1 int i = j; // 11 27:iload_1 // 12 28:istore_0 for(; j < 10; j++) //* 13 29:iload_1 //* 14 30:bipush 10 //* 15 32:icmpge 101 { for(int k = 0; k < 10; k++) //* 16 35:iconst_0 //* 17 36:istore_2 //* 18 37:iload_2 //* 19 38:bipush 10 //* 20 40:icmpge 94 { for(int l = 0; l < 10;) //* 21 43:iconst_0 //* 22 44:istore_3 //* 23 45:iload_3 //* 24 46:bipush 10 //* 25 48:icmpge 87 { TRIPLET_TO_CHARS[i] = j + 48 << 16 | k + 48 << 8 | l + 48; // 26 51:getstatic #47 <Field int[] TRIPLET_TO_CHARS> // 27 54:iload_0 // 28 55:iload_1 // 29 56:bipush 48 // 30 58:iadd // 31 59:bipush 16 // 32 61:ishl // 33 62:iload_2 // 34 63:bipush 48 // 35 65:iadd // 36 66:bipush 8 // 37 68:ishl // 38 69:ior // 39 70:iload_3 // 40 71:bipush 48 // 41 73:iadd // 42 74:ior // 43 75:iastore l++; // 44 76:iload_3 // 45 77:iconst_1 // 46 78:iadd // 47 79:istore_3 i++; // 48 80:iload_0 // 49 81:iconst_1 // 50 82:iadd // 51 83:istore_0 } } // 52 84:goto 45 // 53 87:iload_2 // 54 88:iconst_1 // 55 89:iadd // 56 90:istore_2 } // 57 91:goto 37 // 58 94:iload_1 // 59 95:iconst_1 // 60 96:iadd // 61 97:istore_1 //* 62 98:goto 29 // 63 101:bipush 11 // 64 103:anewarray String[] // 65 106:dup // 66 107:iconst_0 // 67 108:ldc1 #49 <String "0"> // 68 110:aastore // 69 111:dup // 70 112:iconst_1 // 71 113:ldc1 #51 <String "1"> // 72 115:aastore // 73 116:dup // 74 117:iconst_2 // 75 118:ldc1 #53 <String "2"> // 76 120:aastore // 77 121:dup // 78 122:iconst_3 // 79 123:ldc1 #55 <String "3"> // 80 125:aastore // 81 126:dup // 82 127:iconst_4 // 83 128:ldc1 #57 <String "4"> // 84 130:aastore // 85 131:dup // 86 132:iconst_5 // 87 133:ldc1 #59 <String "5"> // 88 135:aastore // 89 136:dup // 90 137:bipush 6 // 91 139:ldc1 #61 <String "6"> // 92 141:aastore // 93 142:dup // 94 143:bipush 7 // 95 145:ldc1 #63 <String "7"> // 96 147:aastore // 97 148:dup // 98 149:bipush 8 // 99 151:ldc1 #65 <String "8"> // 100 153:aastore // 101 154:dup // 102 155:bipush 9 // 103 157:ldc1 #67 <String "9"> // 104 159:aastore // 105 160:dup // 106 161:bipush 10 // 107 163:ldc1 #69 <String "10"> // 108 165:aastore // 109 166:putstatic #71 <Field String[] sSmallIntStrs> // 110 169:bipush 10 // 111 171:anewarray String[] // 112 174:dup // 113 175:iconst_0 // 114 176:ldc1 #73 <String "-1"> // 115 178:aastore // 116 179:dup // 117 180:iconst_1 // 118 181:ldc1 #75 <String "-2"> // 119 183:aastore // 120 184:dup // 121 185:iconst_2 // 122 186:ldc1 #77 <String "-3"> // 123 188:aastore // 124 189:dup // 125 190:iconst_3 // 126 191:ldc1 #79 <String "-4"> // 127 193:aastore // 128 194:dup // 129 195:iconst_4 // 130 196:ldc1 #81 <String "-5"> // 131 198:aastore // 132 199:dup // 133 200:iconst_5 // 134 201:ldc1 #83 <String "-6"> // 135 203:aastore // 136 204:dup // 137 205:bipush 6 // 138 207:ldc1 #85 <String "-7"> // 139 209:aastore // 140 210:dup // 141 211:bipush 7 // 142 213:ldc1 #87 <String "-8"> // 143 215:aastore // 144 216:dup // 145 217:bipush 8 // 146 219:ldc1 #89 <String "-9"> // 147 221:aastore // 148 222:dup // 149 223:bipush 9 // 150 225:ldc1 #91 <String "-10"> // 151 227:aastore // 152 228:putstatic #93 <Field String[] sSmallIntStrs2> //* 153 231:return } }
30.567271
94
0.407795
822adf878f8249f9cd7d9198aa8057eff1169431
520
package com.shubham.selenium.config; public class TestNGConstant { public static final String baseURL = "baseURL";// www.baseurl.com/ public static final String cromeDriver = "webdriver.chrome.driver"; // chrome driver public static final String cromeDriverPath = "D:\\Project\\chromedriver\\chromedriver.exe"; // chrome driver path public static final String dataProvider = "C:\\Users\\sachi\\eclipse-workspace\\SeleniumTestNG\\src\\test\\java\\com\\shubham\\selenium\\test\\dataProvider.txt"; }
37.142857
163
0.742308
2f50fdd662e2481098a25099106d9af0134ed99c
2,412
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.appservice.implementation; import com.microsoft.azure.PagedList; import com.microsoft.azure.management.apigeneration.LangDefinition; import com.microsoft.azure.management.appservice.AppServiceDomain; import com.microsoft.azure.management.appservice.AppServiceDomains; import com.microsoft.azure.management.appservice.DomainLegalAgreement; import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; import com.microsoft.azure.management.resources.fluentcore.utils.PagedListConverter; import rx.Observable; /** * The implementation for AppServiceDomains. */ @LangDefinition(ContainerName = "/Microsoft.Azure.Management.AppService.Fluent") class AppServiceDomainsImpl extends TopLevelModifiableResourcesImpl< AppServiceDomain, AppServiceDomainImpl, DomainInner, DomainsInner, AppServiceManager> implements AppServiceDomains { AppServiceDomainsImpl(AppServiceManager manager) { super(manager.inner().domains(), manager); } @Override protected AppServiceDomainImpl wrapModel(String name) { return new AppServiceDomainImpl(name, new DomainInner(), this.manager()); } @Override protected AppServiceDomainImpl wrapModel(DomainInner inner) { if (inner == null) { return null; } return new AppServiceDomainImpl(inner.name(), inner, this.manager()); } @Override public AppServiceDomainImpl define(String name) { return wrapModel(name); } @Override public PagedList<DomainLegalAgreement> listAgreements(String topLevelExtension) { return new PagedListConverter<TldLegalAgreementInner, DomainLegalAgreement>() { @Override public Observable<DomainLegalAgreement> typeConvertAsync(TldLegalAgreementInner tldLegalAgreementInner) { return Observable.just((DomainLegalAgreement) new DomainLegalAgreementImpl(tldLegalAgreementInner)); } }.convert(this.manager().inner().topLevelDomains().listAgreements(topLevelExtension, new TopLevelDomainAgreementOptionInner())); } }
37.6875
136
0.735075
a22a03ecf39af7266ffae1c2660c0dd18daba7a5
1,048
package pxf.toolkit.extension.pinyin; import javax.annotation.Nonnull; import pxf.toolkit.basic.lang.collection.ArrayObject; /** * 拼音 * * @author potatoxf * @date 2021/4/29 */ public class PinYin extends ArrayObject<String> { private static final long serialVersionUID = 2163839972630926530L; PinYin(final String... array) { super(array); } PinYin(final PinYin pinYin) { super(pinYin); } PinYin(final PinYin pinYin, @Nonnull final String... array) { super(pinYin, array); } PinYin(final ArrayObject<String> arrayObject, @Nonnull final String... array) { super(arrayObject, array); } /** * 是否为多音字 * * @return 如果 {@code true}则是多音字,否则false */ public boolean isPoly() { return length() > 1; } /** * 是否为单音字 * * @return 如果 {@code true}则是单音字,否则false */ public boolean isMono() { return length() == 1; } /** * 去重 * * @return {@code pxf.toolkit.extension.pinyin.PinYin} */ PinYin distinct() { return new PinYin(super.distinct(String[]::new)); } }
19.407407
81
0.638359
407d93e1de244db4b1415d802848213d000adc54
520
package org.baghdasaryan.packageuninstaller.data.apps; public class App { private final String name; private final String packageName; private final int icon; public App(String name, String packageName, int icon) { this.name = name; this.packageName = packageName; this.icon = icon; } public String getName() { return name; } public String getPackageName() { return packageName; } public int getIcon() { return icon; } }
18.571429
59
0.621154
d557ccdf4419bd6a6c271a595d3c223fbf9416e4
388
package com.gjr.wheelpickerbyrecyclerview; import android.app.Application; import com.gjr.wheelpickerbyrecyclerview.data.ProvinceUtil; import io.realm.Realm; /** * Created by geng * on 2017/4/6. */ public class App extends Application { @Override public void onCreate() { super.onCreate(); Realm.init(this); ProvinceUtil.insertAll(this); } }
16.166667
59
0.685567