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
6bfa78fc68433ae4f719cc5a940d603c7d6a18f2
968
package com.cx.entity; /** * h_name varchar2(10) , position varchar2(10) not null, price number(8) not null, constraint hero_h_name primary key(h_name) * @author KKW * */ public class hero { private String hname; private String position; private Integer price; public String getHname() { return hname; } public void setHname(String hname) { this.hname = hname; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } @Override public String toString() { return "hero [hname=" + hname + ", position=" + position + ", price=" + price + ", getHname()=" + getHname() + ", getPosition()=" + getPosition() + ", getPrice()=" + getPrice() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; } }
22
110
0.640496
44457e971aee3276de6512d36bdaaf33b5c67a04
726
package fr.improve.struts.taglib.layout.util; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import fr.improve.struts.taglib.layout.crumb.Crumb; import fr.improve.struts.taglib.layout.crumb.CrumbsTag; /** * Render crumbs elements. * * @author jribette */ public interface ICrumbRenderer { /** * Start crumbs rendering. */ public void doStartCrumbs(PageContext pageContext, CrumbsTag crumbs) throws JspException; /** * End crumbs rendering. */ public void doEndCrumbs(PageContext pageContext, CrumbsTag crumbs) throws JspException; /** * Render one crumb. */ public void doRenderCrumb(PageContext pageContext, CrumbsTag crumbsTag, Crumb crumb) throws JspException; }
24.2
106
0.761708
685c0170fe175852b0ea07d44b843f761b35f150
6,362
package gms.shared.mechanisms.objectstoragedistribution.coi.stationreference.service.utility; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import gms.shared.mechanisms.objectstoragedistribution.coi.common.TestUtilities; import gms.shared.mechanisms.objectstoragedistribution.coi.stationreference.commonobjects.ReferenceNetwork; import gms.shared.mechanisms.objectstoragedistribution.coi.stationreference.service.testUtilities.TestFixtures; import java.time.Instant; import java.util.HashSet; import java.util.List; import java.util.UUID; import java.util.function.Function; import org.junit.Test; public class FilterUtilityTest { private final List<ReferenceNetwork> networks = TestFixtures.allNetworks; private static Instant changeTime1 = TestFixtures.network.getActualChangeTime(), changeTime2 = TestFixtures.network2.getActualChangeTime(), changeTime3 = TestFixtures.network_v2.getActualChangeTime(), changeTime4 = TestFixtures.network2_v2.getActualChangeTime(); private static final Function<ReferenceNetwork, Instant> timeExtractor = ReferenceNetwork::getActualChangeTime; private static final Function<ReferenceNetwork, UUID> idExtractor = ReferenceNetwork::getEntityId; @Test public void testFilterByStartTime() { // case 1: filter with start time before all networks, should find all. List<ReferenceNetwork> filtered = FilterUtility.filterByStartTime( networks, changeTime1.minusSeconds(1), timeExtractor, idExtractor); assertNoDuplicates(filtered); assertEquals(networks, filtered); // case 2: filter with start time equal to first network change time, should find all. filtered = FilterUtility.filterByStartTime( networks, changeTime1, timeExtractor, idExtractor); assertNoDuplicates(filtered); assertEquals(networks, filtered); // case 3: filter by time after first network change time, should find all filtered = FilterUtility.filterByStartTime(networks, changeTime1.plusSeconds(1), timeExtractor, idExtractor); assertNoDuplicates(filtered); assertEquals(networks, filtered); // case 4: filter by time at 2nd network came online, should find all. filtered = FilterUtility.filterByStartTime(networks, changeTime2, timeExtractor, idExtractor); assertNoDuplicates(filtered); assertEquals(networks, filtered); // case 5: filter by time of network_v2, should find {network_v2, network2, network2_v2} // (exclude first 'network' because it was overtaken by network_v2) filtered = FilterUtility.filterByStartTime(networks, changeTime3, timeExtractor, idExtractor); assertNoDuplicates(filtered); assertEquals(List.of(TestFixtures.network2, TestFixtures.network_v2, TestFixtures.network2_v2), filtered); // case 6: filter by time of network2_v2, should find {network_v2, network2_v2} // (exclude 'network2' because it was overtaken by network2_v2) filtered = FilterUtility.filterByStartTime(networks, changeTime4, timeExtractor, idExtractor); assertNoDuplicates(filtered); assertEquals(List.of(TestFixtures.network_v2, TestFixtures.network2_v2), filtered); // case 7: filter by time after network2_v2, should find {network_v2, network2_v2} filtered = FilterUtility.filterByStartTime(networks, changeTime4.plusSeconds(1), timeExtractor, idExtractor); assertNoDuplicates(filtered); assertEquals(List.of(TestFixtures.network_v2, TestFixtures.network2_v2), filtered); } @Test public void testFilterByEndTime() { // case 1: filter with end time before all networks, should find none List<ReferenceNetwork> filtered = FilterUtility.filterByEndTime( networks, changeTime1.minusSeconds(1), timeExtractor); assertNotNull(filtered); assertTrue(filtered.isEmpty()); // case 2: filter with end time equal to first network change time, should only find first network. filtered = FilterUtility.filterByEndTime( networks, changeTime1, timeExtractor); assertEquals(List.of(TestFixtures.network), filtered); // case 3: filter with end time after first network change time (but before network2 change time), // should only find first network filtered = FilterUtility.filterByEndTime( networks, changeTime1.plusSeconds(1), timeExtractor); assertEquals(List.of(TestFixtures.network), filtered); // case 4: filter with end time equal to second network change time, should find // {network, network2}. filtered = FilterUtility.filterByEndTime( networks, changeTime2, timeExtractor); assertNoDuplicates(filtered); assertEquals(List.of(TestFixtures.network, TestFixtures.network2), filtered); // case 5: filter with end time equal to network_v2 change time, should find // {network, network2, network_v2} filtered = FilterUtility.filterByEndTime( networks, changeTime3, timeExtractor); assertNoDuplicates(filtered); assertEquals(List.of(TestFixtures.network, TestFixtures.network2, TestFixtures.network_v2), filtered); // case 6: filter with end time equal to network2_v2 change time, // should find all networks filtered = FilterUtility.filterByEndTime( networks, changeTime4, timeExtractor); assertNoDuplicates(filtered); assertEquals(TestFixtures.allNetworks, filtered); // case 7: filter with end time after network2_v2 change time, // should find all networks filtered = FilterUtility.filterByEndTime( networks, changeTime4.plusSeconds(1), timeExtractor); assertNoDuplicates(filtered); assertEquals(TestFixtures.allNetworks, filtered); } @Test public void filterByStartTimeNullArgumentValidationTest() throws Exception { TestUtilities.checkStaticMethodValidatesNullArguments(FilterUtility.class, "filterByStartTime", networks, changeTime1, timeExtractor, idExtractor); } @Test public void filterByEndTimeNullArgumentValidationTest() throws Exception { TestUtilities.checkStaticMethodValidatesNullArguments(FilterUtility.class, "filterByEndTime", networks, changeTime1, timeExtractor); } private static <T> void assertNoDuplicates(List<T> elems) { assertEquals(new HashSet<>(elems).size(), elems.size()); } }
48.19697
111
0.762496
88932e0697d774582e4ccf6879e9d6cfd911b711
2,286
package com.slugterra.model; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; public class ModelRope extends ModelBase { //fields ModelRenderer Shape1; ModelRenderer Shape3; ModelRenderer Shape4; ModelRenderer Shape5; ModelRenderer Shape6; public ModelRope() { textureWidth = 32; textureHeight = 32; Shape1 = new ModelRenderer(this, 0, 0); Shape1.addBox(-2F, 0F, -2F, 4, 16, 4); Shape1.setRotationPoint(0F, 0F, 0F); Shape1.setTextureSize(32, 32); Shape1.mirror = true; setRotation(Shape1, 0F, 0F, 0F); Shape3 = new ModelRenderer(this, 4, 0); Shape3.addBox(0F, 0F, 0F, 2, 2, 2); Shape3.setRotationPoint(-3F, 4F, 0F); Shape3.setTextureSize(32, 32); Shape3.mirror = true; setRotation(Shape3, 0F, 0F, 0F); Shape4 = new ModelRenderer(this, 4, 0); Shape4.addBox(0F, 0F, 0F, 2, 2, 2); Shape4.setRotationPoint(1F, 11F, -3F); Shape4.setTextureSize(32, 32); Shape4.mirror = true; setRotation(Shape4, 0F, 0F, 0F); Shape5 = new ModelRenderer(this, 4, 0); Shape5.addBox(0F, 0F, 0F, 2, 2, 2); Shape5.setRotationPoint(1F, 1F, 1F); Shape5.setTextureSize(32, 32); Shape5.mirror = true; setRotation(Shape5, 0F, 0F, 0F); Shape6 = new ModelRenderer(this, 4, 0); Shape6.addBox(0F, 0F, 0F, 2, 2, 2); Shape6.setRotationPoint(-1F, 12F, 1F); Shape6.setTextureSize(32, 32); Shape6.mirror = true; setRotation(Shape6, 0F, 0F, 0F); } public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.render(entity, f, f1, f2, f3, f4, f5); setRotationAngles(f, f1, f2, f3, f4, f5, entity); Shape1.render(f5); Shape3.render(f5); Shape4.render(f5); Shape5.render(f5); Shape6.render(f5); } private void setRotation(ModelRenderer model, float x, float y, float z) { model.rotateAngleX = x; model.rotateAngleY = y; model.rotateAngleZ = z; } public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); } }
29.688312
105
0.634296
a818354e40fe2ecfed225742502551cfdfde94cf
3,367
package com.medicalappointmentsonline.MedicalAppointmentsOnline; import com.vaadin.server.FontAwesome; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Component; import com.vaadin.ui.CssLayout; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme; @SuppressWarnings("serial") public class MenuView extends CustomComponent { public MenuView(){ setPrimaryStyleName("valo-menu"); setSizeUndefined(); setCompositionRoot(buildContent()); } private Component buildContent() { final CssLayout menuContent = new CssLayout(); menuContent.addStyleName(ValoTheme.MENU_PART); menuContent.setWidth(null); menuContent.setHeight("100%"); menuContent.addComponent(buildTitle()); menuContent.addComponent(buildMenuItems()); return menuContent; } private Component buildTitle() { Label logo = new Label("<strong>Witaj!</strong>", ContentMode.HTML); logo.setSizeUndefined(); VerticalLayout logoWrapper = new VerticalLayout(logo); logoWrapper.setComponentAlignment(logo, Alignment.MIDDLE_CENTER); logoWrapper.addStyleName("valo-menu-title"); return logoWrapper; } private Component buildMenuItems() { CssLayout menuItemsLayout = new CssLayout(); menuItemsLayout.addStyleName("valo-menuitems"); menuItemsLayout.addComponent(new AppointmentButton()); menuItemsLayout.addComponent(new HistoryButton()); menuItemsLayout.addComponent(new ProfileButton()); menuItemsLayout.addComponent(new LogoutButton()); return menuItemsLayout; } public class HistoryButton extends Button { public HistoryButton(){ setPrimaryStyleName("valo-menu-item"); setCaption("Moje wizyty"); setIcon(FontAwesome.BRIEFCASE); addClickListener(new ClickListener() { @Override public void buttonClick(final ClickEvent event) { getUI().getNavigator().navigateTo("history"); } }); } } public class LogoutButton extends Button { public LogoutButton(){ setPrimaryStyleName("valo-menu-item"); setCaption("Wyloguj"); setIcon(FontAwesome.SIGN_OUT); addClickListener(new ClickListener() { @Override public void buttonClick(final ClickEvent event) { getSession().setAttribute("user", null); getUI().getNavigator().navigateTo(""); } }); } } public class ProfileButton extends Button { public ProfileButton(){ setPrimaryStyleName("valo-menu-item"); setCaption("Profil"); setIcon(FontAwesome.INFO); addClickListener(new ClickListener() { @Override public void buttonClick(final ClickEvent event) { getUI().getNavigator().navigateTo(ProfileView.NAME); } }); } } public class AppointmentButton extends Button { public AppointmentButton(){ setPrimaryStyleName("valo-menu-item"); setCaption("Umów wizytę"); setIcon(FontAwesome.ARCHIVE); addClickListener(new ClickListener() { @Override public void buttonClick(final ClickEvent event) { getUI().getNavigator().navigateTo(AppointmentsMainView.NAME); } }); } } }
30.609091
74
0.69112
1b951c3fcf70c052c82b7adbad1b2b9b19acab3c
875
package com.github.housepower.jdbc; import com.github.housepower.jdbc.tool.EmbeddedDriver; import org.junit.Assert; import org.junit.Test; import java.sql.DriverManager; import java.util.Properties; public class ClickhouseDriverRegisterTest { private static final int SERVER_PORT = Integer.valueOf(System.getProperty("CLICK_HOUSE_SERVER_PORT", "9000")); @Test public void successfullyCreateConnection() throws Exception { Properties properties = new Properties(); properties.setProperty("user", "user"); properties.setProperty("password", "password"); String mockedUrl = EmbeddedDriver.EMBEDDED_DRIVER_PREFIX + "//127.0.0.1:" + SERVER_PORT; DriverManager.registerDriver(new EmbeddedDriver()); Assert.assertEquals(EmbeddedDriver.MOCKED_CONNECTION, DriverManager.getConnection(mockedUrl, properties)); } }
33.653846
114
0.749714
16a2a82847f0d301d97f9c6205f75923c6f92e21
149
package lucassbeiler.aplicativo.models; public class Reacao { private Integer id; public Reacao(Integer id) { this.id = id; } }
16.555556
39
0.651007
84bf6d9dff40dc57d7e70c003f6034efa57c78fd
255
package server.controller.message; import lombok.Data; @Data public class News { private String id; // News id private String head_line; // News headline private String times; // New set and modification time private String data; // News contents }
23.181818
56
0.752941
7f53372908db032d7b0cdff180215fb603f722e9
4,884
package com.yilian.luckypurchase.fragment; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.View; import com.chad.library.adapter.base.BaseQuickAdapter; import com.yilian.luckypurchase.R; import com.yilian.luckypurchase.activity.LuckyUnboxingActivity; import com.yilian.luckypurchase.adapter.SnatchShowAdapter; import com.yilian.mylibrary.CheckServiceReturnEntityUtil; import com.yilian.mylibrary.CommonUtils; import com.yilian.mylibrary.Constants; import com.yilian.mylibrary.RequestOftenKey; import com.yilian.networkingmodule.entity.SnatchShowListEntity; import com.yilian.networkingmodule.httpresult.HttpResultBean; import com.yilian.networkingmodule.retrofitutil.RetrofitUtils2; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * @author Created by LYQ on 2017/10/30. * 晒单记录 */ public class PriceRecordSnatchShowFragment extends BaseMyRecordFragment { private SnatchShowAdapter adapter; @Override protected RecyclerView.Adapter getAdapter() { return null; } @Override public void getData() { if (null==adapter){ adapter = new SnatchShowAdapter(R.layout.lucky_item_record_show_list); recyclerView.setAdapter(adapter); adapter.setOnLoadMoreListener(this, recyclerView); initAdapterListener(); } /** * 我的晒单列表固定传值 * type 0我的夺宝晒单记录 * snatchIndex 0所有 */ RetrofitUtils2.getInstance(mContext).setToken(RequestOftenKey.getToken(mContext)).setDeviceIndex(RequestOftenKey.getDeviceIndex(mContext)) .getSnatchShowList("1", page, "0", new Callback<SnatchShowListEntity>() { @Override public void onResponse(Call<SnatchShowListEntity> call, Response<SnatchShowListEntity> response) { HttpResultBean bean = response.body(); if (CheckServiceReturnEntityUtil.checkServiceReturnEntity(mContext, bean)) { if (CommonUtils.serivceReturnCode(mContext, bean.code, bean.msg)) { switch (bean.code) { case 1: List<SnatchShowListEntity.SnatchInfoBean> showSnatchInfo = response.body().snatchInfo; if (page > 0) { if (null==showSnatchInfo||showSnatchInfo.size()<=0){ adapter.loadMoreEnd(); } adapter.addData(showSnatchInfo); } else { if (null != showSnatchInfo && showSnatchInfo.size() > 0) { adapter.setNewData(showSnatchInfo); } else { adapter.setEmptyView(getEmptyView()); } if (Constants.PAGE_COUNT>showSnatchInfo.size()){ adapter.loadMoreEnd(); }else { adapter.loadMoreComplete(); } } break; default: break; } } } refreshLayout.setRefreshing(false); } @Override public void onFailure(Call<SnatchShowListEntity> call, Throwable t) { refreshLayout.setRefreshing(false); if (page>0){ showToast(R.string.aliwx_net_null_setting); }else { adapter.setEmptyView(getErrorView()); } } }); } public void initAdapterListener() { adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() { @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) { SnatchShowListEntity.SnatchInfoBean bean = (SnatchShowListEntity.SnatchInfoBean) adapter.getItem(position); Intent intent = new Intent(mContext, LuckyUnboxingActivity.class); intent.putExtra("activity_id", bean.commentIndex); startActivity(intent); } }); } }
43.221239
146
0.518018
12a8a64dbc7be2a6e7ea827f8f26c3971bfc4663
2,322
package ml.alternet.parser.util; /** * Wraps a value subject to transformation * (the value may exist in its source form, * or its target form). * * @author Philippe Poulard * * @param <Source> The source type * @param <Target> The target type */ public class Dual<Source, Target> { private Object value; private boolean isSource; /** * Set this value as a source. * * @param source The source value. * * @return This * * @param <T> The concrete dual type. */ @SuppressWarnings("unchecked") public <T extends Dual<Source, Target>> T setSource(Source source) { this.value = source; this.isSource = true; return (T) this; } /** * Set this value as a target. * * @param target The target value. * * @return This * * @param <T> The concrete dual type. */ @SuppressWarnings("unchecked") public <T extends Dual<Source, Target>> T setTarget(Target target) { this.value = target; this.isSource = false; return (T) this; } /** * Set this value and this type. * * @param value The value. * * @return This * * @param <T> The concrete dual type. */ @SuppressWarnings("unchecked") public <T extends Dual<Source, Target>> T setValue(Dual<Source, Target> value) { this.value = value.value; this.isSource = value.isSource; return (T) this; } /** * Return this source value. * * @return The value. */ @SuppressWarnings("unchecked") public Source getSource() { return (Source) this.value; } /** * Return this target value. * * @return The value. */ @SuppressWarnings("unchecked") public Target getTarget() { return (Target) this.value; } /** * Indicates which kind of value is actually wrapped. * * @return <code>true</code> if the value is a source, * <code>false</code> otherwise. */ public boolean isSource() { return this.isSource; } @Override public String toString() { return (isSource() ? "⦉" : "⦗") + (this.value == null ? "" : this.value.toString()) + (isSource() ? "⦊" : "⦘"); } }
22.326923
84
0.552972
926a1ee9031ab713001aadbc2f42b4e6f1b5a801
3,773
/** * Copyright (c) Dell Inc., or its subsidiaries. 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 */ package io.pravega.client.tables.impl; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.pravega.client.segment.impl.Segment; import io.pravega.client.stream.impl.SegmentWithRange; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import java.util.TreeMap; import lombok.val; import org.junit.Assert; import org.junit.Test; /** * Unit tests for the {@link KeyValueTableSegments} class. */ public class KeyValueTableSegmentsTests { private static final String SCOPE_NAME = "Scope"; private static final String STREAM_NAME = "Stream"; private static final int SEGMENT_COUNT = 16; /** * Verifies uniformity for {@link KeyValueTableSegments#getSegmentForKey(ByteBuf)}. */ @Test public void testGetSegmentForKeyByteBuf() { val testCount = 10000; val segmentsWithRange = createSegmentMap(); val s = new KeyValueTableSegments(segmentsWithRange, null); Assert.assertEquals(segmentsWithRange.size(), s.getSegmentCount()); val hits = new HashMap<Segment, Double>(); val rnd = new Random(0); for (int i = 0; i < testCount; i++) { byte[] a1 = new byte[KeyFamilySerializer.PREFIX_LENGTH]; byte[] a2 = new byte[128]; rnd.nextBytes(a1); rnd.nextBytes(a2); val segment = s.getSegmentForKey(Unpooled.wrappedBuffer(Unpooled.wrappedBuffer(a1), Unpooled.wrappedBuffer(a2))); hits.put(segment, hits.getOrDefault(segment, 0.0) + 1.0 / testCount); } // Since the SegmentsWithRange already contain a normalized distribution of ranges (over the interval [0,1]), // all we need to do is verify that the number of hits (normalized) is about the same as the range length. for (val e : segmentsWithRange.entrySet()) { double expected = e.getValue().getRange().getHigh() - e.getValue().getRange().getLow(); double actual = hits.get(e.getValue().getSegment()); Assert.assertEquals("Unexpected count for range " + e.getValue().getRange() + " for " + s, expected, actual, 0.01); } } @Test public void testEquals() { val s1 = new KeyValueTableSegments(createSegmentMap(), null); val s2 = new KeyValueTableSegments(createSegmentMap(), null); Assert.assertEquals(s1.hashCode(), s2.hashCode()); Assert.assertEquals(s1, s2); } private TreeMap<Double, SegmentWithRange> createSegmentMap() { final int rangeIncrease = 10; int totalRangeLength = 0; val ranges = new ArrayList<Integer>(); for (int i = 0; i < SEGMENT_COUNT; i++) { int rangeLength = (ranges.size() == 0 ? 0 : ranges.get(i - 1)) + rangeIncrease; ranges.add(rangeLength); totalRangeLength += rangeLength; } val result = new TreeMap<Double, SegmentWithRange>(); int rangeLow = 0; for (int i = 0; i < ranges.size(); i++) { int rangeLength = ranges.get(i); int rangeHigh = rangeLow + rangeLength; val segment = new Segment(SCOPE_NAME, STREAM_NAME, i); val segmentWithRange = new SegmentWithRange(segment, (double) rangeLow / totalRangeLength, (double) rangeHigh / totalRangeLength); result.put(segmentWithRange.getRange().getHigh(), segmentWithRange); rangeLow = rangeHigh; } return result; } }
40.138298
142
0.649351
8b9590c49493e9fef1b039855f3004679be69c03
2,680
/* * Copyright 2012 Sebastian Annies, Hamburg * * 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.mp4parser.muxer; import org.mp4parser.boxes.iso14496.part12.CompositionTimeToSample; import org.mp4parser.boxes.iso14496.part12.SampleDependencyTypeBox; import org.mp4parser.boxes.iso14496.part12.SampleDescriptionBox; import org.mp4parser.boxes.iso14496.part12.SubSampleInformationBox; import org.mp4parser.boxes.samplegrouping.GroupEntry; import java.io.Closeable; import java.util.List; import java.util.Map; /** * Represents a Track. A track is a timed sequence of related samples.<br> * <b>NOTE:</b> * For media data, a track corresponds to a sequence of images or sampled audio; for hint tracks, a track * corresponds to a streaming channel. */ public interface Track extends Closeable { SampleDescriptionBox getSampleDescriptionBox(); /** * Each samples is covers a small time span in a video. This method * returns the duration for each sample in track timescale. The array * must contain exactly as many samples as {@link #getSamples()} contains. * * @return an array of ticks */ long[] getSampleDurations(); /** * The duration of the track in track timescale. It's the sum of all samples' duration and does NOT include * any edits. * * @return the track's duration */ long getDuration(); List<CompositionTimeToSample.Entry> getCompositionTimeEntries(); long[] getSyncSamples(); List<SampleDependencyTypeBox.Entry> getSampleDependencies(); TrackMetaData getTrackMetaData(); String getHandler(); /** * The list of all samples. * * @return this track's samples */ List<Sample> getSamples(); public SubSampleInformationBox getSubsampleInformationBox(); /** * A name for identification purposes. Might return the underlying filename or network address or any * other identifier. For informational/debug only. This is no metadata! * * @return the track's name */ public String getName(); public List<Edit> getEdits(); public Map<GroupEntry, long[]> getSampleGroups(); }
30.804598
111
0.718657
d3b470ea5e13432dd8ff4896a8c106d069203cb6
9,334
/* * Copyright (c) 2008-2019, Hazelcast, 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.hazelcast.jet.core.metrics; import com.hazelcast.jet.Job; import com.hazelcast.jet.TestInClusterSupport; import com.hazelcast.jet.config.JobConfig; import com.hazelcast.jet.config.ProcessingGuarantee; import com.hazelcast.jet.pipeline.JournalInitialPosition; import com.hazelcast.jet.pipeline.Pipeline; import com.hazelcast.jet.pipeline.Sinks; import com.hazelcast.jet.pipeline.Sources; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.Collection; import java.util.List; import java.util.Map; import static com.hazelcast.jet.core.JobStatus.FAILED; import static com.hazelcast.jet.core.JobStatus.RUNNING; import static com.hazelcast.jet.core.JobStatus.SUSPENDED; import static com.hazelcast.jet.core.metrics.JobMetrics_BatchTest.JOB_CONFIG_WITH_METRICS; import static org.junit.Assert.assertEquals; public class JobMetrics_StreamTest extends TestInClusterSupport { private static final String NOT_FILTER_OUT_PREFIX = "ok"; private static final String FILTER_OUT_PREFIX = "nok"; private static final String FLAT_MAP_AND_FILTER_VERTEX = "fused(map, filter)"; private static final String RECEIVE_COUNT_METRIC = "receivedCount"; private static final String EMITTED_COUNT_METRIC = "emittedCount"; private static String journalMapName; private static String sinkListName; @Before public void before() { journalMapName = JOURNALED_MAP_PREFIX + randomString(); sinkListName = "sinkList" + randomString(); } @Test public void when_jobRunning_then_metricsEventuallyExist() { Map<String, String> map = jet().getMap(journalMapName); putIntoMap(map, 2, 1); List<String> sink = jet().getList(sinkListName); Pipeline p = createPipeline(); // When Job job = jet().newJob(p); assertTrueEventually(() -> assertEquals(2, sink.size())); // Then assertTrueEventually(() -> assertMetrics(job.getMetrics(), 3, 1)); putIntoMap(map, 1, 1); assertTrueEventually(() -> assertEquals(3, sink.size())); // Then assertTrueEventually(() -> assertMetrics(job.getMetrics(), 5, 2)); } @Test public void when_jobCancelled_then_terminalMetricsExist() { Map<String, String> map = jet().getMap(journalMapName); putIntoMap(map, 2, 1); List<String> sink = jet().getList(sinkListName); Pipeline p = createPipeline(); Job job = jet().newJob(p, JOB_CONFIG_WITH_METRICS); putIntoMap(map, 1, 1); assertTrueEventually(() -> assertEquals(3, sink.size())); // When job.cancel(); assertJobStatusEventually(job, FAILED); // Then assertTrueEventually(() -> assertMetrics(job.getMetrics(), 5, 2)); } @Test public void when_jobWithExactlyOnceSuspendAndResume_then_metricsReset() { Map<String, String> map = jet().getMap(journalMapName); putIntoMap(map, 2, 1); List<String> sink = jet().getList(sinkListName); Pipeline p = createPipeline(); JobConfig jobConfig = new JobConfig() .setStoreMetricsAfterJobCompletion(true) .setProcessingGuarantee(ProcessingGuarantee.EXACTLY_ONCE); // When Job job = jet().newJob(p, jobConfig); putIntoMap(map, 1, 1); assertTrueEventually(() -> assertEquals(3, sink.size())); assertTrueEventually(() -> assertMetrics(job.getMetrics(), 5, 2)); job.suspend(); assertJobStatusEventually(job, SUSPENDED); assertTrueEventually(() -> assertMetrics(job.getMetrics(), 5, 2)); putIntoMap(map, 1, 1); assertTrueAllTheTime(() -> assertMetrics(job.getMetrics(), 5, 2), 5); job.resume(); assertJobStatusEventually(job, RUNNING); assertTrueEventually(() -> assertEquals(4, sink.size())); // Then assertTrueEventually(() -> assertMetrics(job.getMetrics(), 2, 1)); putIntoMap(map, 1, 1); assertTrueEventually(() -> assertEquals(5, sink.size())); // Then assertTrueEventually(() -> assertMetrics(job.getMetrics(), 4, 2)); job.cancel(); assertJobStatusEventually(job, FAILED); assertMetrics(job.getMetrics(), 4, 2); } @Test public void when_jobRestarted_then_metricsReset() { Map<String, String> map = jet().getMap(journalMapName); putIntoMap(map, 2, 1); List<String> sink = jet().getList(sinkListName); Pipeline p = createPipeline(); Job job = jet().newJob(p, JOB_CONFIG_WITH_METRICS); assertTrueEventually(() -> assertEquals(2, sink.size())); assertTrueEventually(() -> assertMetrics(job.getMetrics(), 3, 1)); putIntoMap(map, 1, 1); assertTrueEventually(() -> assertEquals(3, sink.size())); assertTrueEventually(() -> assertMetrics(job.getMetrics(), 5, 2)); // When job.restart(); assertJobStatusEventually(job, RUNNING); assertTrueEventually(() -> assertEquals(6, sink.size())); // Then assertTrueEventually(() -> assertMetrics(job.getMetrics(), 5, 2)); putIntoMap(map, 1, 1); assertTrueEventually(() -> assertEquals(7, sink.size())); assertTrueEventually(() -> assertMetrics(job.getMetrics(), 7, 3)); job.cancel(); assertJobStatusEventually(job, FAILED); assertMetrics(job.getMetrics(), 7, 3); } @Test public void when_jobRestarted_then_metricsReset_withJournal() { Map<String, String> map = jet().getMap(journalMapName); putIntoMap(map, 2, 1); List<String> sink = jet().getList(sinkListName); Pipeline p = createPipeline(JournalInitialPosition.START_FROM_CURRENT); Job job = jet().newJob(p, JOB_CONFIG_WITH_METRICS); assertJobStatusEventually(job, RUNNING); assertTrueEventually(() -> assertMetrics(job.getMetrics(), 0, 0)); putIntoMap(map, 2, 1); assertTrueEventually(() -> assertEquals(2, sink.size())); assertTrueEventually(() -> assertMetrics(job.getMetrics(), 3, 1)); // When job.restart(); assertJobStatusEventually(job, RUNNING); assertTrueEventually(() -> assertEquals(2, sink.size())); // Then assertTrueEventually(() -> assertMetrics(job.getMetrics(), 0, 0)); putIntoMap(map, 1, 1); assertTrueEventually(() -> assertEquals(3, sink.size())); assertTrueEventually(() -> assertMetrics(job.getMetrics(), 2, 1)); job.cancel(); assertJobStatusEventually(job, FAILED); assertMetrics(job.getMetrics(), 2, 1); } private Pipeline createPipeline() { return createPipeline(JournalInitialPosition.START_FROM_OLDEST); } private Pipeline createPipeline(JournalInitialPosition position) { Pipeline p = Pipeline.create(); p.<Map.Entry<String, String>>readFrom(Sources.mapJournal(journalMapName, position)) .withIngestionTimestamps() .map(map -> map.getKey()) .filter(word -> !word.startsWith(FILTER_OUT_PREFIX)) .writeTo(Sinks.list(sinkListName)); return p; } private void putIntoMap(Map<String, String> map, int notFilterOutItemsCount, int filterOutItemsCount) { for (int i = 0; i < notFilterOutItemsCount; i++) { map.put(NOT_FILTER_OUT_PREFIX + randomString(), "whateverHere"); } for (int i = 0; i < filterOutItemsCount; i++) { map.put(FILTER_OUT_PREFIX + randomString(), "whateverHere"); } } private void assertMetrics(JobMetrics metrics, int allItems, int filterOutItems) { Assert.assertNotNull(metrics); assertEquals(allItems, sumValueFor(metrics, "mapJournalSource(" + journalMapName + ")", EMITTED_COUNT_METRIC)); assertEquals(allItems, sumValueFor(metrics, FLAT_MAP_AND_FILTER_VERTEX, RECEIVE_COUNT_METRIC)); assertEquals(allItems - filterOutItems, sumValueFor(metrics, FLAT_MAP_AND_FILTER_VERTEX, EMITTED_COUNT_METRIC)); assertEquals(allItems - filterOutItems, sumValueFor(metrics, "listSink(" + sinkListName + ")", RECEIVE_COUNT_METRIC)); } private long sumValueFor(JobMetrics metrics, String vertex, String metric) { Collection<Measurement> measurements = metrics .filter(MeasurementPredicates.tagValueEquals(MetricTags.VERTEX, vertex) .and(MeasurementPredicates.tagValueEquals(MetricTags.ORDINAL, "snapshot").negate())) .get(metric); return measurements.stream().mapToLong(Measurement::value).sum(); } }
37.187251
120
0.660489
41e1c8a3de35f624f3bc1336783be5689f717e83
3,900
package fibex.structures; import java.util.Iterator; import net.asam.xml.fbx.ECUTYPE; import net.asam.xml.fbx.FIBEXDocument; /** * This class implements all functionality of FibexECU for FIBEX 2.0.1 * * @author TUM CREATE - RP3 - Philipp Mundhenk */ public class FibexECU2_0_1 extends FibexECU { Boolean controllersLoaded = false; /** * This constructor creates a new ECU * * @param name * name of ECU */ public FibexECU2_0_1(String name) { super(name); } /** * This constructor creates a new instance of ECU. Access via getInstance() * * @param ecuRepresentation * reference to ECU node * @param docReference * reference to FIBEX document */ protected FibexECU2_0_1(Object ecuRepresentation, Object docReference) { super(ecuRepresentation, docReference); } /** * This method returns the ID of the ECU node * * @return * ID of ECU node */ @Override public String getId() { if(this.id == null) { return ((ECUTYPE)ecuRepresentation).getID(); } else { return this.id; } } /** * This method returns the name (short-name) of the ECU * * @return * name (short-name) of the ECU */ public String getName() { if(this.name == null) { return ((ECUTYPE)ecuRepresentation).getSHORTNAME(); } else { return this.name; } } /** * This method creates and returns a new controller * * @param name * name of controller to create * @return * newly created controller */ @Override public FibexController getNewController(String name) { if(this.name == null) { /* ECU is linked to FIBEX */ if(!controllersLoaded) { for (int i = 0; i < ((ECUTYPE)ecuRepresentation).getCONTROLLERS().getCONTROLLERArray().length; i++) { FibexController controller = FibexController2_0_1.getInstance(((ECUTYPE)ecuRepresentation).getCONTROLLERS().getCONTROLLERArray(i), docReference); if(controller != null) { controllers.add(controller); } } controllersLoaded = true; } } for (Iterator<FibexController> i = controllers.iterator(); i.hasNext();) { FibexController controller = (FibexController) i.next(); if(controller.getName().equals(name)) { return controller; } } FibexController controller = new FibexController2_0_1(name); this.controllers.add(controller); return controller; } /** * This method saves the ECU and all its subcomponents * * @param docReference * reference to FIBEX document * @param additionalData * addition data */ @Override public void save(Object docReference, Object... additionalData) { if(!(this.name == null)) { String clusterType = (String)additionalData[0]; if(((FIBEXDocument)docReference).getFIBEX().getELEMENTS().getECUS() == null) { ((FIBEXDocument)docReference).getFIBEX().getELEMENTS().addNewECUS(); } ECUTYPE ecu = ((FIBEXDocument)docReference).getFIBEX().getELEMENTS().getECUS().addNewECU(); ecu.setSHORTNAME(name); ecu.setID(getId()); ecu.addNewDESC().setStringValue("This is an ECU"); ecu.addNewCONTROLLERS(); ecu.addNewCONNECTORS(); for (Iterator<FibexController> i = controllers.iterator(); i.hasNext();) { FibexController controller = (FibexController) i.next(); controller.save(docReference, ecu.getCONTROLLERS(), ecu.getCONNECTORS(), clusterType); } } } /** * This method creates and returns a new instance of the ECU. * * @param ecuRepresentation * reference to ECU node * @param docReference * reference to FIBEX document * @return * newly created ECU, null if given wrong input nodes given */ public static FibexECU getInstance(Object ecuRepresentation, Object docReference) { if(ecuRepresentation instanceof net.asam.xml.fbx.ECUTYPE) { return new FibexECU2_0_1(ecuRepresentation, docReference); } else { return null; } } }
22.033898
150
0.676667
aa18e54838321af9045ed946e10e8a87cb2adb75
36,283
package org.yeastrc.xlink.www.searcher; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import org.yeastrc.xlink.base.constants.Database_OneTrueZeroFalse_Constants; import org.yeastrc.xlink.base_searcher.PsmCountForSearchIdReportedPeptideIdSearcher; import org.yeastrc.xlink.db.DBConnectionFactory; import org.yeastrc.xlink.dto.AnnotationDataBaseDTO; import org.yeastrc.xlink.dto.AnnotationTypeDTO; import org.yeastrc.xlink.dto.PsmAnnotationDTO; import org.yeastrc.xlink.dto.SearchReportedPeptideAnnotationDTO; import org.yeastrc.xlink.enum_classes.FilterDirectionType; import org.yeastrc.xlink.enum_classes.Yes_No__NOT_APPLICABLE_Enum; import org.yeastrc.xlink.searcher_constants.SearcherGeneralConstants; import org.yeastrc.xlink.searcher_psm_peptide_cutoff_objects.SearcherCutoffValuesAnnotationLevel; import org.yeastrc.xlink.searcher_psm_peptide_cutoff_objects.SearcherCutoffValuesSearchLevel; import org.yeastrc.xlink.utils.XLinkUtils; import org.yeastrc.xlink.www.constants.DynamicModificationsSelectionConstants; import org.yeastrc.xlink.www.constants.PeptideViewLinkTypesConstants; import org.yeastrc.xlink.www.searcher_utils.DefaultCutoffsExactlyMatchAnnTypeDataToSearchData; import org.yeastrc.xlink.www.searcher_utils.DefaultCutoffsExactlyMatchAnnTypeDataToSearchData.DefaultCutoffsExactlyMatchAnnTypeDataToSearchDataResult; import org.yeastrc.xlink.www.searcher_via_cached_data.request_objects_for_searchers_for_cached_data.ReportedPeptideBasicObjectsSearcherRequestParameters; import org.yeastrc.xlink.www.searcher_via_cached_data.return_objects_from_searchers_for_cached_data.ReportedPeptideBasicObjectsSearcherResult; import org.yeastrc.xlink.www.searcher_via_cached_data.return_objects_from_searchers_for_cached_data.ReportedPeptideBasicObjectsSearcherResultEntry; /** * Return basic objects for Reported Peptide Search * */ public class ReportedPeptideBasicObjectsSearcher { private static final Logger log = LoggerFactory.getLogger( ReportedPeptideBasicObjectsSearcher.class); private ReportedPeptideBasicObjectsSearcher() { } private static final ReportedPeptideBasicObjectsSearcher _INSTANCE = new ReportedPeptideBasicObjectsSearcher(); public static ReportedPeptideBasicObjectsSearcher getInstance() { return _INSTANCE; } public static enum ReturnOnlyReportedPeptidesWithMonolinks { YES, NO } /** * Should it use the optimization of Peptide and PSM defaults to skip joining the tables with the annotation values? */ private final boolean USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES = false; // UNTESTED for a value of "true" /** * UNTESTED for a value of "true" * * If make true, need to change calling code since best PSM annotation values will not be populated * * Also, test web page and/or webservice */ // private final boolean USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES = true; // UNTESTED for a value of "true" private final String PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS = "psm_fltrbl_tbl_"; private final String PEPTIDE_VALUE_FILTER_TABLE_ALIAS = "srch__rep_pept_fltrbl_tbl_"; private final String SQL_FIRST_PART = "SELECT unified_rp__search__rep_pept__generic_lookup.reported_peptide_id, " + " unified_rp__search__rep_pept__generic_lookup.unified_reported_peptide_id, " + " unified_rp__search__rep_pept__generic_lookup.link_type, " + " unified_rp__search__rep_pept__generic_lookup.psm_num_at_default_cutoff, " + " unified_rp__search__rep_pept__generic_lookup.num_unique_psm_at_default_cutoff "; private final String SQL_MAIN_FROM_START = " FROM unified_rp__search__rep_pept__generic_lookup "; private final String SQL_LAST_PART = ""; // Removed since not needed. // A WARN log message will be written if duplicate reported_peptide_id are found in the result set // " GROUP BY unified_rp__search__rep_pept__generic_lookup.reported_peptide_id "; /** * If Dynamic Mods are selected, this gets added after the Join to the Dynamic Mods subselect */ private final String SQL_MAIN_WHERE_START = " WHERE unified_rp__search__rep_pept__generic_lookup.search_id = ? "; // If Dynamic Mods are selected, one of these three gets added after the main where clause // No Mods Only private static final String SQL_NO_MODS_ONLY__MAIN_WHERE_CLAUSE = " AND unified_rp__search__rep_pept__generic_lookup.has_dynamic_modifictions = " + Database_OneTrueZeroFalse_Constants.DATABASE_FIELD_FALSE + " "; // Yes Mods Only private static final String SQL_YES_MODS_ONLY_MAIN_WHERE_CLAUSE = " AND unified_rp__search__rep_pept__generic_lookup.has_dynamic_modifictions = " + Database_OneTrueZeroFalse_Constants.DATABASE_FIELD_TRUE + " "; private static final String SQL_NO_AND_YES_MODS__MAIN_WHERE_CLAUSE = " AND ( " // No Mods + "unified_rp__search__rep_pept__generic_lookup.has_dynamic_modifictions = " + Database_OneTrueZeroFalse_Constants.DATABASE_FIELD_FALSE + " OR " // Yes Mods: // need srch_id_rep_pep_id_for_mod_masses.search_id IS NOT NULL // since doing LEFT OUTER JOIN when both Yes and No Mods + " ( unified_rp__search__rep_pept__generic_lookup.has_dynamic_modifictions = " + Database_OneTrueZeroFalse_Constants.DATABASE_FIELD_TRUE + " AND" + " srch_id_rep_pep_id_for_mod_masses.search_id IS NOT NULL " + " ) " + " ) "; // Yes Monolinks Only private static final String SQL_YES_MOONOLINKS_ONLY_MAIN_WHERE_CLAUSE = " AND unified_rp__search__rep_pept__generic_lookup.has_monolinks = " + Database_OneTrueZeroFalse_Constants.DATABASE_FIELD_TRUE + " "; /////////////////// // Additional SQL parts private static final String SQL_LINK_TYPE_START = " unified_rp__search__rep_pept__generic_lookup.link_type IN ( "; private static final String SQL_LINK_TYPE_END = " ) "; // Dynamic Mod processing private static final String SQL_DYNAMIC_MOD_JOIN_START = " INNER JOIN ("; private static final String SQL_DYNAMIC_MOD_AND_NO_MODS_JOIN_START = " LEFT OUTER JOIN ("; private static final String SQL_DYNAMIC_MOD_INNER_SELECT_START = " SELECT DISTINCT search_id, reported_peptide_id " + " FROM search__reported_peptide__dynamic_mod_lookup " + " WHERE search_id = ? AND dynamic_mod_mass IN ( "; private static final String SQL_DYNAMIC_MOD_JOIN_AFTER_MOD_MASSES = // After Dynamic Mod Masses " ) "; private static final String SQL_DYNAMIC_MOD_JOIN_START_LINK_TYPES = // After Dynamic Mod Masses " AND ( "; private static final String SQL_DYNAMIC_MOD_LINK_TYPE_START = " search__reported_peptide__dynamic_mod_lookup.link_type IN ( "; private static final String SQL_DYNAMIC_MOD_LINK_TYPE_END = " ) "; private static final String SQL_DYNAMIC_MOD_JOIN_AFTER_LINK_TYPES = // After Link Types " ) "; private static final String SQL_DYNAMIC_MOD_JOIN_END = " ) AS srch_id_rep_pep_id_for_mod_masses " + " ON unified_rp__search__rep_pept__generic_lookup.search_id = srch_id_rep_pep_id_for_mod_masses.search_id " + " AND unified_rp__search__rep_pept__generic_lookup.reported_peptide_id = srch_id_rep_pep_id_for_mod_masses.reported_peptide_id"; /** * Get the peptides corresponding to the given parameters * @param searchId The search we're searching * @param searcherCutoffValuesSearchLevel - PSM and Peptide cutoffs for a search id * @param linkTypes Which link types to include in the results * @param modMassSelections Which modified masses to include. Null if include all. element "" means no modifications * @param returnOnlyReportedPeptidesWithMonolinks - Only return Reported Peptides with Monolinks * @return * @throws Exception */ public ReportedPeptideBasicObjectsSearcherResult searchOnSearchIdPsmCutoffPeptideCutoff( ReportedPeptideBasicObjectsSearcherRequestParameters reportedPeptideBasicObjectsSearcherRequestParameters ) throws Exception { int searchId = reportedPeptideBasicObjectsSearcherRequestParameters.getSearchId(); SearcherCutoffValuesSearchLevel searcherCutoffValuesSearchLevel = reportedPeptideBasicObjectsSearcherRequestParameters.getSearcherCutoffValuesSearchLevel(); String[] linkTypes = reportedPeptideBasicObjectsSearcherRequestParameters.getLinkTypes(); String[] modMassSelections = reportedPeptideBasicObjectsSearcherRequestParameters.getModMassSelections(); ReturnOnlyReportedPeptidesWithMonolinks returnOnlyReportedPeptidesWithMonolinks = reportedPeptideBasicObjectsSearcherRequestParameters.getReturnOnlyReportedPeptidesWithMonolinks(); List<ReportedPeptideBasicObjectsSearcherResultEntry> entryList = new ArrayList<>(); List<SearcherCutoffValuesAnnotationLevel> peptideCutoffValuesList = searcherCutoffValuesSearchLevel.getPeptidePerAnnotationCutoffsList(); List<SearcherCutoffValuesAnnotationLevel> psmCutoffValuesList = searcherCutoffValuesSearchLevel.getPsmPerAnnotationCutoffsList(); // If null, create empty lists if ( peptideCutoffValuesList == null ) { peptideCutoffValuesList = new ArrayList<>(); } if ( psmCutoffValuesList == null ) { psmCutoffValuesList = new ArrayList<>(); } List<AnnotationTypeDTO> peptideCutoffsAnnotationTypeDTOList = new ArrayList<>( psmCutoffValuesList.size() ); List<AnnotationTypeDTO> psmCutoffsAnnotationTypeDTOList = new ArrayList<>( psmCutoffValuesList.size() ); for ( SearcherCutoffValuesAnnotationLevel searcherCutoffValuesAnnotationLevel : peptideCutoffValuesList ) { peptideCutoffsAnnotationTypeDTOList.add( searcherCutoffValuesAnnotationLevel.getAnnotationTypeDTO() ); } for ( SearcherCutoffValuesAnnotationLevel searcherCutoffValuesAnnotationLevel : psmCutoffValuesList ) { psmCutoffsAnnotationTypeDTOList.add( searcherCutoffValuesAnnotationLevel.getAnnotationTypeDTO() ); } // Determine if can use PSM count at Default Cutoff DefaultCutoffsExactlyMatchAnnTypeDataToSearchDataResult defaultCutoffsExactlyMatchAnnTypeDataToSearchDataResult = DefaultCutoffsExactlyMatchAnnTypeDataToSearchData.getInstance() .defaultCutoffsExactlyMatchAnnTypeDataToSearchData( searchId, searcherCutoffValuesSearchLevel ); boolean defaultCutoffsExactlyMatchAnnTypeDataToSearchData = defaultCutoffsExactlyMatchAnnTypeDataToSearchDataResult.isDefaultCutoffsExactlyMatchAnnTypeDataToSearchData(); ////////////////////////////////// Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; // Pre-process the dynamic mod masses selections boolean modMassSelectionsIncludesNoModifications = false; boolean modMassSelectionsIncludesYesModifications = false; List<String> modMassSelectionsWithoutNoMods = null; if ( modMassSelections != null ) { for ( String modMassSelection : modMassSelections ) { if ( DynamicModificationsSelectionConstants.NO_DYNAMIC_MODIFICATIONS_SELECTION_ITEM.equals( modMassSelection ) ) { modMassSelectionsIncludesNoModifications = true; } else { modMassSelectionsIncludesYesModifications = true; if ( modMassSelectionsWithoutNoMods == null ) { modMassSelectionsWithoutNoMods = new ArrayList<>( modMassSelections.length ); } modMassSelectionsWithoutNoMods.add( modMassSelection ); } } } ////////////////////// ///// Start building the SQL StringBuilder sqlSB = new StringBuilder( 1000 ); sqlSB.append( SQL_FIRST_PART ); /////// Add fields to result from best PSM annotation values { if ( ( ! defaultCutoffsExactlyMatchAnnTypeDataToSearchData ) || ( ! USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES ) ) { // Non-Default PSM or Peptide cutoffs so have to query on the cutoffs // Add Field retrieval for each PSM cutoff for ( int counter = 1; counter <= psmCutoffValuesList.size(); counter++ ) { sqlSB.append( " , " ); sqlSB.append( PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".annotation_type_id " ); sqlSB.append( " AS " ); sqlSB.append( PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( "_annotation_type_id " ); sqlSB.append( " , " ); sqlSB.append( PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".best_psm_value_for_ann_type_id " ); sqlSB.append( " AS " ); sqlSB.append( PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( "_best_psm_value_for_ann_type_id " ); } } } /////// Add fields to result from best Peptide annotation values { if ( ( ( ! defaultCutoffsExactlyMatchAnnTypeDataToSearchData ) ) || ( ! USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES ) ) { // Non-Default PSM or Peptide cutoffs so have to query on the cutoffs // Add inner join for each Peptide cutoff for ( int counter = 1; counter <= peptideCutoffValuesList.size(); counter++ ) { sqlSB.append( " , " ); sqlSB.append( PEPTIDE_VALUE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".annotation_type_id " ); sqlSB.append( " AS " ); sqlSB.append( PEPTIDE_VALUE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( "_annotation_type_id " ); sqlSB.append( " , " ); sqlSB.append( PEPTIDE_VALUE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".value_double " ); sqlSB.append( " AS " ); sqlSB.append( PEPTIDE_VALUE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( "_value_double " ); sqlSB.append( " , " ); sqlSB.append( PEPTIDE_VALUE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".value_string " ); sqlSB.append( " AS " ); sqlSB.append( PEPTIDE_VALUE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( "_value_string " ); } } } sqlSB.append( SQL_MAIN_FROM_START ); { if ( ( ( ! defaultCutoffsExactlyMatchAnnTypeDataToSearchData ) ) || ( ! USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES ) ) { // Non-Default PSM or Peptide cutoffs so have to query on the cutoffs // Add inner join for each PSM cutoff for ( int counter = 1; counter <= psmCutoffValuesList.size(); counter++ ) { sqlSB.append( " INNER JOIN " ); sqlSB.append( " unified_rp__search__rep_pept__best_psm_value_generic_lookup AS " ); sqlSB.append( PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( " ON " ); sqlSB.append( " unified_rp__search__rep_pept__generic_lookup.search_id = " ); sqlSB.append( PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".search_id" ); sqlSB.append( " AND " ); sqlSB.append( " unified_rp__search__rep_pept__generic_lookup.reported_peptide_id = " ); sqlSB.append( PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".reported_peptide_id" ); } } } { if ( ( ( ! defaultCutoffsExactlyMatchAnnTypeDataToSearchData ) ) || ( ! USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES ) ) { // Non-Default PSM cutoffs so have to query on the cutoffs // Add inner join for each Peptide cutoff for ( int counter = 1; counter <= peptideCutoffValuesList.size(); counter++ ) { sqlSB.append( " INNER JOIN " ); sqlSB.append( " srch__rep_pept__annotation AS " ); sqlSB.append( PEPTIDE_VALUE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( " ON " ); sqlSB.append( " unified_rp__search__rep_pept__generic_lookup.search_id = " ); sqlSB.append( PEPTIDE_VALUE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".search_id" ); sqlSB.append( " AND " ); sqlSB.append( " unified_rp__search__rep_pept__generic_lookup.reported_peptide_id = " ); sqlSB.append( PEPTIDE_VALUE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".reported_peptide_id" ); } } } // If Yes modifications, join to get records for those modifications if ( modMassSelectionsIncludesYesModifications && modMassSelectionsWithoutNoMods != null ) { if ( modMassSelectionsIncludesNoModifications) { sqlSB.append( SQL_DYNAMIC_MOD_AND_NO_MODS_JOIN_START ); } else { sqlSB.append( SQL_DYNAMIC_MOD_JOIN_START ); } // Start Dynamic Mods subselect sqlSB.append( SQL_DYNAMIC_MOD_INNER_SELECT_START ); sqlSB.append( modMassSelectionsWithoutNoMods.get( 0 ) ); // start at the second entry for ( int index = 1; index < modMassSelectionsWithoutNoMods.size(); index++ ) { sqlSB.append( ", " ); sqlSB.append( modMassSelectionsWithoutNoMods.get( index ) ); } sqlSB.append( SQL_DYNAMIC_MOD_JOIN_AFTER_MOD_MASSES ); // Process link types for Dynamic Mod subselect if ( linkTypes != null && ( linkTypes.length > 0 ) ) { sqlSB.append( SQL_DYNAMIC_MOD_JOIN_START_LINK_TYPES ); sqlSB.append( SQL_DYNAMIC_MOD_LINK_TYPE_START ); // ... IN ( boolean firstLinkType = true; for ( String linkType : linkTypes ) { if ( firstLinkType ) { firstLinkType = false; } else { sqlSB.append( ", " ); } if ( PeptideViewLinkTypesConstants.CROSSLINK_PSM.equals( linkType ) ) { sqlSB.append( "'" ); sqlSB.append( XLinkUtils.CROSS_TYPE_STRING ); sqlSB.append( "'" ); } else if ( PeptideViewLinkTypesConstants.LOOPLINK_PSM.equals( linkType ) ) { sqlSB.append( "'" ); sqlSB.append( XLinkUtils.LOOP_TYPE_STRING ); sqlSB.append( "'" ); } else if ( PeptideViewLinkTypesConstants.UNLINKED_PSM.equals( linkType ) ) { sqlSB.append( "'" ); sqlSB.append( XLinkUtils.UNLINKED_TYPE_STRING ); sqlSB.append( "'" ); sqlSB.append( ", " ); sqlSB.append( "'" ); sqlSB.append( XLinkUtils.DIMER_TYPE_STRING ); sqlSB.append( "'" ); } else { String msg = "linkType is invalid, linkType: " + linkType; log.error( linkType ); throw new Exception( msg ); } } sqlSB.append( SQL_DYNAMIC_MOD_LINK_TYPE_END ); sqlSB.append( SQL_DYNAMIC_MOD_JOIN_AFTER_LINK_TYPES ); } sqlSB.append( SQL_DYNAMIC_MOD_JOIN_END ); } ////////// sqlSB.append( SQL_MAIN_WHERE_START ); ////////// // Process link types if ( linkTypes != null && ( linkTypes.length > 0 ) ) { sqlSB.append( " AND ( " ); sqlSB.append( SQL_LINK_TYPE_START ); // ... IN ( boolean firstLinkType = true; for ( String linkType : linkTypes ) { if ( firstLinkType ) { firstLinkType = false; } else { sqlSB.append( ", " ); } if ( PeptideViewLinkTypesConstants.CROSSLINK_PSM.equals( linkType ) ) { sqlSB.append( "'" ); sqlSB.append( XLinkUtils.CROSS_TYPE_STRING ); sqlSB.append( "'" ); } else if ( PeptideViewLinkTypesConstants.LOOPLINK_PSM.equals( linkType ) ) { sqlSB.append( "'" ); sqlSB.append( XLinkUtils.LOOP_TYPE_STRING ); sqlSB.append( "'" ); } else if ( PeptideViewLinkTypesConstants.UNLINKED_PSM.equals( linkType ) ) { sqlSB.append( "'" ); sqlSB.append( XLinkUtils.UNLINKED_TYPE_STRING ); sqlSB.append( "'" ); sqlSB.append( ", " ); sqlSB.append( "'" ); sqlSB.append( XLinkUtils.DIMER_TYPE_STRING ); sqlSB.append( "'" ); } else { String msg = "linkType is invalid, linkType: " + linkType; log.error( linkType ); throw new Exception( msg ); } } sqlSB.append( SQL_LINK_TYPE_END ); // ) sqlSB.append( " ) " ); } // add modifications condition on unified_rep_pep__reported_peptide__search_lookup to main where clause if ( modMassSelectionsIncludesYesModifications && modMassSelectionsIncludesNoModifications ) { sqlSB.append( SQL_NO_AND_YES_MODS__MAIN_WHERE_CLAUSE ); } else if ( modMassSelectionsIncludesNoModifications) { sqlSB.append( SQL_NO_MODS_ONLY__MAIN_WHERE_CLAUSE ); } else if ( modMassSelectionsIncludesYesModifications ) { sqlSB.append( SQL_YES_MODS_ONLY_MAIN_WHERE_CLAUSE ); } // add only containing monolinks condition on unified_rep_pep__reported_peptide__search_lookup to main where clause if ( returnOnlyReportedPeptidesWithMonolinks == ReturnOnlyReportedPeptidesWithMonolinks.YES ) { sqlSB.append( SQL_YES_MOONOLINKS_ONLY_MAIN_WHERE_CLAUSE ); } // Process PSM Cutoffs for WHERE { if ( ( ( ! defaultCutoffsExactlyMatchAnnTypeDataToSearchData ) ) || ( ! USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES ) ) { // Non-Default PSM or Peptide cutoffs so have to query on the cutoffs int counter = 0; for ( SearcherCutoffValuesAnnotationLevel searcherCutoffValuesPsmAnnotationLevel : psmCutoffValuesList ) { AnnotationTypeDTO srchPgmFilterablePsmAnnotationTypeDTO = searcherCutoffValuesPsmAnnotationLevel.getAnnotationTypeDTO(); counter++; sqlSB.append( " AND " ); sqlSB.append( " ( " ); sqlSB.append( PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".search_id = ? AND " ); sqlSB.append( PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".annotation_type_id = ? AND " ); sqlSB.append( PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".best_psm_value_for_ann_type_id " ); if ( srchPgmFilterablePsmAnnotationTypeDTO.getAnnotationTypeFilterableDTO().getFilterDirectionType() == FilterDirectionType.ABOVE ) { sqlSB.append( SearcherGeneralConstants.SQL_END_BIGGER_VALUE_BETTER ); } else { sqlSB.append( SearcherGeneralConstants.SQL_END_SMALLER_VALUE_BETTER ); } sqlSB.append( " ? " ); sqlSB.append( " ) " ); } } else { // Only Default PSM Cutoffs chosen so criteria simply the Peptides where the PSM count for the default cutoffs is > zero sqlSB.append( " AND " ); sqlSB.append( " unified_rp__search__rep_pept__generic_lookup.psm_num_at_default_cutoff > 0 " ); } } // Process Peptide Cutoffs for WHERE { if ( ( ( ! defaultCutoffsExactlyMatchAnnTypeDataToSearchData ) ) || ( ! USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES ) ) { // Non-Default PSM or Peptide cutoffs so have to query on the cutoffs int counter = 0; for ( SearcherCutoffValuesAnnotationLevel searcherCutoffValuesReportedPeptideAnnotationLevel : peptideCutoffValuesList ) { AnnotationTypeDTO srchPgmFilterableReportedPeptideAnnotationTypeDTO = searcherCutoffValuesReportedPeptideAnnotationLevel.getAnnotationTypeDTO(); counter++; sqlSB.append( " AND " ); sqlSB.append( " ( " ); sqlSB.append( PEPTIDE_VALUE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".search_id = ? AND " ); sqlSB.append( PEPTIDE_VALUE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".annotation_type_id = ? AND " ); sqlSB.append( PEPTIDE_VALUE_FILTER_TABLE_ALIAS ); sqlSB.append( Integer.toString( counter ) ); sqlSB.append( ".value_double " ); if ( srchPgmFilterableReportedPeptideAnnotationTypeDTO.getAnnotationTypeFilterableDTO().getFilterDirectionType() == FilterDirectionType.ABOVE ) { sqlSB.append( SearcherGeneralConstants.SQL_END_BIGGER_VALUE_BETTER ); } else { sqlSB.append( SearcherGeneralConstants.SQL_END_SMALLER_VALUE_BETTER ); } sqlSB.append( "? " ); sqlSB.append( " ) " ); } } else { // Only Default Peptide Cutoffs chosen so criteria simply the Peptides where the defaultPeptideCutoffs is yes // WARNING: This code is currently not run for set value of USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES // WARNING This is possibly still WRONG and needs testing before using. // For certain inputs, the right value to search for is: Yes_No__NOT_APPLICABLE_Enum.NOT_APPLICABLE sqlSB.append( " AND " ); sqlSB.append( " unified_rp__search__rep_pept__generic_lookup.peptide_meets_default_cutoffs = '" ); if ( peptideCutoffValuesList.isEmpty() ) { sqlSB.append( Yes_No__NOT_APPLICABLE_Enum.NOT_APPLICABLE.value() ); } else { sqlSB.append( Yes_No__NOT_APPLICABLE_Enum.YES.value() ); } sqlSB.append( "' " ); } } sqlSB.append( SQL_LAST_PART ); final String sql = sqlSB.toString(); try { conn = DBConnectionFactory.getConnection( DBConnectionFactory.PROXL ); pstmt = conn.prepareStatement( sql ); int paramCounter = 0; if ( modMassSelectionsIncludesYesModifications && modMassSelectionsWithoutNoMods != null ) { // If Yes modifications, have search id in subselect paramCounter++; pstmt.setInt( paramCounter, searchId ); } // For: unified_rp__search__rep_pept__generic_lookup.search_id = ? paramCounter++; pstmt.setInt( paramCounter, searchId ); // Process PSM Cutoffs for WHERE { if ( ( ( ! defaultCutoffsExactlyMatchAnnTypeDataToSearchData ) ) || ( ! USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES ) ) { // Non-Default PSM or Peptide cutoffs so have to query on the cutoffs for ( SearcherCutoffValuesAnnotationLevel searcherCutoffValuesPsmAnnotationLevel : psmCutoffValuesList ) { AnnotationTypeDTO srchPgmFilterablePsmAnnotationTypeDTO = searcherCutoffValuesPsmAnnotationLevel.getAnnotationTypeDTO(); paramCounter++; pstmt.setInt( paramCounter, searchId ); paramCounter++; pstmt.setInt( paramCounter, srchPgmFilterablePsmAnnotationTypeDTO.getId() ); paramCounter++; pstmt.setDouble( paramCounter, searcherCutoffValuesPsmAnnotationLevel.getAnnotationCutoffValue() ); } } } // Process Peptide Cutoffs for WHERE { if ( ( ( ! defaultCutoffsExactlyMatchAnnTypeDataToSearchData ) ) || ( ! USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES ) ) { // Non-Default PSM or Peptide cutoffs so have to query on the cutoffs for ( SearcherCutoffValuesAnnotationLevel searcherCutoffValuesReportedPeptideAnnotationLevel : peptideCutoffValuesList ) { AnnotationTypeDTO srchPgmFilterableReportedPeptideAnnotationTypeDTO = searcherCutoffValuesReportedPeptideAnnotationLevel.getAnnotationTypeDTO(); paramCounter++; pstmt.setInt( paramCounter, searchId ); paramCounter++; pstmt.setInt( paramCounter, srchPgmFilterableReportedPeptideAnnotationTypeDTO.getId() ); paramCounter++; pstmt.setDouble( paramCounter, searcherCutoffValuesReportedPeptideAnnotationLevel.getAnnotationCutoffValue() ); } } } // if ( log.isDebugEnabled() ) { // log.debug( "Executed Statement: " + ((DelegatingPreparedStatement)pstmt).getDelegate().toString() ); // } // if ( log.isDebugEnabled() ) { // log.debug( "Executed Statement: " // // Commented out since is specific DBCP dependency // + ((org.apache.commons.dbcp2.DelegatingPreparedStatement)pstmt).getDelegate().toString() ); // } rs = pstmt.executeQuery(); Set<Integer> retrieved_reported_peptide_id_values_Set = new HashSet<>(); while( rs.next() ) { ReportedPeptideBasicObjectsSearcherResultEntry item = populateFromResultSet( rs, searchId, searcherCutoffValuesSearchLevel, peptideCutoffsAnnotationTypeDTOList, psmCutoffsAnnotationTypeDTOList, defaultCutoffsExactlyMatchAnnTypeDataToSearchData, sql ); if ( item != null ) { int itemReportedPeptideId = item.getReportedPeptideId(); if ( ! retrieved_reported_peptide_id_values_Set.add( itemReportedPeptideId ) ) { // String msg = "Already processed result entry for itemReportedPeptideId: " + itemReportedPeptideId; // log.warn( msg ); // log.error( msg ); // throw new ProxlWebappDataException(msg); } else { entryList.add( item ); } } } } catch ( Exception e ) { String msg = "Exception in search( SearchDTO search, ... ), sql: " + sql; log.error( msg, e ); throw e; } finally { // be sure database handles are closed if( rs != null ) { try { rs.close(); } catch( Throwable t ) { ; } rs = null; } if( pstmt != null ) { try { pstmt.close(); } catch( Throwable t ) { ; } pstmt = null; } if( conn != null ) { try { conn.close(); } catch( Throwable t ) { ; } conn = null; } } ReportedPeptideBasicObjectsSearcherResult result = new ReportedPeptideBasicObjectsSearcherResult(); result.setEntryList( entryList ); result.setSearchId( searchId ); return result; } /** * @param rs * @param searchDTO * @param searcherCutoffValuesSearchLevel * @param defaultCutoffsExactlyMatchAnnTypeDataToSearchData * @param sql * @return - null if PSM count is zero or link type unknown, otherwise a populated object * @throws SQLException * @throws Exception */ private ReportedPeptideBasicObjectsSearcherResultEntry populateFromResultSet( ResultSet rs, int searchId, SearcherCutoffValuesSearchLevel searcherCutoffValuesSearchLevel, List<AnnotationTypeDTO> peptideCutoffsAnnotationTypeDTOList, List<AnnotationTypeDTO> psmCutoffsAnnotationTypeDTOList, boolean defaultCutoffsExactlyMatchAnnTypeDataToSearchData, String sql ) throws SQLException, Exception { ReportedPeptideBasicObjectsSearcherResultEntry item = new ReportedPeptideBasicObjectsSearcherResultEntry(); String linkType = rs.getString( "link_type" ); int reportedPeptideId = rs.getInt( "reported_peptide_id" ); int unifiedReportedPeptideId = rs.getInt( "unified_reported_peptide_id" ); int linkTypeNumber = XLinkUtils.getTypeNumber( linkType ); item.setLinkType( linkTypeNumber ); item.setReportedPeptideId(reportedPeptideId); item.setUnifiedReportedPeptideId( unifiedReportedPeptideId ); if ( defaultCutoffsExactlyMatchAnnTypeDataToSearchData ) { int numPsmsForDefaultCutoffs = rs.getInt( "psm_num_at_default_cutoff" ); if ( ! rs.wasNull() ) { item.setNumPsms( numPsmsForDefaultCutoffs ); } int numUniquePsmsForDefaultCutoffs = rs.getInt( "num_unique_psm_at_default_cutoff" ); if ( ! rs.wasNull() ) { item.setNumUniquePsms( numUniquePsmsForDefaultCutoffs ); } } if ( peptideCutoffsAnnotationTypeDTOList.size() > 1 || psmCutoffsAnnotationTypeDTOList.size() > 1 ) { int numPsms = PsmCountForSearchIdReportedPeptideIdSearcher.getInstance() .getPsmCountForSearchIdReportedPeptideId( reportedPeptideId, searchId, searcherCutoffValuesSearchLevel ); if ( numPsms <= 0 ) { // !!!!!!! Number of PSMs is zero this this isn't really a peptide that meets the cutoffs return null; // EARY EXIT } else { item.setNumPsms( numPsms ); } } // Get Peptide and PSM annotations // Peptide annotations are for Peptide annotations searched for // PSM annotations are for PSM annotations searched for and are best values for the peptides if ( ( ( ! defaultCutoffsExactlyMatchAnnTypeDataToSearchData ) ) || ( ! USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES ) ) { Map<Integer, AnnotationDataBaseDTO> searchedForPeptideAnnotationDTOFromQueryMap = getPeptideValuesFromDBQuery( rs, peptideCutoffsAnnotationTypeDTOList ); item.setPeptideAnnotationDTOMap( searchedForPeptideAnnotationDTOFromQueryMap ); } else { // Get Peptide values in separate DB query, since peptide value table was not joined // List<Integer> peptideCutoffsAnnotationTypeIdList = new ArrayList<>( peptideCutoffsAnnotationTypeDTOList.size() ); // for ( AnnotationTypeDTO peptideAnnotationTypeDTO : peptideCutoffsAnnotationTypeDTOList ) { // peptideCutoffsAnnotationTypeIdList.add( peptideAnnotationTypeDTO.getId() ); // } // List<SearchReportedPeptideAnnotationDTO> searchedForPeptideAnnotationDTOList = // SearchReportedPeptideAnnotationDataSearcher.getInstance(). // getSearchReportedPeptideAnnotationDTOList( search.getId(), reportedPeptideId, peptideCutoffsAnnotationTypeIdList ); // item.setSearchedForPeptideAnnotationDTOList( searchedForPeptideAnnotationDTOList ); } if ( ( ( ! defaultCutoffsExactlyMatchAnnTypeDataToSearchData ) ) || ( ! USE_PEPTIDE_PSM_DEFAULTS_TO_SKIP_JOIN_ANNOTATION_DATA_VALUES_TABLES ) ) { // Get PSM best values from DB query, since psm best value table was joined Map<Integer, AnnotationDataBaseDTO> bestPsmAnnotationDTOFromQueryMap = getPSMBestValuesFromDBQuery( rs, psmCutoffsAnnotationTypeDTOList ); item.setPsmAnnotationDTOMap( bestPsmAnnotationDTOFromQueryMap ); } else { // Get PSM best values in separate DB query, since psm best value table was not joined // List<PsmAnnotationDTO> bestPsmAnnotationDTOList = // PsmAnnotationDataBestValueForPeptideSearcher.getInstance() // .getPsmAnnotationDataBestValueForPeptideList( search.getId(), reportedPeptideId, psmCutoffsAnnotationTypeDTOList ); // item.setBestPsmAnnotationDTOList( bestPsmAnnotationDTOList ); int z = 0; } return item; } /** * Get PSM best values from DB query, since psm best value table was joined * @param rs * @param psmCutoffsAnnotationTypeDTOList * @return * @throws SQLException */ private Map<Integer, AnnotationDataBaseDTO> getPSMBestValuesFromDBQuery( ResultSet rs, List<AnnotationTypeDTO> psmCutoffsAnnotationTypeDTOList ) throws SQLException { Map<Integer, AnnotationDataBaseDTO> bestPsmAnnotationDTOFromQueryMap = new HashMap<>(); // Add inner join for each PSM cutoff for ( int counter = 1; counter <= psmCutoffsAnnotationTypeDTOList.size(); counter++ ) { PsmAnnotationDTO item = new PsmAnnotationDTO(); String annotationTypeIdField = PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS + counter + "_annotation_type_id"; String valueDoubleField = PSM_BEST_VALUE_FOR_PEPTIDE_FILTER_TABLE_ALIAS + counter + "_best_psm_value_for_ann_type_id"; item.setAnnotationTypeId( rs.getInt( annotationTypeIdField ) ); double valueDouble = rs.getDouble( valueDoubleField ); item.setValueDouble( valueDouble ); item.setValueString( Double.toString( valueDouble ) ); bestPsmAnnotationDTOFromQueryMap.put( item.getAnnotationTypeId(), item ); } return bestPsmAnnotationDTOFromQueryMap; } /** * Get Peptide values from DB query, since peptide value table was joined * @param rs * @param peptideCutoffsAnnotationTypeDTOList * @return * @throws SQLException */ private Map<Integer, AnnotationDataBaseDTO> getPeptideValuesFromDBQuery( ResultSet rs, List<AnnotationTypeDTO> peptideCutoffsAnnotationTypeDTOList ) throws SQLException { Map<Integer, AnnotationDataBaseDTO> searchedForPeptideAnnotationDTOFromQueryMap = new HashMap<>(); // Add inner join for each Peptide cutoff for ( int counter = 1; counter <= peptideCutoffsAnnotationTypeDTOList.size(); counter++ ) { SearchReportedPeptideAnnotationDTO item = new SearchReportedPeptideAnnotationDTO(); String annotationTypeIdField = PEPTIDE_VALUE_FILTER_TABLE_ALIAS + counter + "_annotation_type_id"; String valueDoubleField = PEPTIDE_VALUE_FILTER_TABLE_ALIAS + counter + "_value_double"; String valueStringField = PEPTIDE_VALUE_FILTER_TABLE_ALIAS + counter + "_value_string"; item.setAnnotationTypeId( rs.getInt( annotationTypeIdField ) ); item.setValueDouble( rs.getDouble( valueDoubleField ) ); item.setValueString( rs.getString( valueStringField ) ); searchedForPeptideAnnotationDTOFromQueryMap.put( item.getAnnotationTypeId(), item ); } return searchedForPeptideAnnotationDTOFromQueryMap; } }
48.702013
156
0.747099
4a0a58b96f44eb0b1212afd897ccac63eb0403df
797
package net.mueller_martin.turirun; import com.badlogic.gdx.Game; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import net.mueller_martin.turirun.screens.GameScreen; public class Turirun extends Game { public SpriteBatch batch; ScreenManager screenManager; String host = "127.0.0.1"; int port = 1337; String nickname = "Unnamed"; String winner = ""; @Override public void create () { batch = new SpriteBatch(); // Load Settings // Load Assets AssetOrganizer.instance.init(new AssetManager()); MusicBox.instance.init(new MusicBox()); screenManager = new ScreenManager(this); screenManager.setScreenState(Constants.MENUSCREEN); } @Override public void render () { super.render(); CameraHelper.instance.update(); } }
23.441176
53
0.747804
107145854146e70169af33f9decf70aa03ae5108
9,963
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.client.gwt.com.google.web.bindery.event.shared; import com.google.web.bindery.event.shared.Event; import com.google.web.bindery.event.shared.Event.Type; import com.google.web.bindery.event.shared.EventBus; import com.google.web.bindery.event.shared.HandlerRegistration; import com.vaadin.client.flow.collection.JsArray; import com.vaadin.client.flow.collection.JsCollections; import com.vaadin.client.flow.collection.JsMap; /** * Basic implementation of {@link EventBus}. * * Copied from the GWT project to use JsArray and JsMap instead of ArrayList and * HashMap * * @since 1.0 */ public class SimpleEventBus extends EventBus { @FunctionalInterface private interface Command { void execute(); } private int firingDepth = 0; /** * Add and remove operations received during dispatch. */ private JsArray<Command> deferredDeltas; /** * Map of event type to map of event source to list of their handlers. */ private final JsMap<Event.Type<?>, JsMap<Object, JsArray<?>>> map = JsCollections .map(); /** * Create an instance of the event bus. */ public SimpleEventBus() { // Intentionally left empty } @Override public <H> HandlerRegistration addHandler(Type<H> type, H handler) { return doAdd(type, null, handler); } @Override public <H> HandlerRegistration addHandlerToSource(final Event.Type<H> type, final Object source, final H handler) { if (source == null) { throw new NullPointerException( "Cannot add a handler with a null source"); } return doAdd(type, source, handler); } @Override public void fireEvent(Event<?> event) { doFire(event, null); } @Override public void fireEventFromSource(Event<?> event, Object source) { if (source == null) { throw new NullPointerException("Cannot fire from a null source"); } doFire(event, source); } /** * Not documented in GWT, required by legacy features in GWT's old * HandlerManager. * * @param type * the type * @param source * the source * @param handler * the handler * @param <H> * the handler type * @deprecated required by legacy features in GWT's old HandlerManager */ @Deprecated protected <H> void doRemove(Event.Type<H> type, Object source, H handler) { if (firingDepth > 0) { enqueueRemove(type, source, handler); } else { doRemoveNow(type, source, handler); } } /** * Not documented in GWT, required by legacy features in GWT's old * HandlerManager. * * @param type * the type * @param index * the index * @param <H> * the handler type * @return the handler * * @deprecated required by legacy features in GWT's old HandlerManager */ @Deprecated protected <H> H getHandler(Event.Type<H> type, int index) { assert index < getHandlerCount(type) : "handlers for " + type.getClass() + " have size: " + getHandlerCount(type) + " so do not have a handler at index: " + index; JsArray<H> l = getHandlerList(type, null); return l.get(index); } /** * Not documented in GWT, required by legacy features in GWT's old * HandlerManager. * * @param eventKey * the event type * @return the handlers count * * @deprecated required by legacy features in GWT's old HandlerManager */ @Deprecated protected int getHandlerCount(Event.Type<?> eventKey) { return getHandlerList(eventKey, null).length(); } /** * Not documented in GWT, required by legacy features in GWT's old * HandlerManager. * * @param eventKey * the event type * @return {@code true} if the event is handled, {@code false} otherwise * @deprecated required by legacy features in GWT's old HandlerManager */ @Deprecated protected boolean isEventHandled(Event.Type<?> eventKey) { return map.has(eventKey); } private void defer(Command command) { if (deferredDeltas == null) { deferredDeltas = JsCollections.array(); } deferredDeltas.push(command); } private <H> HandlerRegistration doAdd(final Event.Type<H> type, final Object source, final H handler) { if (type == null) { throw new NullPointerException( "Cannot add a handler with a null type"); } if (handler == null) { throw new NullPointerException("Cannot add a null handler"); } if (firingDepth > 0) { enqueueAdd(type, source, handler); } else { doAddNow(type, source, handler); } return () -> doRemove(type, source, handler); } @SuppressWarnings("unchecked") private <H> void doAddNow(Event.Type<H> type, Object source, H handler) { JsArray<H> l = ensureHandlerList(type, source); l.push(handler); } private <H> void doFire(Event<H> event, Object source) { if (event == null) { throw new NullPointerException("Cannot fire null event"); } try { firingDepth++; if (source != null) { setSourceOfEvent(event, source); } JsArray<H> handlers = getDispatchList(event.getAssociatedType(), source); JsArray<Throwable> causes = null; for (int i = 0; i < handlers.length(); i++) { H handler = handlers.get(i); try { dispatchEvent(event, handler); } catch (Exception e) { if (causes == null) { causes = JsCollections.array(); } causes.set(causes.length(), e); } } if (causes != null) { throw new RuntimeException(causes.get(0)); } } finally { firingDepth--; if (firingDepth == 0) { handleQueuedAddsAndRemoves(); } } } private <H> void doRemoveNow(Event.Type<H> type, Object source, H handler) { JsArray<H> l = getHandlerList(type, source); boolean removed = l.remove(handler); if (removed && l.isEmpty()) { prune(type, source); } } private <H> void enqueueAdd(final Event.Type<H> type, final Object source, final H handler) { defer(() -> doAddNow(type, source, handler)); } private <H> void enqueueRemove(final Event.Type<H> type, final Object source, final H handler) { defer(() -> doRemoveNow(type, source, handler)); } private <H> JsArray<H> ensureHandlerList(Event.Type<H> type, Object source) { JsMap<Object, JsArray<?>> sourceMap = map.get(type); if (sourceMap == null) { sourceMap = JsCollections.map(); map.set(type, sourceMap); } // safe, we control the puts. @SuppressWarnings("unchecked") JsArray<H> handlers = (JsArray<H>) sourceMap.get(source); if (handlers == null) { handlers = JsCollections.array(); sourceMap.set(source, handlers); } return handlers; } private <H> JsArray<H> getDispatchList(Event.Type<H> type, Object source) { JsArray<H> directHandlers = getHandlerList(type, source); if (source == null) { return directHandlers; } JsArray<H> globalHandlers = getHandlerList(type, null); JsArray<H> rtn = JsCollections.array(); rtn.pushArray(directHandlers); rtn.pushArray(globalHandlers); return rtn; } private <H> JsArray<H> getHandlerList(Event.Type<H> type, Object source) { JsMap<Object, JsArray<?>> sourceMap = map.get(type); if (sourceMap == null) { return JsCollections.array(); } // safe, we control the puts. @SuppressWarnings("unchecked") JsArray<H> handlers = (JsArray<H>) sourceMap.get(source); if (handlers == null) { return JsCollections.array(); } return handlers; } private void handleQueuedAddsAndRemoves() { if (deferredDeltas != null) { try { for (int i = 0; i < deferredDeltas.length(); i++) { Command c = deferredDeltas.get(i); c.execute(); } } finally { deferredDeltas = null; } } } private void prune(Event.Type<?> type, Object source) { JsMap<Object, JsArray<?>> sourceMap = map.get(type); JsArray<?> pruned = sourceMap.get(source); sourceMap.delete(source); assert pruned != null : "Can't prune what wasn't there"; assert pruned.isEmpty() : "Pruned unempty list!"; if (sourceMap.isEmpty()) { map.delete(type); } } }
29.918919
85
0.571916
93d9e610072bd5c2229b46c1e70de7d47ba2147f
2,219
package mage.cards.a; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.Effect; import mage.abilities.effects.common.AttachEffect; import mage.abilities.effects.common.combat.CanAttackAsThoughItDidntHaveDefenderSourceEffect; import mage.abilities.effects.common.continuous.GainAbilityAttachedEffect; import mage.abilities.keyword.EnchantAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.mageobject.SubtypePredicate; import mage.target.TargetPermanent; import mage.target.common.TargetCreaturePermanent; /** * * @author Quercitron */ public final class AnimateWall extends CardImpl { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("Wall"); static { filter.add(new SubtypePredicate(SubType.WALL)); } public AnimateWall(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{W}"); this.subtype.add(SubType.AURA); // Enchant Wall TargetPermanent auraTarget = new TargetCreaturePermanent(filter); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.AddAbility)); Ability ability = new EnchantAbility(auraTarget.getTargetName()); this.addAbility(ability); // Enchanted Wall can attack as though it didn't have defender. Ability canAttackAbility = new SimpleStaticAbility(Zone.BATTLEFIELD, new CanAttackAsThoughItDidntHaveDefenderSourceEffect(Duration.WhileOnBattlefield)); Effect enchantEffect = new GainAbilityAttachedEffect(canAttackAbility, AttachmentType.AURA, Duration.WhileOnBattlefield); enchantEffect.setText("Enchanted Wall can attack as though it didn't have defender"); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, enchantEffect)); } public AnimateWall(final AnimateWall card) { super(card); } @Override public AnimateWall copy() { return new AnimateWall(this); } }
36.983333
160
0.757548
5fe35a3f5c061f33b4bbd4730f4e8cc8016855b1
1,774
package nl.dslmeinte.xtext.examples.scoping; import static org.eclipse.xtext.scoping.Scopes.scopeFor; import nl.dslmeinte.xtext.examples.DataModelDslUtil; import nl.dslmeinte.xtext.examples.dataModelDsl.DataModel; import nl.dslmeinte.xtext.examples.dataModelDsl.DataType; import nl.dslmeinte.xtext.examples.dataModelDsl.Entity; import org.eclipse.emf.ecore.EReference; import org.eclipse.xtext.scoping.IScope; import org.eclipse.xtext.scoping.impl.AbstractDeclarativeScopeProvider; import org.eclipse.xtext.util.IResourceScopeCache; import com.google.inject.Inject; import com.google.inject.Provider; /** * Custom (local) scoping implementation. */ public class DataModelDslScopeProvider extends AbstractDeclarativeScopeProvider { @Inject private IResourceScopeCache primitiveTypesCache; IScope scope_Field_type(DataType dataType, EReference eRef) { final DataModel model = (DataModel) dataType.eContainer(); return primitiveTypesCache.get(model, model.eResource(), new Provider<IScope>() { public IScope get() { return scopeFor(model.getPrimitives().getPrimitiveTypes()); } } ); } @Inject private IResourceScopeCache allEntityFieldsCache; IScope scope_Usage_field (final Entity entity, EReference ref) { return allEntityFieldsCache.get(entity, entity.eResource(), new Provider<IScope>() { public IScope get() { return scopeFor(DataModelDslUtil.allFields(entity)); } } ); } @Inject private IResourceScopeCache dataTypeFieldsCache; IScope scope_Usage_field (final DataType dataType, EReference ref) { return dataTypeFieldsCache.get(dataType, dataType.eResource(), new Provider<IScope>() { public IScope get() { return scopeFor(dataType.getFields()); } } ); } }
28.15873
81
0.762683
627bee506c7511d85b652831c54966625876cf89
1,105
package ssm.downgrade.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ssm.downgrade.entity.DownGrade; import ssm.downgrade.mapper.DownGradeMapper; import java.util.List; import java.util.Map; @Service public class DownGradeImpl implements DownGradeService { @Autowired private DownGradeMapper downGradeMapper; @Override public int add(DownGrade downGrade){ return downGradeMapper.add(downGrade); } @Override public int edit(DownGrade downGrade){ return downGradeMapper.edit(downGrade); } @Override public int delete(String ids){ return downGradeMapper.delete(ids); } @Override public List<DownGrade> findList(Map<String,Object> queryMap){ return downGradeMapper.findList(queryMap); } @Override public int getTotal(Map<String,Object> queryMap){ return downGradeMapper.getTotal(queryMap); } @Override public DownGrade findRecord(String studentId){ return downGradeMapper.findRecord(studentId); } }
27.625
65
0.729412
873e1fffb5c6a142531970641956b2dc737189cb
1,611
//Sort a linked list in O(n log n) time using constant space complexity. package org.leituo.leetcode.sort; /** * Created by leituo56 on 1/7/15. */ public class SortList { class Solution{ //Merge sorting //split the list by quick slow runner //sort(quick), sort(slow) //merge quick and slow public ListNode sortList(ListNode head) { ListNode quickRunner = head; ListNode slowRunner = head; ListNode divisor = head; while(quickRunner.next!=null && quickRunner.next.next!=null){ divisor = slowRunner; slowRunner = slowRunner.next; quickRunner = quickRunner.next.next; } divisor.next = null; slowRunner = sortList(slowRunner); head = sortList(head); return merge(head, slowRunner); } private ListNode merge(ListNode left, ListNode right){ ListNode helper = new ListNode(0); ListNode end = helper; while(left!=null && right!=null){ if(left.val < right.val){ end.next = left; left = left.next; }else{ end.next = right; right = right.next; } end = end.next; } end.next = left==null?right:left; return helper.next; } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } }
29.290909
73
0.495345
8f9031276bb1b7dbb73a6607e942bb0a5051384b
349
package com.example.university; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class AkademisyenActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_akademisyen); } }
24.928571
60
0.773639
0a2dc90e8150834495a39fcfb887dd77f9acf578
311
package common.dominios; import common.dominios.enums.EstadoPrestamo; import lombok.Data; @Data public class DetallePrestamo { private int id; private Prestamo prestamo; private CopiaRecurso copiaRecurso; private EstadoPrestamo estadoPrestamo; private Biblioteca bibliotecaDevolucion; }
19.4375
44
0.784566
ab2c6264f3ee6a5887d374bc7bf4bc06af96bbe2
4,176
package dao; import util.*; import java.sql.*; import java.util.*; import bean.*; public class NoticeDAOImpl { public ArrayList<NoticeBean> _select() { ArrayList<NoticeBean> list = new ArrayList<NoticeBean>(); ResultSet rs = null; String sql="select * " +"from notice " +"order by dates desc;"; PreparedStatement pstmt=null; Connection conn=DBConnection.getConnection(); try{ pstmt=conn.prepareStatement(sql); rs=pstmt.executeQuery(); while(rs.next()){ NoticeBean _bean=new NoticeBean(); _bean.setId(rs.getInt("id")); _bean.setTitle(rs.getString("title")); _bean.setContent(rs.getString("content")); _bean.setDates(rs.getString("dates")); _bean.setIdent(rs.getString("ident")); list.add(_bean); } }catch (Exception e) { e.printStackTrace(); }finally{ DBConnection.close(rs,pstmt,conn); } return list; } public ArrayList<NoticeBean> _selectById(int id) { ArrayList<NoticeBean> list = new ArrayList<NoticeBean>(); ResultSet rs = null; String sql="select * " +"from notice " +"where id=?;"; PreparedStatement pstmt=null; Connection conn=DBConnection.getConnection(); try{ pstmt=conn.prepareStatement(sql); pstmt.setInt(1, id); rs=pstmt.executeQuery(); while(rs.next()){ NoticeBean _bean=new NoticeBean(); _bean.setId(rs.getInt("id")); _bean.setTitle(rs.getString("title")); _bean.setContent(rs.getString("content")); _bean.setDates(rs.getString("dates")); _bean.setIdent(rs.getString("ident")); list.add(_bean); } }catch (Exception e) { e.printStackTrace(); }finally{ DBConnection.close(rs,pstmt,conn); } return list; } public ArrayList<NoticeBean> _selectByIdent(String ident) { ArrayList<NoticeBean> list = new ArrayList<NoticeBean>(); ResultSet rs = null; String sql="select * " +"from notice where ident!=?" +"order by dates desc;"; PreparedStatement pstmt=null; Connection conn=DBConnection.getConnection(); try{ pstmt=conn.prepareStatement(sql); pstmt.setString(1, ident); rs=pstmt.executeQuery(); while(rs.next()){ NoticeBean _bean=new NoticeBean(); _bean.setId(rs.getInt("id")); _bean.setTitle(rs.getString("title")); _bean.setContent(rs.getString("content")); _bean.setDates(rs.getString("dates")); _bean.setIdent(rs.getString("ident")); list.add(_bean); } }catch (Exception e) { e.printStackTrace(); }finally{ DBConnection.close(rs,pstmt,conn); } return list; } public int _insert(NoticeBean data)throws Exception{ int i=0; String sql="INSERT INTO notice(title,content,ident,dates)VALUES (?, ?, ?,now())"; ResultSet rs = null; PreparedStatement pstmt=null; Connection conn = DBConnection.getConnection(); try{ pstmt=conn.prepareStatement(sql); pstmt.setString(1,data.getTitle()); pstmt.setString(2,data.getContent()); pstmt.setString(3,data.getIdent()); i=pstmt.executeUpdate(); }catch (Exception e) { e.printStackTrace(); }finally{ DBConnection.close(rs,pstmt,conn); } return i; } public int _delete(int id) throws Exception { String sql="delete from notice where id=?"; PreparedStatement pstmt=null; ResultSet rs = null; int result=0; Connection conn=DBConnection.getConnection(); try{ pstmt=conn.prepareStatement(sql); pstmt.setInt(1,id); result=pstmt.executeUpdate(); }catch (Exception e) { e.printStackTrace(); }finally{ DBConnection.close(rs,pstmt,conn); } return result; } public int _update(NoticeBean data) throws Exception { ResultSet rs = null; int i=0; PreparedStatement pstmt=null; Connection conn=DBConnection.getConnection(); String sql ="update notice set title=?, content=?,ident=? ,dates=now() where id=?"; try{ pstmt=conn.prepareStatement(sql); pstmt.setString(1,data.getTitle()); pstmt.setString(2,data.getContent()); pstmt.setString(3,data.getIdent()); pstmt.setInt(4,data.getId()); i=pstmt.executeUpdate(); }catch(SQLException e){ e.printStackTrace(); }finally{ DBConnection.close(rs,pstmt,conn); } return i; } }
24.27907
85
0.670738
77f03d0df00e1f572f1c2deab9919ef7916e1d49
128
package com.po.custom; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class SysAccessTokenCustom{ }
14.222222
48
0.820313
a9be8f1789e1cb99ec9ffaa27b28f1eed25faf07
1,491
/* * Copyright 2018 Leonardo Rossetto * * 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.github.leonardoxh.keystore; import android.content.Context; import com.github.leonardoxh.keystore.store.Storage; import javax.annotation.Nullable; /** * Factory class for test * This will return a dummy but functional implementation * for test implementations */ public final class CipherStorageFactory { private CipherStorageFactory() { throw new AssertionError(); } /** * Factory for test usage * @param context not used in tests * @return a {@link InMemoryCipherStorage} for test proposes */ public static CipherStorage newInstance(@Nullable Context context) { return InMemoryCipherStorage.INSTANCE; } /** * Dummy factory * @see #newInstance(Context) */ public static CipherStorage newInstance(@Nullable Context context, Storage storage) { return newInstance(context); } }
29.235294
89
0.715627
b3e721fa301391f3ea5d8ba2f919cb75419c3ccd
238
package com.mega4tech.oction.mvp.account.presenter; import com.mega4tech.oction.mvp.account.view.AccountView; import com.mega4tech.oction.presenter.BasePresenter; public interface AccountPresenter extends BasePresenter<AccountView> { }
29.75
70
0.844538
d030f268af1dad6396ff5d9400d86305ea376cfd
2,036
/** * @Company JBINFO * @Title: BaseTest.java * @Package org.bana.wechat.cp.user * @author Liu Wenjie * @date 2018年1月19日 下午3:33:45 * @version V1.0 */ package org.bana.wechat.cp; import org.bana.wechat.cp.app.CorpAppType; import org.bana.wechat.cp.app.WechatCorpAppConfig; import org.bana.wechat.cp.app.WechatCorpSuiteConfig; import org.bana.wechat.cp.app.impl.MemoryWechatAppManager; import org.bana.wechat.cp.token.impl.SimpleAccessTokenServiceImpl; import org.bana.wechat.cp.token.impl.SimpleJsApiTicketService; import org.junit.BeforeClass; /** * @ClassName: BaseTest * @Description: 抽象类 * @author Liu Wenjie */ public class BaseCPTest { protected static SimpleAccessTokenServiceImpl tokenService; protected static SimpleJsApiTicketService jsApiTicketService ; protected static MemoryWechatAppManager wechatAppManager; protected static String corpId = "ww3dd9e376336105bf"; protected static String agentId = "-1"; protected static String suiteId = "wwc4869e05df46f0d5"; @BeforeClass public static void beforeClass(){ WechatCorpAppConfig appConfig = new WechatCorpAppConfig(); appConfig.setCorpId(corpId); appConfig.setAgentId(agentId); appConfig.setCorpAppType(CorpAppType.通讯录管理API); appConfig.setSecret("MXBIDelnTGVfItVno8UdO7JxSS9sicviwfXeRbUbZPg"); wechatAppManager = new MemoryWechatAppManager(); wechatAppManager.addAppConfig(appConfig); tokenService = new SimpleAccessTokenServiceImpl(); tokenService.setWechatAppManager(wechatAppManager); jsApiTicketService = new SimpleJsApiTicketService(); jsApiTicketService.setAccessTokenService(tokenService); WechatCorpSuiteConfig suiteConfig = new WechatCorpSuiteConfig(); suiteConfig.setSuiteId(suiteId); suiteConfig.setEncodingAesKey("vx8rQi8dXszcyU9WBimSFLNdc3AAEL1Kn3twYnybd1U"); suiteConfig.setSuiteSecret("SqI67zMSSyi2uhY6_weE6UEykwjC0Qlus_BBJfVjwck"); suiteConfig.setToken("VDwLCrGDTJVWledn"); wechatAppManager.addSuiteConfig(suiteConfig); } }
33.377049
80
0.780943
85af765cf993e325f9da924dc431d0f2e3a2eebd
2,466
/* * Copyright 2000-2019 JetBrains s.r.o. * * 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 jetbrains.slow.plugins.rakerunner; import jetbrains.buildServer.agent.rakerunner.SupportedTestFramework; import jetbrains.buildServer.serverSide.BuildStatistics; import jetbrains.buildServer.serverSide.BuildStatisticsOptions; import jetbrains.buildServer.serverSide.SBuild; import org.jetbrains.annotations.NotNull; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * @author Roman Chernyatchik */ public class Cucumber4BuildLogTest extends AbstractCucumberTest { @Factory(dataProvider = "cucumber4", dataProviderClass = BundlerBasedTestsDataProvider.class) public Cucumber4BuildLogTest(@NotNull final String ruby, @NotNull final String cucumber) { super(ruby, cucumber); } @NotNull @Override protected String getTestDataApp() { return "app_cucumber-4"; } @Override protected void beforeMethod2() throws Throwable { super.beforeMethod2(); setMessagesTranslationEnabled(true); activateTestFramework(SupportedTestFramework.CUCUMBER); setMockingOptions(MockingOptions.FAKE_STACK_TRACE, MockingOptions.FAKE_LOCATION_URL); setBuildEnvironmentVariable("CUCUMBER_PUBLISH_QUIET", "true"); } @Test public void testGeneral() throws Throwable { setPartialMessagesChecker(); initAndDoTest("stat:features", true); } @Test public void testCounts() throws Throwable { doTestWithoutLogCheck("stat:features", true); final SBuild build = getLastFinishedBuild(); final BuildStatistics statNotGrouped = build.getBuildStatistics( new BuildStatisticsOptions(BuildStatisticsOptions.PASSED_TESTS | BuildStatisticsOptions.IGNORED_TESTS | BuildStatisticsOptions.NO_GROUPING_BY_NAME, 0)); assertTestsCount(6, 0, 0, statNotGrouped); assertTestsCount(6, 0, 0, build.getFullStatistics()); assertTestsCount(6, 0, 0, build.getShortStatistics()); } }
34.732394
158
0.773723
cc0234f78c4aacaa1a176cf934ee5ff742949c1a
9,460
package net.trustyuri.rdf; import net.trustyuri.TrustyUriException; import net.trustyuri.TrustyUriResource; import net.trustyuri.TrustyUriUtils; import org.eclipse.rdf4j.OpenRDFException; import org.eclipse.rdf4j.model.BNode; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.URI; import org.eclipse.rdf4j.model.impl.URIImpl; import org.eclipse.rdf4j.rio.*; import org.eclipse.rdf4j.rio.helpers.RDFaParserSettings; import java.io.*; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.Map; import java.util.zip.GZIPOutputStream; public class RdfUtils { public static final char bnodeChar = '_'; public static final char preAcChar = '.'; public static final char postAcChar = '#'; public static final char postAcFallbackChar = '.'; private RdfUtils() { } // no instances allowed public static String getTrustyUriString(URI baseUri, String artifactCode, String suffix) { String s = expandBaseUri(baseUri) + artifactCode; if (suffix != null) { suffix = suffix.replace("#", "%23"); if (suffix.startsWith(bnodeChar + "")) { // Duplicate bnode character for escaping: s += "" + getPostAcChar(baseUri) + bnodeChar + suffix; } else { s += "" + getPostAcChar(baseUri) + suffix; } } return s; } public static String getTrustyUriString(URI baseUri, String artifactCode) { return getTrustyUriString(baseUri, artifactCode, null); } public static URI getTrustyUri(URI baseUri, String artifactCode, String suffix) { if (baseUri == null) return null; return new URIImpl(getTrustyUriString(baseUri, artifactCode, suffix)); } public static URI getTrustyUri(URI baseUri, String artifactCode) { if (baseUri == null) return null; return new URIImpl(getTrustyUriString(baseUri, artifactCode, null)); } public static URI getPreUri(Resource resource, URI baseUri, Map<String, Integer> bnodeMap, boolean frozen) { if (resource == null) { throw new RuntimeException("Resource is null"); } else if (resource instanceof URI) { URI plainUri = (URI) resource; checkUri(plainUri); // TODO Add option to disable suffixes appended to trusty URIs String suffix = getSuffix(plainUri, baseUri); if (suffix == null && !plainUri.equals(baseUri)) { return plainUri; } else if (frozen) { return null; } else if (TrustyUriUtils.isPotentialTrustyUri(plainUri)) { return plainUri; } else { return getTrustyUri(baseUri, " ", suffix); } } else { if (frozen) { return null; } else { return getSkolemizedUri((BNode) resource, baseUri, bnodeMap); } } } public static void checkUri(URI uri) { try { // Raise error if not well-formed new java.net.URI(uri.stringValue()); } catch (URISyntaxException ex) { throw new RuntimeException("Malformed URI: " + uri.stringValue(), ex); } } public static char getPostAcChar(URI baseUri) { if (baseUri.stringValue().contains("#")) { return postAcFallbackChar; } return postAcChar; } private static URI getSkolemizedUri(BNode bnode, URI baseUri, Map<String, Integer> bnodeMap) { int n = getBlankNodeNumber(bnode, bnodeMap); return new URIImpl(expandBaseUri(baseUri) + " " + getPostAcChar(baseUri) + bnodeChar + n); } private static String getSuffix(URI plainUri, URI baseUri) { if (baseUri == null) return null; String b = baseUri.toString(); String p = plainUri.toString(); if (p.equals(b)) { return null; } else if (p.startsWith(b)) { return p.substring(b.length()); } else { return null; } } public static String normalize(URI uri, String artifactCode) { String s = uri.toString(); if (s.indexOf('\n') > -1 || s.indexOf('\t') > -1) { throw new RuntimeException("Newline or tab character in URI: " + s); } if (artifactCode == null) return s; return s.replace(artifactCode, " "); } private static int getBlankNodeNumber(BNode blankNode, Map<String, Integer> bnodeMap) { String id = blankNode.getID(); Integer n = bnodeMap.get(id); if (n == null) { n = bnodeMap.size() + 1; bnodeMap.put(id, n); } return n; } private static String expandBaseUri(URI baseUri) { String s = baseUri.toString(); s = s.replaceFirst("ARTIFACTCODE-PLACEHOLDER[\\.#/]?$", ""); if (s.matches(".*[A-Za-z0-9\\-_]")) { s += preAcChar; } return s; } public static RdfFileContent load(InputStream in, RDFFormat format) throws IOException, TrustyUriException { RDFParser p = getParser(format); RdfFileContent content = new RdfFileContent(format); p.setRDFHandler(content); try { p.parse(new InputStreamReader(in, Charset.forName("UTF-8")), ""); } catch (OpenRDFException ex) { throw new TrustyUriException(ex); } in.close(); return content; } public static RDFParser getParser(RDFFormat format) { RDFParser p = Rio.createParser(format); p.getParserConfig().set(RDFaParserSettings.FAIL_ON_RDFA_UNDEFINED_PREFIXES, true); return p; } public static RdfFileContent load(TrustyUriResource r) throws IOException, TrustyUriException { return load(r.getInputStream(), RDFFormat.TURTLE); } public static void fixTrustyRdf(File file) throws IOException, TrustyUriException { TrustyUriResource r = new TrustyUriResource(file); RdfFileContent content = RdfUtils.load(r); String oldArtifactCode = r.getArtifactCode(); content = RdfPreprocessor.run(content, oldArtifactCode); String newArtifactCode = createArtifactCode(content, oldArtifactCode.startsWith("RB")); content = processNamespaces(content, oldArtifactCode, newArtifactCode); OutputStream out; String filename = r.getFilename().replace(oldArtifactCode, newArtifactCode); if (filename.matches(".*\\.(gz|gzip)")) { out = new GZIPOutputStream(new FileOutputStream(new File("fixed." + filename))); } else { out = new FileOutputStream(new File("fixed." + filename)); } RDFWriter writer = Rio.createWriter(RDFFormat.TRIG, new OutputStreamWriter(out, Charset.forName("UTF-8"))); TransformRdf.transformPreprocessed(content, null, writer); } public static void fixTrustyRdf(RdfFileContent content, String oldArtifactCode, RDFHandler writer) throws TrustyUriException { content = RdfPreprocessor.run(content, oldArtifactCode); String newArtifactCode = createArtifactCode(content, oldArtifactCode.startsWith("RB")); content = processNamespaces(content, oldArtifactCode, newArtifactCode); TransformRdf.transformPreprocessed(content, null, writer); } private static String createArtifactCode(RdfFileContent preprocessedContent, boolean graphModule) throws TrustyUriException { if (graphModule) { return RdfHasher.makeGraphArtifactCode(preprocessedContent.getStatements()); } else { return RdfHasher.makeArtifactCode(preprocessedContent.getStatements()); } } private static RdfFileContent processNamespaces(RdfFileContent content, String oldArtifactCode, String newArtifactCode) { try { RdfFileContent contentOut = new RdfFileContent(content.getOriginalFormat()); content.propagate(new NamespaceProcessor(oldArtifactCode, newArtifactCode, contentOut)); return contentOut; } catch (RDFHandlerException ex) { ex.printStackTrace(); } return content; } private static class NamespaceProcessor implements RDFHandler { private RDFHandler handler; private String oldArtifactCode, newArtifactCode; public NamespaceProcessor(String oldArtifactCode, String newArtifactCode, RDFHandler handler) { this.handler = handler; this.oldArtifactCode = oldArtifactCode; this.newArtifactCode = newArtifactCode; } @Override public void startRDF() throws RDFHandlerException { handler.startRDF(); } @Override public void endRDF() throws RDFHandlerException { handler.endRDF(); } @Override public void handleNamespace(String prefix, String uri) throws RDFHandlerException { handler.handleNamespace(prefix, uri.replace(oldArtifactCode, newArtifactCode)); } @Override public void handleStatement(Statement st) throws RDFHandlerException { handler.handleStatement(st); } @Override public void handleComment(String comment) throws RDFHandlerException { handler.handleComment(comment); } } }
37.098039
129
0.634989
52151dbdeb554e0811997107a7349a0a817449c3
3,585
import com.google.errorprone.annotations.Var; import com.hedera.hashgraph.sdk.FileCreateTransaction; import com.hedera.hashgraph.sdk.FileDeleteTransaction; import com.hedera.hashgraph.sdk.FileInfoQuery; import com.hedera.hashgraph.sdk.KeyList; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Objects; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertNotNull; public class FileCreateIntegrationTest { @Test @DisplayName("Can create file") void canCreateFile() { assertDoesNotThrow(() -> { var testEnv = new IntegrationTestEnv(1); var response = new FileCreateTransaction() .setKeys(testEnv.operatorKey) .setContents("[e2e::FileCreateTransaction]") .execute(testEnv.client); var fileId = Objects.requireNonNull(response.getReceipt(testEnv.client).fileId); @Var var info = new FileInfoQuery() .setFileId(fileId) .execute(testEnv.client); assertEquals(info.fileId, fileId); assertEquals(info.size, 28); assertFalse(info.isDeleted); assertNotNull(info.keys); assertNull(info.keys.getThreshold()); assertEquals(info.keys, KeyList.of(testEnv.operatorKey)); new FileDeleteTransaction() .setFileId(fileId) .execute(testEnv.client) .getReceipt(testEnv.client); testEnv.close(); }); } @Test @DisplayName("Can create file with no contents") void canCreateFileWithNoContents() { assertDoesNotThrow(() -> { var testEnv = new IntegrationTestEnv(1); var response = new FileCreateTransaction() .setKeys(testEnv.operatorKey) .execute(testEnv.client); var fileId = Objects.requireNonNull(response.getReceipt(testEnv.client).fileId); @Var var info = new FileInfoQuery() .setFileId(fileId) .execute(testEnv.client); assertEquals(info.fileId, fileId); assertEquals(info.size, 0); assertFalse(info.isDeleted); assertNotNull(info.keys); assertNull(info.keys.getThreshold()); assertEquals(info.keys, KeyList.of(testEnv.operatorKey)); new FileDeleteTransaction() .setFileId(fileId) .execute(testEnv.client) .getReceipt(testEnv.client); testEnv.close(); }); } @Test @DisplayName("Can create file with no keys") void canCreateFileWithNoKeys() { assertDoesNotThrow(() -> { var testEnv = new IntegrationTestEnv(1); var response = new FileCreateTransaction() .execute(testEnv.client); var fileId = Objects.requireNonNull(response.getReceipt(testEnv.client).fileId); @Var var info = new FileInfoQuery() .setFileId(fileId) .execute(testEnv.client); assertEquals(info.fileId, fileId); assertEquals(info.size, 0); assertFalse(info.isDeleted); assertNull(info.keys); testEnv.close(); }); } }
33.194444
92
0.618968
1ef59f1b4f1feeacc4f72c22dcde84f1208e1a9a
911
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.client.ui.api.attribute; import net.sf.mmm.util.lang.api.Alignment; import net.sf.mmm.util.pojo.path.api.TypedProperty; /** * This interface gives read access to the {@link #getAlignment() alignment} of an object. * * @see AttributeWriteAlignment * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.0 */ public abstract interface AttributeReadAlignment { /** {@link TypedProperty} for {@link #getAlignment()}. */ TypedProperty<Alignment> PROPERTY_ALIGNMENT = new TypedProperty<Alignment>(Alignment.class, "alignment"); /** * This method gets the {@link Alignment} of this object. * * @return the {@link Alignment} or <code>null</code> if not set and no default available. */ Alignment getAlignment(); }
31.413793
107
0.713502
897c75064de56a2b86ef20bf1b38646e095a1606
3,626
/* * Copyright 2012 Mirko Caserta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this software 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.springcryptoutils.core.signature; import java.security.PublicKey; import java.util.HashMap; import java.util.Map; /** * The default implementation for verifying the authenticity of messages using * base64 encoded digital signatures when the public key is configured in an * underlying mapping using a logical name. * * @author Mirko Caserta ([email protected]) */ public class Base64EncodedVerifierWithChooserByPublicKeyIdImpl implements Base64EncodedVerifierWithChooserByPublicKeyId { private Map<String, Base64EncodedVerifier> cache = new HashMap<String, Base64EncodedVerifier>(); private Map<String, PublicKey> publicKeyMap; private String algorithm = "SHA1withRSA"; private String charsetName = "UTF-8"; private String provider; /** * The map of public keys where the map keys are logical names which must * match the publicKeyId parameter as specified in the verify method. * * @param publicKeyMap the public key map * @see #verify(String, String, String) */ public void setPublicKeyMap(Map<String, PublicKey> publicKeyMap) { this.publicKeyMap = publicKeyMap; } /** * The signature algorithm. The default is SHA1withRSA. * * @param algorithm the signature algorithm */ public void setAlgorithm(String algorithm) { this.algorithm = algorithm; } /** * The charset to use when converting a string into a raw byte array * representation. The default is UTF-8. * * @param charsetName the charset name (default: UTF-8) */ public void setCharsetName(String charsetName) { this.charsetName = charsetName; } /** * Sets the provider name of the specific implementation requested (e.g., * "BC" for BouncyCastle, "SunJCE" for the default Sun JCE provider). * * @param provider the provider to set */ public void setProvider(String provider) { this.provider = provider; } /** * Verifies the authenticity of a message using a base64 encoded digital * signature. * * @param publicKeyId the logical name of the public key as configured in * the underlying mapping * @param message the original message to verify * @param signature the base64 encoded digital signature * @return true if the original message is verified by the digital signature * @see #setPublicKeyMap(java.util.Map) */ public boolean verify(String publicKeyId, String message, String signature) { Base64EncodedVerifier verifier = cache.get(publicKeyId); if (verifier != null) { return verifier.verify(message, signature); } Base64EncodedVerifierImpl verifierImpl = new Base64EncodedVerifierImpl(); verifierImpl.setAlgorithm(algorithm); verifierImpl.setCharsetName(charsetName); verifierImpl.setProvider(provider); PublicKey publicKey = publicKeyMap.get(publicKeyId); if (publicKey == null) { throw new SignatureException("public key not found: publicKeyId=" + publicKeyId); } verifierImpl.setPublicKey(publicKey); cache.put(publicKeyId, verifierImpl); return verifierImpl.verify(message, signature); } }
31.530435
121
0.748483
d292de100b6afd91b2a16d511125208daed073fd
208
package samples.springboot.fluentmybatis.config; /** * @author: daibin * @date: 2021/7/29 11:35 上午 */ //@MapperScan("samples.fluentmybatis.manager.mapper") //@Configuration public class MyBatisConfig { }
18.909091
53
0.730769
189744f69c507a1dcdda5d286d8c961589b568b5
1,135
package com.wuwii.config.security; import com.wuwii.dao.UserDao; import com.wuwii.entity.User; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; /** * * 接受一个String类型的用户名参数,返回 UserDetails对象。 */ @Slf4j @CacheConfig(cacheNames = "users") public class UserDetailServiceImpl implements UserDetailsService { @Autowired private UserDao userDao; @Override @Cacheable(key = "#p0") public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userDao.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("Username is not valid."); } log.debug("The User is {}", user); return SecurityModelFactory.create(user); } }
32.428571
93
0.761233
bd5d4f3c956e2e4c3d704935c9ff02ba0470e5d2
703
package io.github.alexnalivayko.archive.document.model; import io.github.alexnalivayko.archive.document.entity.Document; import io.github.alexnalivayko.archive.document.service.DocumentService; import io.github.alexnalivayko.archive.document.type.DocumentType; import org.springframework.stereotype.Component; import java.util.List; @Component("other") public class OtherDocumentGenerator implements DocumentGenerator { private final DocumentService documentService; @Override public List<Document> findAll() { return documentService.getAllDocumentsByType(DocumentType.OTHER); } public OtherDocumentGenerator(DocumentService documentService) { this.documentService = documentService; } }
30.565217
72
0.834993
f1755ffabb043ab44b08b359f1f886e60ef17c95
1,124
package com.wjybxx.fastjgame.net.socket.outer; import com.wjybxx.fastjgame.net.socket.SocketConnectRequest; import com.wjybxx.fastjgame.net.socket.SocketConnectRequestTO; /** * 对外连接请求传输对象 * * @author wjybxx * @version 1.0 * date - 2019/10/2 * github - https://github.com/hl845740757 */ public class OuterSocketConnectRequestTO implements SocketConnectRequestTO { private final long initSequence; private final long ack; private final boolean close; private final SocketConnectRequest connectRequest; OuterSocketConnectRequestTO(long initSequence, long ack, boolean close, SocketConnectRequest connectRequest) { this.initSequence = initSequence; this.ack = ack; this.close = close; this.connectRequest = connectRequest; } @Override public long getInitSequence() { return initSequence; } @Override public long getAck() { return ack; } @Override public boolean isClose() { return close; } @Override public SocketConnectRequest getConnectRequest() { return connectRequest; } }
23.416667
114
0.69484
9d534459ed94aeacc1c2f8282d302542665602d7
3,110
package com.ak47007.utils; import com.ak47007.model.addr.AdInfo; import com.ak47007.model.addr.Response; import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; /** * @author AK47007 * 获得定位 */ @Component public class LocationUtil { /** * 获取地址接口 */ private static final String GET_ADDR_API = "https://apis.map.qq.com/ws/location/v1/ip?ip=%s&key=%s"; /** * 获取地址key */ @Value("${ip-key}") private String GET_ADDR_KEY; /** * 获取登录用户的IP地址 * * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if ("0:0:0:0:0:0:0:1".equals(ip)) { ip = "127.0.0.1"; } if (ip.split(",").length > 1) { ip = ip.split(",")[0]; } return ip; } /** * 获取位置 * * @param ip ip * @return 响应 */ private Response getLocation(String ip) { String localIp1 = "127.0.0.1"; String localIp2 = "localhost"; if (localIp1.equalsIgnoreCase(ip) || localIp2.equals(ip)) { return null; } Response response = null; try { String doGet = HttpClientUtil.doGet(String.format(GET_ADDR_API,ip,GET_ADDR_KEY)); response = JSONObject.parseObject(doGet, Response.class); } catch (Exception e) { e.printStackTrace(); } return response; } /** * 获取省与市 * * @param ip ip * @return 省市 */ public String getPlace(String ip) { Response response = getLocation(ip); // 获取位置成功 if (response != null && response.getStatus().equals(0)) { // 获取结果成功 if (response.getResult() != null) { // 获取定位详细信息 AdInfo adInfo = response.getResult().getAdInfo(); // 外国IP if (adInfo.getAdCode().equals(-1)) { return adInfo.getNation(); } // 省与市同名说明为直辖市 else if (adInfo.getProvince().equals(adInfo.getCity())) { return adInfo.getCity(); } else { return adInfo.getProvince() + adInfo.getCity(); } } } return "中国"; } /** * 获取定位信息 * * @param request 请求 * @return 返回定位信息 */ public String locationInfo(HttpServletRequest request) { return getPlace(getIpAddr(request)); } }
25.702479
104
0.523473
6b37c9e98202b6b3757e11e4605a4bc46e7e73a4
548
package com.teoan.tclass.user.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.teoan.tclass.user.mapper.DepartmentMapper; import com.teoan.tclass.user.entity.Department; import com.teoan.tclass.user.service.DepartmentService; import org.springframework.stereotype.Service; /** * (Department)表服务实现类 * * @author Teoan * @since 2021-05-19 16:48:29 */ @Service("departmentService") public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService { }
28.842105
115
0.808394
af1e97324f39d4c297b4a1a68e97ebf44fd2aab1
821
package org.example.com.leetcode.array.simple; import java.util.HashMap; import java.util.Map; /** * 496. 下一个更大元素 I */ public class Q34 { // 哈希表 public int[] nextGreaterElement(int[] nums1, int[] nums2) { Map<Integer, Integer> map = new HashMap<>(); int len = nums2.length; for (int i = 0; i < len; i++) { int cur = nums2[i]; int right = i; while (right < len && nums2[right] <= cur) { right++; } if (right < len) { map.put(cur, nums2[right]); } else { map.put(cur, -1); } } int len2 = nums1.length; for (int i = 0; i < len2;i++) { nums1[i] = map.get(nums1[i]); } return nums1; } // 栈 }
20.525
63
0.44458
f670cff39aaa39319080034073788c5db2dbbe42
4,659
package com.eficode.vis.model; import com.eficode.vis.exception.validation.DescriptionException; import com.eficode.vis.exception.validation.ServerNameException; import com.eficode.vis.exception.validation.ValidationException; import com.google.gson.annotations.Expose; import java.io.Serializable; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name="servers") public class Server implements Serializable { @Id @Expose @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id", nullable=false) private Long id; @Expose @Column(name="name", nullable=false, length=45) private String name; @Expose @ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="type_id", nullable=false) private ServerType serverType; @Expose @ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="status_id", nullable=false) private ServerStatus serverStatus; @Expose @Column(name="due_date", nullable=false) @Temporal(TemporalType.DATE) private Date dueDate; @Expose @Column(name="description") private String description; @Expose @Column(name="created_date", nullable=false) @Temporal(TemporalType.DATE) private Date createdDate; @Column(name="deleted") private Boolean deleted; public Server() { this.id = 0l; this.name = ""; this.serverType = new ServerType(); this.serverStatus = new ServerStatus(); this.dueDate = new Date(); this.description = ""; this.createdDate = new Date(); this.deleted = false; } public Server(Long id, String name, ServerType serverType, ServerStatus serverStatus, Date dueDate, String description, Date createdDate, Boolean deleted) throws ValidationException { this.id = id; setName(name); this.serverType = serverType; this.serverStatus = serverStatus; this.dueDate = dueDate; setDescription(description); this.createdDate = createdDate; this.deleted = deleted; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public final void setName(String name) throws ServerNameException { if (!AbstractValidate("^[a-zA-Z0-9_-]{3,45}$", name)) throw new ServerNameException(); this.name = name; } public ServerType getServerType() { return serverType; } public void setServerType(ServerType serverType) { this.serverType = serverType; } public ServerStatus getServerStatus() { return serverStatus; } public void setServerStatus(ServerStatus serverStatus) { this.serverStatus = serverStatus; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } public String getDescription() { return description; } public final void setDescription(String description) throws DescriptionException { if(!AbstractValidate("^.{0,1000}$", description)) throw new DescriptionException(); this.description = description; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Boolean getDeleted() { return deleted; } public void setDeleted(Boolean deleted) { this.deleted = deleted; } @Override public String toString() { return "Server{" + "id=" + id + ", name=" + name + ", serverType=" + serverType + ", serverStatus=" + serverStatus + ", dueDate=" + dueDate + ", description=" + description + ", createdDate=" + createdDate + ", deleted=" + deleted + '}'; } private boolean AbstractValidate(String parameter, String toCompare){ Pattern pattern = Pattern.compile(parameter); Matcher matcher = pattern.matcher(toCompare); if(!matcher.matches()) return false; else return true; } }
27.405882
245
0.657652
a77ee876b94ce28d7554302ba06ca3a2b87f9e79
8,424
package com.sap.cloud.lm.sl.cf.process.steps; import static java.text.MessageFormat.format; import java.io.IOException; import java.sql.Timestamp; import java.text.MessageFormat; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.runtime.Job; import org.activiti.engine.runtime.JobQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sap.activiti.common.ExecutionStatus; import com.sap.activiti.common.LogicalRetryException; import com.sap.cloud.lm.sl.cf.core.dao.ContextExtensionDao; import com.sap.cloud.lm.sl.cf.core.model.ContextExtension; import com.sap.cloud.lm.sl.cf.core.model.ErrorType; import com.sap.cloud.lm.sl.cf.process.Constants; import com.sap.cloud.lm.sl.cf.process.message.Messages; import com.sap.cloud.lm.sl.common.ContentException; import com.sap.cloud.lm.sl.common.SLException; import com.sap.cloud.lm.sl.persistence.model.ProgressMessage; import com.sap.cloud.lm.sl.persistence.model.ProgressMessage.ProgressMessageType; import com.sap.cloud.lm.sl.persistence.services.FileStorageException; import com.sap.cloud.lm.sl.persistence.services.ProcessLoggerProviderFactory; import com.sap.cloud.lm.sl.persistence.services.ProgressMessageService; public class ProcessStepHelper { private static final Logger LOGGER = LoggerFactory.getLogger(ProcessStepHelper.class); private static final String CORRELATION_ID = "correlationId"; private ContextExtensionDao contextExtensionDao; private ProgressMessageService progressMessageService; protected ProcessLoggerProviderFactory processLoggerProviderFactory; private StepIndexProvider stepIndexProvider; private String indexedStepName; private int stepIndex; private boolean isInError; public ProcessStepHelper(ProgressMessageService progressMessageService, ProcessLoggerProviderFactory processLoggerProviderFactory, StepIndexProvider stepIndexProvider, ContextExtensionDao contextExtensionDao) { this.progressMessageService = progressMessageService; this.processLoggerProviderFactory = processLoggerProviderFactory; this.stepIndexProvider = stepIndexProvider; this.contextExtensionDao = contextExtensionDao; } protected void postExecuteStep(DelegateExecution context, ExecutionStatus status) { logDebug(context, MessageFormat.format(Messages.STEP_FINISHED, context.getCurrentActivityName())); processLoggerProviderFactory.removeAll(); // Write the log messages: try { processLoggerProviderFactory.append(context, ProcessLoggerProviderFactory.LOG_DIR); } catch (IOException | FileStorageException e) { LOGGER.warn(MessageFormat.format(Messages.COULD_NOT_PERSIST_LOGS_FILE, e.getMessage()), e); } if (ExecutionStatus.LOGICAL_RETRY.equals(status)) { context.setVariable(Constants.RETRY_STEP_NAME, context.getCurrentActivityId()); } } void preExecuteStep(DelegateExecution context, ExecutionStatus initialStatus) throws SLException { init(context, initialStatus); context.setVariable(Constants.INDEXED_STEP_NAME, indexedStepName); if (isInError) { deletePreviousExecutionData(context); } logTaskStartup(context, indexedStepName); } private void init(DelegateExecution context, ExecutionStatus initialStatus) { this.isInError = isInError(context); this.stepIndex = computeStepIndex(context, initialStatus, isInError); this.indexedStepName = context.getCurrentActivityId() + stepIndex; } private boolean isInError(DelegateExecution context) { Job job = getJob(context); if (job == null) { return false; } String exceptionMessage = job.getExceptionMessage(); return exceptionMessage != null && !exceptionMessage.isEmpty(); } Job getJob(DelegateExecution context) { JobQuery jobQuery = context.getEngineServices().getManagementService().createJobQuery(); if (jobQuery == null) { return null; } return jobQuery.processInstanceId(context.getProcessInstanceId()).singleResult(); } private int computeStepIndex(DelegateExecution context, ExecutionStatus initialStatus, boolean isInError) { int stepIndex = getLastStepIndex(context); if (!isInError && !initialStatus.equals(ExecutionStatus.LOGICAL_RETRY) && !initialStatus.equals(ExecutionStatus.RUNNING)) { return ++stepIndex; } return stepIndex; } private int getLastStepIndex(DelegateExecution context) throws SLException { String activityId = context.getCurrentActivityId(); String lastTaskId = progressMessageService.findLastTaskId(getCorrelationId(context), activityId); if (lastTaskId == null) { return stepIndexProvider.getStepIndex(context); } return Integer.parseInt(lastTaskId.substring(activityId.length())); } private String getCorrelationId(DelegateExecution context) { return (String) context.getVariable(CORRELATION_ID); } private void logTaskStartup(DelegateExecution context, String indexedStepName) { String message = format(Messages.EXECUTING_ACTIVITI_TASK, context.getId(), context.getCurrentActivityId()); progressMessageService.add(new ProgressMessage(getCorrelationId(context), indexedStepName, ProgressMessageType.TASK_STARTUP, message, new Timestamp(System.currentTimeMillis()))); } protected void deletePreviousExecutionData(DelegateExecution context) { progressMessageService.removeByProcessIdAndTaskId(getCorrelationId(context), indexedStepName); if (context.hasVariable(Constants.RETRY_STEP_NAME)) { String taskId = (String) context.getVariable(Constants.RETRY_STEP_NAME) + stepIndex; progressMessageService.removeByProcessIdAndTaskId(getCorrelationId(context), taskId); context.removeVariable(Constants.RETRY_STEP_NAME); } String processId = context.getProcessInstanceId(); ContextExtension contextExtension = contextExtensionDao.find(processId, Constants.VAR_ERROR_TYPE); if (contextExtension == null) { return; } LOGGER.debug(MessageFormat.format(Messages.DELETING_CONTEXT_EXTENSION_WITH_ID_NAME_AND_VALUE_FOR_PROCESS, contextExtension.getId(), contextExtension.getName(), contextExtension.getValue(), processId)); contextExtensionDao.remove(contextExtension.getId()); } protected void logException(DelegateExecution context, Throwable t) { LOGGER.error(Messages.EXCEPTION_CAUGHT, t); getLogger(context).error(Messages.EXCEPTION_CAUGHT, t); if (!(t instanceof SLException) && !(t instanceof LogicalRetryException)) { storeExceptionInProgressMessageService(context, t); } if (t instanceof ContentException) { StepsUtil.setErrorType(context.getProcessInstanceId(), contextExtensionDao, ErrorType.CONTENT_ERROR); } else { StepsUtil.setErrorType(context.getProcessInstanceId(), contextExtensionDao, ErrorType.UNKNOWN_ERROR); } } public void storeExceptionInProgressMessageService(DelegateExecution context, Throwable t) { try { ProgressMessage msg = new ProgressMessage(getCorrelationId(context), indexedStepName, ProgressMessageType.ERROR, MessageFormat.format(Messages.UNEXPECTED_ERROR, t.getMessage()), new Timestamp(System.currentTimeMillis())); progressMessageService.add(msg); } catch (SLException e) { getLogger(context).error(Messages.SAVING_ERROR_MESSAGE_FAILED, e); } } private void logDebug(DelegateExecution context, String message) { getLogger(context).debug(message); } org.apache.log4j.Logger getLogger(DelegateExecution context) { return processLoggerProviderFactory.getDefaultLoggerProvider().getLogger(getCorrelationId(context), this.getClass().getName()); } public void failStepIfProcessIsAborted(DelegateExecution context) throws SLException { Boolean processAborted = (Boolean) context.getVariable(Constants.PROCESS_ABORTED); if (processAborted != null && processAborted) { throw new SLException(Messages.PROCESS_WAS_ABORTED); } } }
45.290323
139
0.738723
227bb5dcdded79f39ff28ab7179bb7f24eb96b08
9,158
/* * 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.shiro.config; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.MapCache; import org.apache.shiro.crypto.hash.Sha256Hash; import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.realm.Realm; import org.apache.shiro.realm.text.IniRealm; import org.apache.shiro.realm.text.PropertiesRealm; import org.apache.shiro.session.Session; import org.apache.shiro.session.mgt.AbstractSessionManager; import org.apache.shiro.session.mgt.DefaultSessionManager; import org.apache.shiro.session.mgt.eis.CachingSessionDAO; import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; import org.apache.shiro.session.mgt.eis.SessionDAO; import org.apache.shiro.subject.Subject; import org.junit.Test; import java.util.Collection; import static junit.framework.Assert.*; /** * Unit tests for the {@link IniSecurityManagerFactory} implementation. * * @since 1.0 */ public class IniSecurityManagerFactoryTest { @Test public void testGetInstanceWithoutIni() { IniSecurityManagerFactory factory = new IniSecurityManagerFactory(); SecurityManager sm = factory.getInstance(); assertNotNull(sm); assertTrue(sm instanceof DefaultSecurityManager); } @Test public void testGetInstanceWithResourcePath() { String path = "classpath:org/apache/shiro/config/IniSecurityManagerFactoryTest.ini"; IniSecurityManagerFactory factory = new IniSecurityManagerFactory(path); SecurityManager sm = factory.getInstance(); assertNotNull(sm); assertTrue(sm instanceof DefaultSecurityManager); } @Test public void testGetInstanceWithEmptyIni() { Ini ini = new Ini(); IniSecurityManagerFactory factory = new IniSecurityManagerFactory(ini); SecurityManager sm = factory.getInstance(); assertNotNull(sm); assertTrue(sm instanceof DefaultSecurityManager); } @Test public void testGetInstanceWithSimpleIni() { Ini ini = new Ini(); ini.setSectionProperty(IniSecurityManagerFactory.MAIN_SECTION_NAME, "securityManager.sessionManager.globalSessionTimeout", "5000"); IniSecurityManagerFactory factory = new IniSecurityManagerFactory(ini); SecurityManager sm = factory.getInstance(); assertNotNull(sm); assertTrue(sm instanceof DefaultSecurityManager); assertEquals(5000, ((AbstractSessionManager) ((DefaultSecurityManager) sm).getSessionManager()).getGlobalSessionTimeout()); } @Test public void testGetInstanceWithConfiguredRealm() { Ini ini = new Ini(); Ini.Section section = ini.addSection(IniSecurityManagerFactory.MAIN_SECTION_NAME); section.put("propsRealm", PropertiesRealm.class.getName()); section.put("propsRealm.resourcePath", "classpath:org/apache/shiro/config/IniSecurityManagerFactoryTest.propsRealm.properties"); IniSecurityManagerFactory factory = new IniSecurityManagerFactory(ini); SecurityManager sm = factory.getInstance(); assertNotNull(sm); assertTrue(sm instanceof DefaultSecurityManager); Collection<Realm> realms = ((DefaultSecurityManager) sm).getRealms(); assertEquals(1, realms.size()); Realm realm = realms.iterator().next(); assertTrue(realm instanceof PropertiesRealm); } @Test public void testGetInstanceWithAutomaticallyCreatedIniRealm() { Ini ini = new Ini(); Ini.Section section = ini.addSection(IniRealm.USERS_SECTION_NAME); section.put("admin", "admin"); IniSecurityManagerFactory factory = new IniSecurityManagerFactory(ini); SecurityManager sm = factory.getInstance(); assertNotNull(sm); assertTrue(sm instanceof DefaultSecurityManager); Collection<Realm> realms = ((DefaultSecurityManager) sm).getRealms(); assertEquals(1, realms.size()); Realm realm = realms.iterator().next(); assertTrue(realm instanceof IniRealm); assertTrue(((IniRealm) realm).accountExists("admin")); } /** * Test for issue <a href="https://issues.apache.org/jira/browse/SHIRO-125">SHIRO-125</a>. */ @Test public void testImplicitIniRealmWithAdditionalRealmConfiguration() { Ini ini = new Ini(); //The users section below should create an implicit 'iniRealm' instance in the //main configuration. So we should be able to set properties on it immediately //such as the Sha256 credentials matcher: Ini.Section main = ini.addSection("main"); main.put("credentialsMatcher", "org.apache.shiro.authc.credential.Sha256CredentialsMatcher"); main.put("iniRealm.credentialsMatcher", "$credentialsMatcher"); //create a users section - user 'admin', with a Sha256-hashed 'admin' password (hex encoded): Ini.Section users = ini.addSection(IniRealm.USERS_SECTION_NAME); users.put("admin", new Sha256Hash("secret").toString()); IniSecurityManagerFactory factory = new IniSecurityManagerFactory(ini); SecurityManager sm = factory.getInstance(); //go ahead and try to log in with the admin user, ensuring the //iniRealm has a Sha256CredentialsMatcher enabled: //try to log-in: Subject subject = new Subject.Builder(sm).buildSubject(); //ensure thread clean-up after the login method returns. Test cases only: subject.execute(new Runnable() { public void run() { //the plain-text 'secret' should be converted to an Sha256 hash first //by the CredentialsMatcher. This should return quietly if //this test case is valid: SecurityUtils.getSubject().login(new UsernamePasswordToken("admin", "secret")); } }); assertTrue(subject.getPrincipal().equals("admin")); } /** * Test case for issue <a href="https://issues.apache.org/jira/browse/SHIRO-95">SHIRO-95</a>. */ @Test public void testCacheManagerConfigOrderOfOperations() { Ini ini = new Ini(); Ini.Section main = ini.addSection(IniSecurityManagerFactory.MAIN_SECTION_NAME); //create a non-default CacheManager: main.put("cacheManager", "org.apache.shiro.config.HashMapCacheManager"); //now add a session DAO after the cache manager has been set - this is what tests the user-reported issue main.put("sessionDAO", "org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO"); main.put("securityManager.sessionManager.sessionDAO", "$sessionDAO"); //add the cache manager after the sessionDAO has been set: main.put("securityManager.cacheManager", "$cacheManager"); //add a test user: ini.setSectionProperty(IniRealm.USERS_SECTION_NAME, "admin", "admin"); IniSecurityManagerFactory factory = new IniSecurityManagerFactory(ini); SecurityManager sm = factory.getInstance(); //try to log-in: Subject subject = new Subject.Builder(sm).buildSubject(); subject.login(new UsernamePasswordToken("admin", "admin")); Session session = subject.getSession(); session.setAttribute("hello", "world"); //session should have been started, and a cache is in use. Assert that the SessionDAO is still using //the cache instances provided by our custom CacheManager and not the Default MemoryConstrainedCacheManager SessionDAO sessionDAO = ((DefaultSessionManager) ((DefaultSecurityManager) sm).getSessionManager()).getSessionDAO(); assertTrue(sessionDAO instanceof EnterpriseCacheSessionDAO); CachingSessionDAO cachingSessionDAO = (CachingSessionDAO) sessionDAO; Cache activeSessionsCache = cachingSessionDAO.getActiveSessionsCache(); assertTrue(activeSessionsCache instanceof MapCache); MapCache mapCache = (MapCache) activeSessionsCache; //this is the line that verifies Caches created by our specific CacheManager are not overwritten by the //default cache manager's caches: assertTrue(mapCache instanceof HashMapCacheManager.HashMapCache); } }
43.818182
131
0.709653
6a94fdfdcf62da925b965cdcf929659ce67592df
1,517
package ee.telekom.workflow.listener; import java.util.Map; /** * Provides details on the human task work item associated with the event, the workflow instance's id, * the workflow's name and version, the token id, role and user as well as the human task's arguments. * * The arguments must be used read-only! * * @author Christian Klock */ public class HumanTaskEvent{ private Long woinRefNum; private String workflowName; private Integer workflowVersion; private Integer tokenId; private String role; private String user; private Map<String, Object> arguments; public HumanTaskEvent( Long woinRefNum, String workflowName, Integer workflowVersion, Integer tokenId, String role, String user, Map<String, Object> arguments ){ this.woinRefNum = woinRefNum; this.workflowName = workflowName; this.workflowVersion = workflowVersion; this.tokenId = tokenId; this.role = role; this.user = user; this.arguments = arguments; } public Long getWoinRefNum(){ return woinRefNum; } public String getWorkflowName(){ return workflowName; } public Integer getWorkflowVersion(){ return workflowVersion; } public Integer getTokenId(){ return tokenId; } public String getRole(){ return role; } public String getUser(){ return user; } public Map<String, Object> getArguments(){ return arguments; } }
24.079365
132
0.661173
bd6ddd2a11752ca52d4f1aa5858d00446d4acb81
777
package com.wisely.ch8_5.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.wisely.ch8_5.domain.Person; import com.wisely.ch8_5.service.DemoService; @RestController public class CacheController { @Autowired DemoService demoService; @RequestMapping("/put") public Person put(Person person){ return demoService.save(person); } @RequestMapping("/able") public Person cacheable(Person person){ return demoService.findOne(person); } @RequestMapping("/evit") public String evit(Long id){ demoService.remove(id); return "ok"; } }
18.069767
63
0.706564
1dab2853db5054ffedaddd55423aa7f530cc5abe
906
/* * Copyright(c) 2019 mirelplatform All right reserved. */ package jp.vemi.mirel.apps.mste.domain.dao.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import jp.vemi.mirel.apps.mste.domain.dao.entity.MsteStencil; /** * {@link MsteStencil} のrepositoryです。 */ @Repository public interface MsteStencilRepository extends JpaRepository<MsteStencil, String> { public List<MsteStencil> findByStencilName(String stencilName); @Query(value = "from MsteStencil s where s.stencilCd like :stencilCd% and s.itemKind = :itemKind order by sort") public List<MsteStencil> findByStencilCd(@Param("stencilCd") String stencilCd, @Param("itemKind") String itemKind); }
33.555556
120
0.763797
326fc2c163df6dacaf4ad67b7644c0906f9d6498
313
package cn.xy.novelwebproject.dao; import cn.xy.novelwebproject.bean.Novel; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface SearchMapper { public List<Novel> searchBookByName (String keywords); public List<Novel> searchBookByAuth (String keywords); }
22.357143
56
0.805112
176d726b1f08b9c616f2763535b00c10b7b3a727
13,735
package com.ztech.travelholic.Activities; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; import com.github.ybq.android.spinkit.style.Wave; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.squareup.picasso.Picasso; import com.theartofdev.edmodo.cropper.CropImage; import com.theartofdev.edmodo.cropper.CropImageView; import com.ztech.travelholic.R; import com.ztech.travelholic.Utils.CommonFunctions; import com.ztech.travelholic.databinding.ActivityEditProfileBinding; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import es.dmoral.toasty.Toasty; import id.zelory.compressor.Compressor; public class EditProfileActivity extends AppCompatActivity { ActivityEditProfileBinding binding; DatabaseReference rootRef; Uri profileUri; StorageReference profileImageReference; String profileUriString; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); binding = ActivityEditProfileBinding.inflate(getLayoutInflater()); rootRef = FirebaseDatabase.getInstance().getReference(); profileImageReference = FirebaseStorage.getInstance().getReference().child("UsersImages"); profileUriString = ""; setContentView(binding.getRoot()); Wave wave = new Wave(); binding.LoadingBar.setIndeterminateDrawable(wave); binding.LoadingBar.setVisibility(View.INVISIBLE); if (HomeActivity.HOME_USER != null) { binding.Name.setText(HomeActivity.HOME_USER.getUsername()); binding.Email.setText(HomeActivity.HOME_USER.getEmail()); binding.Phone.setText(HomeActivity.HOME_USER.getPhoneNumber()); binding.Address.setText(HomeActivity.HOME_USER.getAddress()); binding.Profession.setText(HomeActivity.HOME_USER.getProfession()); Picasso.get().load(HomeActivity.HOME_USER.getUri()).placeholder(R.drawable.person_picture).error(R.drawable.person_picture).into(binding.PreviewImage); } binding.editProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CheckField(); } }); binding.ivBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); binding.Camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CropImage.activity() .setGuidelines(CropImageView.Guidelines.ON) .setAspectRatio(1, 1) .start(EditProfileActivity.this); } }); } private void CheckField() { try { final String name = binding.Name.getText().toString(); final String email = binding.Email.getText().toString(); final String phone = binding.Phone.getText().toString(); final String address = binding.Address.getText().toString(); final String profession = binding.Profession.getText().toString(); if (TextUtils.isEmpty(name)) { CommonFunctions.setError(binding.Name, "Username Required"); } else if (TextUtils.isEmpty(email)) { CommonFunctions.setError(binding.Email, "Email Required"); } else if (TextUtils.isEmpty(phone)) { CommonFunctions.setError(binding.Phone, "Phone Number Required"); } else if (TextUtils.isEmpty(address)) { CommonFunctions.setError(binding.Address, "Full Address Required"); } else if (TextUtils.isEmpty(profession)) { CommonFunctions.setError(binding.Profession, "Profession Required"); } else { if (CommonFunctions.isNetworkAvailable(this)) { EditUserProfile(name, email, phone, address, profession); } else { CommonFunctions.showShortToastInfo(this, "Check Your Internet ! Make Sure Your are Connected to Internet "); } } } catch (Exception e) { Toast.makeText(EditProfileActivity.this, "Try Again, Something wrong occur while registration", Toast.LENGTH_SHORT).show(); } } private void EditUserProfile(String name, String email, String phone, String address, String profession) { try { binding.LoadingBar.setVisibility(View.VISIBLE); Map MessageMap = new HashMap<>(); MessageMap.put("ID", HomeActivity.HOME_USER.getID()); MessageMap.put("Email", email); MessageMap.put("Address", address); MessageMap.put("Password", HomeActivity.HOME_USER.getPassword()); MessageMap.put("Username", name); MessageMap.put("PhoneNumber", phone); MessageMap.put("Profession", profession); if (profileUri != null) { if (profileUri.equals(Uri.EMPTY)) { MessageMap.put("Uri", HomeActivity.HOME_USER.getUri()); rootRef.child("Users").child(HomeActivity.HOME_USER.getID()).setValue(MessageMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { HomeActivity.HOME_USER.setAddress(address); HomeActivity.HOME_USER.setUsername(name); HomeActivity.HOME_USER.setPhoneNumber(phone); HomeActivity.HOME_USER.setProfession(profession); startActivity(new Intent(EditProfileActivity.this, HomeActivity.class)); finish(); } else { binding.LoadingBar.setVisibility(View.GONE); CommonFunctions.showShortToastWarning(EditProfileActivity.this, "Some Problem happen will editing user...!"); } } }); } else { try { binding.LoadingBar.setVisibility(View.VISIBLE); File actualImage = new File(profileUri.getPath()); Bitmap compressedImage = new Compressor(EditProfileActivity.this) .setMaxWidth(300) .setMaxHeight(300) .setQuality(100) .setCompressFormat(Bitmap.CompressFormat.WEBP) .compressToBitmap(actualImage); ByteArrayOutputStream baos = new ByteArrayOutputStream(); compressedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] final_image = baos.toByteArray(); final StorageReference filePath = profileImageReference.child(profileUri.getLastPathSegment() + ".jpg"); UploadTask uploadTask = filePath.putBytes(final_image); uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) { filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { MessageMap.put("Uri", uri + ""); rootRef.child("Users").child(HomeActivity.HOME_USER.getID()).setValue(MessageMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { HomeActivity.HOME_USER.setAddress(address); HomeActivity.HOME_USER.setUsername(name); HomeActivity.HOME_USER.setPhoneNumber(phone); HomeActivity.HOME_USER.setProfession(profession); startActivity(new Intent(EditProfileActivity.this, HomeActivity.class)); finish(); } else { binding.LoadingBar.setVisibility(View.GONE); CommonFunctions.showShortToastWarning(EditProfileActivity.this, "Some Problem happen will editing user...!"); } } }); } }); } }); } catch (Exception error) { binding.LoadingBar.setVisibility(View.GONE); Toasty.error(EditProfileActivity.this, "Some Problem happen will editing Users...!" +error.getMessage(), Toasty.LENGTH_SHORT).show(); } } } else { MessageMap.put("Uri", HomeActivity.HOME_USER.getUri()); rootRef.child("Users").child(HomeActivity.HOME_USER.getID()).setValue(MessageMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { HomeActivity.HOME_USER.setAddress(address); HomeActivity.HOME_USER.setUsername(name); HomeActivity.HOME_USER.setPhoneNumber(phone); HomeActivity.HOME_USER.setProfession(profession); startActivity(new Intent(EditProfileActivity.this, HomeActivity.class)); finish(); } else { binding.LoadingBar.setVisibility(View.GONE); CommonFunctions.showShortToastWarning(EditProfileActivity.this, "Some Problem happen will editing user...!"); } } }); } } catch (Exception error) { binding.LoadingBar.setVisibility(View.GONE); CommonFunctions.showShortToastWarning(EditProfileActivity.this, "Some Problem happen will editing user...!"); } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { profileUri = result.getUri(); profileUriString = profileUri.toString(); File actualImage = new File(profileUri.getPath()); Bitmap compressedImage = null; try { compressedImage = new Compressor(this) .setMaxWidth(250) .setMaxHeight(250) .setQuality(50) .setCompressFormat(Bitmap.CompressFormat.WEBP) .compressToBitmap(actualImage); binding.PreviewImage.setImageBitmap(Bitmap.createScaledBitmap(compressedImage, 256, 256, true)); } catch (IOException e) { e.printStackTrace(); } } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { Exception error = result.getError(); Toasty.error(EditProfileActivity.this, "" + error, Toasty.LENGTH_SHORT).show(); } } } }
47.199313
176
0.567747
c0e53eda416946cb2a7efb075d0f7cfdb3130240
2,116
package informatica.unipr.it.Prometheus.recyclerView.notificationSettings; import android.content.Context; import android.content.pm.PackageManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.List; import informatica.unipr.it.Prometheus.R; import informatica.unipr.it.Prometheus.recyclerView.ListRemover; import informatica.unipr.it.Prometheus.recyclerView.StatisticsObject; public class NotificationRecyclerViewAdapter extends RecyclerView.Adapter<NotificationViewHolder> implements ListRemover { public static List<StatisticsObject> statistics; private Context context; private int pageIndex; //Costruttore public NotificationRecyclerViewAdapter(List<StatisticsObject> statistics, Context context, int pageIndex) { this.statistics = statistics; this.context = context; this.pageIndex = pageIndex; } //Per rimuovere elemento @Override public void removeItem(int position) { statistics.remove(position); notifyItemRemoved(position); } //Passo il layout della row @Override public NotificationViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_show_item, parent, false); return new NotificationViewHolder(view, context, this, pageIndex); } @Override public int getItemCount() { return statistics.size(); } //Funzione che rimpiazza cioò che sta nelle view //Setto in base all'oggetto del numero corrispondente nella lista @Override public void onBindViewHolder(NotificationViewHolder holder, int position) { if (getItemViewType(position) == 0) { NotificationViewHolder notificationViewHolder = holder; try { notificationViewHolder.setIconAndTime(statistics.get(position)); } catch (PackageManager.NameNotFoundException e) { //e.printStackTrace(); } } } }
32.553846
122
0.724953
5c880617c8032baeefcc31e209b9a1ce7310ccc9
3,959
package de.samply.share.client.fhir; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.parser.DataFormatException; import ca.uhn.fhir.parser.IParser; import javax.ws.rs.core.MediaType; import org.hl7.fhir.r4.model.Bundle; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class FhirUtilTest { public static final String BUNDLE_STRING = "kaf20g."; public static final MediaType MEDIA_TYPE_JSON = new MediaType("application", "json"); public static final String RESULT_STRING = "result-1442"; @Mock private FhirContext fhirContext; @Mock private IParser jsonParser; @Mock private IParser xmlParser; @InjectMocks private FhirUtil fhirUtil; @Test void parseBundleResource_default() throws FhirParseException { when(fhirContext.newXmlParser()).thenReturn(xmlParser); Bundle expectedBundle = new Bundle(); when(xmlParser.parseResource(BUNDLE_STRING)).thenReturn(expectedBundle); Bundle bundle = fhirUtil.parseBundleResource(BUNDLE_STRING, new MediaType()); assertSame(expectedBundle,bundle); } @Test void parseBundleResource_json() throws FhirParseException { when(fhirContext.newJsonParser()).thenReturn(jsonParser); Bundle expectedBundle = new Bundle(); when(jsonParser.parseResource(BUNDLE_STRING)).thenReturn(expectedBundle); Bundle bundle = fhirUtil.parseBundleResource(BUNDLE_STRING, MEDIA_TYPE_JSON); assertSame(expectedBundle,bundle); } @Test void parseBundleResource_configurationException() { when(fhirContext.newJsonParser()).thenReturn(jsonParser); ConfigurationException configurationException = new ConfigurationException(); when(jsonParser.parseResource(BUNDLE_STRING)).thenThrow(configurationException); FhirParseException exception = assertThrows(FhirParseException.class, ()->fhirUtil.parseBundleResource(BUNDLE_STRING, MEDIA_TYPE_JSON)); assertEquals("Error while parsing a json bundle.", exception.getMessage()); assertEquals(configurationException, exception.getCause()); } @Test void parseBundleResource_dataFormatException() { when(fhirContext.newJsonParser()).thenReturn(jsonParser); DataFormatException dataFormatException = new DataFormatException(); when(jsonParser.parseResource(BUNDLE_STRING)).thenThrow(dataFormatException); FhirParseException exception = assertThrows(FhirParseException.class, ()->fhirUtil.parseBundleResource(BUNDLE_STRING, MEDIA_TYPE_JSON)); assertEquals("Error while parsing a json bundle.", exception.getMessage()); assertEquals(dataFormatException, exception.getCause()); } @Test void encodeResourceToJson() { when(fhirContext.newJsonParser()).thenReturn(jsonParser); Bundle bundle = new Bundle(); when(jsonParser.encodeResourceToString(bundle)).thenReturn(RESULT_STRING); String result = fhirUtil.encodeResourceToJson(bundle); assertEquals(RESULT_STRING,result); } @Test void encodeResourceToJson_dataFormatException() { when(fhirContext.newJsonParser()).thenReturn(jsonParser); DataFormatException dataFormatException = new DataFormatException(); Bundle bundle = new Bundle(); when(jsonParser.encodeResourceToString(bundle)).thenThrow(dataFormatException); FhirEncodeException exception = assertThrows(FhirEncodeException.class, ()->fhirUtil.encodeResourceToJson(bundle)); assertEquals("Error while encoding a bundle to json.", exception.getMessage()); assertEquals(dataFormatException, exception.getCause()); } }
35.990909
121
0.782521
a931c1a962d3a78909f10f1f5626d5155218a856
1,035
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Generador; /** * * @author Jose */ public class Triplo { private Object valor1; private String operador; private Object valor2; public Triplo() { } public Triplo(Object valor1, String operador, Object valor2) { this.valor1 = valor1; this.operador = operador; this.valor2 = valor2; } public Object getValor1() { return valor1; } public void setValor1(Object valor1) { this.valor1 = valor1; } public String getOperador() { return operador; } public void setOperador(String operador) { this.operador = operador; } public Object getValor2() { return valor2; } public void setValor2(Object valor2) { this.valor2 = valor2; } }
19.903846
80
0.584541
5be571659ac33506f428873a623820354f74a07f
1,131
package com.ultra.anim; import android.graphics.drawable.AnimationDrawable; import android.view.View; public class GradientAnim { private int alpha; private View view; private int resource; private int duration = 4000; private AnimationDrawable frameAnimation; public GradientAnim setTransitionDuration(int time) { this.duration = time; return this; } public GradientAnim onView(View view) { this.view = view; return this; } public GradientAnim start() { if (view != null) { view.setBackgroundResource(resource); frameAnimation = (AnimationDrawable) view.getBackground(); } frameAnimation.setExitFadeDuration(duration); frameAnimation.setEnterFadeDuration(duration); frameAnimation.start(); return this; } public GradientAnim setBackgroundResource(int resource) { this.resource = resource; return this; } public GradientAnim setAlpha(int alpha) { this.alpha = alpha; frameAnimation.setAlpha(this.alpha); return this; } }
25.704545
70
0.65252
081e26ef7a0399b16f781e74f42ac97f967a8f4b
809
package com.flightstats.hub.util; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import java.math.BigInteger; import java.nio.charset.Charset; public class Hash { //This assumes we are using a full 64 bit range. private static final BigInteger TOTAL_RANGE = BigInteger.valueOf(Long.MAX_VALUE) .subtract(BigInteger.valueOf(Long.MIN_VALUE)) .add(BigInteger.ONE); private static final HashFunction hashFunction = Hashing.farmHashFingerprint64(); public static long hash(String key) { return hashFunction.hashString(key, Charset.defaultCharset()).asLong(); } public static long getRangeSize(int nodes) { return TOTAL_RANGE.divide(BigInteger.valueOf(nodes)).longValue(); } }
29.962963
85
0.703337
d40a8c1620fbb755c6bc6b4467c2c38ce818e1b1
759
package com.so61pi.test.model.relationship.many2many.setlist; import lombok.*; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity @Table(name = BSong.TABLE_NAME) @Getter @Setter @NoArgsConstructor @EqualsAndHashCode(onlyExplicitlyIncluded = true)public class BSong { public final static String TABLE_NAME = "bsongs"; @Id @GeneratedValue private Long id; // JPA: For many-to-many bidirectional relationships either side may be the owning side. @ManyToMany(mappedBy = AArtist.COL_SONGS) private List<AArtist> artists = new ArrayList<>(); @EqualsAndHashCode.Include @Column(nullable = false) private String name; public BSong(String name) { this.name = name; } }
23
92
0.722003
ae8bfab840f04930bd86f12bbaea5c688fc2898c
654
package gameauthoring.creation.cellviews; import engine.profile.IProfilable; import gameauthoring.waves.ListGraphicFactory; import javafx.scene.layout.HBox; /** * Profile cell that can be deleted * * @author RyanStPierre * * @param <E> */ public class DeleteableProfileCellView<E extends IProfilable> extends ProfileCellView<E> { private ListGraphicFactory myFactory = new ListGraphicFactory(); @Override protected HBox createSpriteCell (E profile) { HBox container = super.getHBox(profile); container.getChildren().add(myFactory.createDelete(getListView().getItems(), profile)); return container; } }
24.222222
95
0.737003
e0b6c814f7d5b7741be07b448d98a983b059449c
573
package io.hawt.web.plugin; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; public class HawtioPluginTest { @Test public void setScripts() { HawtioPlugin plugin = new HawtioPlugin(); plugin.setScripts(""); assertThat(plugin.getScripts().length, is(1)); assertThat(plugin.getScripts(), arrayContaining("")); plugin.setScripts("a,b,c"); assertThat(plugin.getScripts().length, is(3)); assertThat(plugin.getScripts(), arrayContaining("a", "b", "c")); } }
24.913043
72
0.647469
da95ca035c205a57a7af483dd4ff4885559313e8
5,299
/* * Copyright (c) 2018 by Philippe Marschall <[email protected]> * * 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.github.ferstl.spring.jdbc.oracle; import java.sql.Array; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Arrays; import org.springframework.dao.CleanupFailureDataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.jdbc.core.SqlTypeValue; import oracle.jdbc.OracleConnection; import oracle.jdbc.OraclePreparedStatement; /** * An implementation of {@link SqlTypeValue} for convenient creation * of an Oracle {@link Array} from the provided scalar values. * * <h2>SQL Syntax</h2> * Any of the following two syntax can be used to filter a column against an array of scalar values * <pre> * <code>WHERE filtered_column_name = ANY(SELECT column_value FROM table(:ids))</code> * </pre> * <pre> * <code>WHERE filtered_column_name IN (SELECT column_value FROM table(:ids))</code> * </pre> * {@code filtered_column_name} has to be replaced by the name of the column to filter against * the array while {@code column_value} and {@code table} have to remain literally the same. * <h2>JdbcTemplate Example</h2> * <pre><code> jdbcTemplate.queryForInt("SELECT val " * + "FROM test_table " * + "WHERE id = ANY(SELECT column_value FROM table(?))", * new SqlOracleArrayValue("MYARRAYTYPE", values));</code></pre> * * <h2>OracleNamedParameterJdbcTemplate Example</h2> * <pre><code> Map&lt;String, Object&gt; map = Collections.singletonMap("ids", new SqlOracleArrayValue("MYARRAYTYPE", values)); * namedParameterJdbcTemplate.query("SELECT val " * + "FROM test_table " * + "WHERE id = ANY(SELECT column_value FROM table(:ids))", * new MapSqlParameterSource(map), * (rs, i) -&gt; ...); * </code></pre> * * <h2>StoredProcedure Example</h2> * <pre><code> storedProcedure.declareParameter(new SqlParameter("myarrayparameter", Types.ARRAY, "MYARRAYTYPE")); * ... * Map&lt;String, Object&gt; inParams = new HashMap&lt;&gt;(); * inParams.put("myarrayparameter", new SqlOracleArrayValue("MYARRAYTYPE", objectArray); * Map&lt;String, Object&gt; out = storedProcedure.execute(inParams); * </code></pre> * * * <p>This class is similar to {@code org.springframework.data.jdbc.support.oracle.SqlArrayValue} * but updated for Spring 5 and later and OJDBC 11.2g and later. * * <p>This class can be combined with {@link OracleNamedParameterJdbcTemplate} for named parameter * support. * * @see <a href="https://docs.oracle.com/en/database/oracle/oracle-database/21/jajdb/oracle/jdbc/OracleConnection.html#createOracleArray_java_lang_String_java_lang_Object_">OracleConnection#createOracleArray</a> */ public final class SqlOracleArrayValue implements NamedSqlValue { private final Object[] values; private final String typeName; private Array array; /** * Constructor that takes two parameters, one parameter with the array of values passed in to * the statement and one that takes the type name. * * @param typeName the type name * @param values the array containing the values */ public SqlOracleArrayValue(String typeName, Object... values) { this.values = values; this.typeName = typeName; } /** * {@inheritDoc} */ @Override public void setValue(PreparedStatement ps, int paramIndex) throws SQLException { Array array = this.createArray(ps.getConnection()); ps.setArray(paramIndex, array); } /** * {@inheritDoc} */ @Override public void setValue(PreparedStatement ps, String paramName) throws SQLException { Array array = this.createArray(ps.getConnection()); ps.unwrap(OraclePreparedStatement.class).setArrayAtName(paramName, array); } private Array createArray(Connection conn) throws SQLException { if (this.array != null) { throw new InvalidDataAccessApiUsageException("Value bound more than once"); } this.array = conn.unwrap(OracleConnection.class).createOracleArray(this.typeName, this.values); return this.array; } /** * {@inheritDoc} */ @Override public void cleanup() { if (this.array == null) { // #cleanup may be called twice in case of exceptions // avoid calling #free twice return; } // https://docs.oracle.com/javase/tutorial/jdbc/basics/array.html#releasing_array try { this.array.free(); this.array = null; } catch (SQLException e) { throw new CleanupFailureDataAccessException("could not free array", e); } } /** * {@inheritDoc} */ @Override public String toString() { return Arrays.toString(this.values); } }
35.092715
211
0.710511
f8c28ca7e1233b5f18869f7a92feb164d26b3347
30,246
package edu.scripps.yates.proteindb.persistence.mysql.access; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import edu.scripps.yates.proteindb.persistence.ContextualSessionHandler; import edu.scripps.yates.proteindb.persistence.mysql.AnnotationType; import edu.scripps.yates.proteindb.persistence.mysql.Condition; import edu.scripps.yates.proteindb.persistence.mysql.Label; import edu.scripps.yates.proteindb.persistence.mysql.MsRun; import edu.scripps.yates.proteindb.persistence.mysql.Organism; import edu.scripps.yates.proteindb.persistence.mysql.Peptide; import edu.scripps.yates.proteindb.persistence.mysql.PeptideAmount; import edu.scripps.yates.proteindb.persistence.mysql.PeptideRatioValue; import edu.scripps.yates.proteindb.persistence.mysql.PeptideScore; import edu.scripps.yates.proteindb.persistence.mysql.Project; import edu.scripps.yates.proteindb.persistence.mysql.Protein; import edu.scripps.yates.proteindb.persistence.mysql.ProteinAmount; import edu.scripps.yates.proteindb.persistence.mysql.ProteinAnnotation; import edu.scripps.yates.proteindb.persistence.mysql.ProteinRatioValue; import edu.scripps.yates.proteindb.persistence.mysql.ProteinScore; import edu.scripps.yates.proteindb.persistence.mysql.ProteinThreshold; import edu.scripps.yates.proteindb.persistence.mysql.Psm; import edu.scripps.yates.proteindb.persistence.mysql.PsmAmount; import edu.scripps.yates.proteindb.persistence.mysql.PsmRatioValue; import edu.scripps.yates.proteindb.persistence.mysql.PsmScore; import edu.scripps.yates.proteindb.persistence.mysql.Ptm; import edu.scripps.yates.proteindb.persistence.mysql.PtmSite; import edu.scripps.yates.proteindb.persistence.mysql.RatioDescriptor; import edu.scripps.yates.proteindb.persistence.mysql.Sample; import edu.scripps.yates.proteindb.persistence.mysql.Tissue; import edu.scripps.yates.utilities.progresscounter.ProgressCounter; import edu.scripps.yates.utilities.progresscounter.ProgressPrintingType; import gnu.trove.map.hash.THashMap; import gnu.trove.set.hash.THashSet; /** * This class provides the methods for the appropiate deletion of the data in * the database, but it doesn-t handle the session, and the potential exceptions * that could be generated (rollbacks needed) * * @author Salva * */ public class MySQLDeleter { private final static Logger log = Logger.getLogger(MySQLDeleter.class); private final Set<Psm> deletedPsms = new THashSet<Psm>(); private final Set<Peptide> deletedPeptides = new THashSet<Peptide>(); private final Set<Protein> deletedProteins = new THashSet<Protein>(); private void deleteProtein(edu.scripps.yates.proteindb.persistence.mysql.Protein protein) { if (deletedProteins.contains(protein)) { return; } deletedProteins.add(protein); if (protein.getId() == null) { return; } // final Set<ProteinAccession> proteinAccessions = // protein.getProteinAccessions(); // protein accesssions // for (ProteinAccession proteinAccession : proteinAccessions) { // deleteProteinAccession(proteinAccession); // } // protein annotations final Set<ProteinAnnotation> proteinAnnotations = protein.getProteinAnnotations(); for (final ProteinAnnotation proteinAnnotation : proteinAnnotations) { deleteProteinAnnotation(proteinAnnotation); } // genes // final Set<Gene> genes = protein.getGenes(); // for (final Gene gene : genes) { // deleteGene(gene); // } // applied threshold final Set<ProteinThreshold> appliedThresholds = protein.getProteinThresholds(); for (final ProteinThreshold appliedThreshold : appliedThresholds) { deleteAppliedThreshold(appliedThreshold); } // scores final Set<ProteinScore> proteinScores = protein.getProteinScores(); if (proteinScores != null) { for (final ProteinScore proteinScore : proteinScores) { deleteProteinScore(proteinScore); } } // // protein ratios final Set<ProteinRatioValue> proteinRatios = protein.getProteinRatioValues(); for (final ProteinRatioValue proteinRatio : proteinRatios) { deleteProteinRatio(proteinRatio); } // amounts final Set<ProteinAmount> amounts = protein.getProteinAmounts(); for (final ProteinAmount amount : amounts) { deleteProteinAmount(amount); } // conditions // final Set<Condition> conditions = protein.getConditions(); // for (final Condition condition : conditions) { // condition.getProteins().remove(protein); // } protein.getConditions().clear(); protein.getMsRuns().clear(); // peptides are the owners of protein-peptide relationships final Iterator<Peptide> peptideIterator = protein.getPeptides().iterator(); while (peptideIterator.hasNext()) { final Peptide peptide = peptideIterator.next(); peptide.getProteins().remove(protein); peptideIterator.remove(); deletePeptide(peptide); } // psms are the owners of the protein-psm relationship final Iterator<Psm> psmsIterator = protein.getPsms().iterator(); while (psmsIterator.hasNext()) { final Psm psm = psmsIterator.next(); psm.getProteins().remove(protein); psmsIterator.remove(); deletePSM(psm); } // delete protein who is not the owner of the relationship ContextualSessionHandler.delete(protein); } private void deleteOrganism(Organism organism) { if (organism.getProteins().isEmpty() && organism.getSamples().isEmpty()) { ContextualSessionHandler.delete(organism); } } private void deletePSM(Psm psm) { if (deletedPsms.contains(psm)) { return; } deletedPsms.add(psm); if (psm.getId() == null) { return; } // final MsRun msRun = psm.getMsRun(); // msRun.getPsms().remove(psm); // deleteMSRun(msRun); final Set<Ptm> ptms = psm.getPtms(); if (ptms != null) { for (final Ptm ptm : ptms) { deletePTM(ptm); } } final Set<PsmScore> scores = psm.getPsmScores(); if (scores != null) { for (final PsmScore psmScore : scores) { deletePSMScore(psmScore); } } final Set<PsmAmount> amounts = psm.getPsmAmounts(); if (amounts != null) { for (final PsmAmount psmAmount : amounts) { deletePsmAmount(psmAmount); } } // ratios final Set<PsmRatioValue> psmRatioValues = psm.getPsmRatioValues(); if (psmRatioValues != null) { for (final PsmRatioValue psmRatioValue : psmRatioValues) { deletePsmRatio(psmRatioValue); } } // conditions // final Set<Condition> conditions = psm.getConditions(); // for (final Condition condition : conditions) { // condition.getPsms().remove(psm); // } psm.getConditions().clear(); psm.setMsRun(null); final Iterator<Protein> iterator = psm.getProteins().iterator(); while (iterator.hasNext()) { final Protein protein = iterator.next(); protein.getPsms().remove(psm); iterator.remove(); } ContextualSessionHandler.delete(psm); } private void deletePeptide(Peptide peptide) { if (deletedPeptides.contains(peptide)) { return; } deletedPeptides.add(peptide); if (peptide.getId() == null) { return; } // deleteMSRun(peptide.getMsRun()); final Set<Ptm> ptms = peptide.getPtms(); if (ptms != null) { for (final Ptm ptm : ptms) { deletePTM(ptm); } } // scores final Set<PeptideScore> scores = peptide.getPeptideScores(); if (scores != null) { for (final PeptideScore psmScore : scores) { deletePeptideScore(psmScore); } } // amounts final Set<PeptideAmount> amounts = peptide.getPeptideAmounts(); if (amounts != null) { for (final PeptideAmount peptideAmount : amounts) { deletePeptideAmount(peptideAmount); } } // ratios final Set<PeptideRatioValue> peptideRatioValues = peptide.getPeptideRatioValues(); if (peptideRatioValues != null) { for (final PeptideRatioValue peptideRatioValue : peptideRatioValues) { deletePeptideRatio(peptideRatioValue); } } // conditions // final Set<Condition> conditions = peptide.getConditions(); // for (final Condition condition : conditions) { // condition.getPeptides().remove(peptide); // } peptide.getConditions().clear(); peptide.getMsRuns().clear(); // psms are the owners final Iterator<Psm> psmsIterator = peptide.getPsms().iterator(); while (psmsIterator.hasNext()) { final Psm psm = psmsIterator.next(); deletePSM(psm); psmsIterator.remove(); } final Iterator<Protein> proteinIterator = peptide.getProteins().iterator(); while (proteinIterator.hasNext()) { final Protein protein = proteinIterator.next(); protein.getPeptides().remove(peptide); proteinIterator.remove(); } ContextualSessionHandler.delete(peptide); } private void deletePSMScore(PsmScore psmScore) { // final ConfidenceScoreType confidenceScoreType = // psmScore.getConfidenceScoreType(); // if (confidenceScoreType != null) { // confidenceScoreType.getPsmScores().remove(psmScore); // // deleteConfidenceScoreType(confidenceScoreType); // // } ContextualSessionHandler.delete(psmScore); } private void deletePeptideScore(PeptideScore score) { // final ConfidenceScoreType confidenceScoreType = // score.getConfidenceScoreType(); // if (confidenceScoreType != null) { // deleteConfidenceScoreType(confidenceScoreType); // } ContextualSessionHandler.delete(score); } private void deleteProteinScore(ProteinScore score) { // final ConfidenceScoreType confidenceScoreType = // score.getConfidenceScoreType(); // if (confidenceScoreType != null) { // deleteConfidenceScoreType(confidenceScoreType); // } ContextualSessionHandler.delete(score); } private void deletePTM(Ptm ptm) { final Set<PtmSite> ptmSites = ptm.getPtmSites(); if (false) { for (final PtmSite ptmSite : ptmSites) { // final ConfidenceScoreType confidenceScoreType = // ptmSite.getConfidenceScoreType(); // if (confidenceScoreType != null) { // confidenceScoreType.getPtmSites().remove(ptmSite); // deleteConfidenceScoreType(confidenceScoreType); // } ContextualSessionHandler.delete(ptmSite); } } ContextualSessionHandler.delete(ptm); } private void deleteProteinRatio(ProteinRatioValue proteinRatioValue) { // deleteRatioDescriptor(proteinRatioValue.getRatioDescriptor()); // final ConfidenceScoreType scoreType = // proteinRatioValue.getConfidenceScoreType(); // if (scoreType != null) { // deleteConfidenceScoreType(scoreType); // // } // combination type // CombinationType combinationType = // proteinRatioValue.getCombinationType(); // if (combinationType != null) { // deleteCombinationType(combinationType); // } ContextualSessionHandler.delete(proteinRatioValue); // proteinRatioValue.getRatioDescriptor().getProteinRatioValues().remove(proteinRatioValue); } private void deletePeptideRatio(PeptideRatioValue peptideRatioValue) { // deletePeptide(peptideRatioValue.getPeptide()); // final ConfidenceScoreType scoreType = // peptideRatioValue.getConfidenceScoreType(); // if (scoreType != null) { // deleteConfidenceScoreType(scoreType); // // } // combination type // CombinationType combinationType = // peptideRatioValue.getCombinationType(); // if (combinationType != null) { // deleteCombinationType(combinationType); // } ContextualSessionHandler.delete(peptideRatioValue); } private void deletePsmRatio(PsmRatioValue psmRatioValue) { // final ConfidenceScoreType scoreType = // psmRatioValue.getConfidenceScoreType(); // if (scoreType != null) { // deleteConfidenceScoreType(scoreType); // // } // combination type // CombinationType combinationType = psmRatioValue.getCombinationType(); // if (combinationType != null) { // deleteCombinationType(combinationType); // } ContextualSessionHandler.delete(psmRatioValue); } private void deleteRatioDescriptor(RatioDescriptor ratioDescriptor) { ContextualSessionHandler.delete(ratioDescriptor); // final Set<ProteinRatioValue> proteinRatioValues = // ratioDescriptor.getProteinRatioValues(); // if (proteinRatioValues != null) { // for (ProteinRatioValue proteinRatioValue : proteinRatioValues) { // deleteProteinRatio(proteinRatioValue); // } // } // // final Set<PeptideRatioValue> peptideRatioValues = // ratioDescriptor.getPeptideRatioValues(); // if (peptideRatioValues != null) { // for (PeptideRatioValue peptideRatioValue : peptideRatioValues) { // deletePeptideRatio(peptideRatioValue); // } // } // // final Set<PsmRatioValue> psmRatioValues = // ratioDescriptor.getPsmRatioValues(); // if (psmRatioValues != null) { // for (PsmRatioValue psmRatioValue : psmRatioValues) { // deletePsmRatio(psmRatioValue); // } // } } private void deleteAppliedThreshold(ProteinThreshold appliedThreshold) { // deleteThreshold(appliedThreshold.getThreshold()); ContextualSessionHandler.delete(appliedThreshold); } private void deleteProteinAmount(ProteinAmount proteinAmount) { proteinAmount.getCondition().getProteinAmounts().remove(proteinAmount); ContextualSessionHandler.delete(proteinAmount); // amount type // final AmountType amountType = proteinAmount.getAmountType(); // if (amountType != null) // deleteAmountType(amountType); // combination type // CombinationType combinationType = proteinAmount.getCombinationType(); // if (combinationType != null) { // deleteCombinationType(combinationType); // } } private void deletePeptideAmount(PeptideAmount peptideAmount) { peptideAmount.getCondition().getPeptideAmounts().remove(peptideAmount); ContextualSessionHandler.delete(peptideAmount); // amount type // final AmountType amountType = peptideAmount.getAmountType(); // if (amountType != null) // deleteAmountType(amountType); // combination type // CombinationType combinationType = peptideAmount.getCombinationType(); // if (combinationType != null) { // deleteCombinationType(combinationType); // // } } private void deletePsmAmount(PsmAmount psmAmount) { psmAmount.getCondition().getPsmAmounts().remove(psmAmount); ContextualSessionHandler.delete(psmAmount); // amount type // final AmountType amountType = psmAmount.getAmountType(); // if (amountType != null) // deleteAmountType(amountType); // combination type // CombinationType combinationType = psmAmount.getCombinationType(); // if (combinationType != null) { // deleteCombinationType(combinationType); // } } private void deleteProteinAnnotation(ProteinAnnotation proteinAnnotation) { // deleteAnnotationType(proteinAnnotation.getAnnotationType()); ContextualSessionHandler.delete(proteinAnnotation); } private void deleteAnnotationType(AnnotationType annotationType) { ContextualSessionHandler.delete(annotationType); } private void deleteMSRun(MsRun msRun) throws InterruptedException { log.info("Deleting MSRun: " + msRun.getRunId() + " of project " + msRun.getProject().getTag()); ContextualSessionHandler.refresh(msRun); final Set<Protein> proteins = msRun.getProteins(); ProgressCounter counter = new ProgressCounter(proteins.size(), ProgressPrintingType.PERCENTAGE_STEPS, 0); counter.setShowRemainingTime(true); counter.setSuffix("proteins deleted"); final Iterator<Protein> iterator = proteins.iterator(); while (iterator.hasNext()) { final Protein protein = iterator.next(); counter.increment(); final String printIfNecessary = counter.printIfNecessary(); if (printIfNecessary != null && !"".equals(printIfNecessary)) { ContextualSessionHandler.flush(); log.info(printIfNecessary); } deleteProtein(protein); iterator.remove(); if (Thread.interrupted()) { throw new InterruptedException(); } } final Set<Peptide> peptides = msRun.getPeptides(); counter = new ProgressCounter(peptides.size(), ProgressPrintingType.PERCENTAGE_STEPS, 0); counter.setShowRemainingTime(true); counter.setSuffix("peptides deleted"); final Iterator<Peptide> iterator2 = peptides.iterator(); while (iterator2.hasNext()) { final Peptide peptide = iterator2.next(); counter.increment(); final String print = counter.printIfNecessary(); if (print != null && !"".equals(print)) { ContextualSessionHandler.flush(); log.info(print); } deletePeptide(peptide); iterator2.remove(); if (Thread.interrupted()) { throw new InterruptedException(); } } final Set<Psm> psms = msRun.getPsms(); counter = new ProgressCounter(psms.size(), ProgressPrintingType.PERCENTAGE_STEPS, 0); counter.setShowRemainingTime(true); counter.setSuffix("PSMs deleted"); final Iterator<Psm> iterator3 = psms.iterator(); while (iterator3.hasNext()) { final Psm psm = iterator3.next(); counter.increment(); final String print = counter.printIfNecessary(); if (print != null && !"".equals(print)) { ContextualSessionHandler.flush(); log.info(print); } deletePSM(psm); iterator3.remove(); if (Thread.interrupted()) { throw new InterruptedException(); } } ContextualSessionHandler.delete(msRun); } public boolean deleteProject2(String projectTag) throws InterruptedException { // look into the database if a project with the same name is already // created final Project hibProject = MySQLProteinDBInterface.getDBProjectByTag(projectTag); if (hibProject != null) { log.info("deleting project " + hibProject.getTag()); // get a map between MSRuns and Conditions final Map<MsRun, Set<Condition>> conditionsByMSRun = getConditionsByMSRun(hibProject); final Map<Condition, Set<MsRun>> msRunsByCondition = getMSRunsByCondition(conditionsByMSRun); int initialMSRunNumber = 0; final Set<MsRun> deletedMSRuns = new THashSet<MsRun>(); final Set<Condition> deletedConditions = new THashSet<Condition>(); while (true) { ContextualSessionHandler.beginGoodTransaction(); ContextualSessionHandler.refresh(hibProject); final Set<MsRun> msRuns = hibProject.getMsRuns(); if (initialMSRunNumber == 0) { initialMSRunNumber = msRuns.size(); } log.info(msRuns.size() + " MSRuns to delete in project " + hibProject.getTag()); final List<Condition> conditionList = new ArrayList<Condition>(); conditionList.addAll(msRunsByCondition.keySet()); Collections.sort(conditionList, new Comparator<Condition>() { @Override public int compare(Condition o1, Condition o2) { final Set<MsRun> msRuns1 = msRunsByCondition.get(o1); // String conditionString1 = // getConditionString(conditions1); final Set<MsRun> msRuns2 = msRunsByCondition.get(o2); // String conditionString2 = // getConditionString(conditions2); // return conditionString1.compareTo(conditionString2); return Integer.compare(msRuns1.size(), msRuns2.size()); } }); for (final Condition condition : conditionList) { final Set<MsRun> msRunList = msRunsByCondition.get(condition); ContextualSessionHandler.beginGoodTransaction(); for (final MsRun msRun : msRunList) { if (deletedMSRuns.contains(msRun)) { continue; } deleteMSRun(msRun); deletedMSRuns.add(msRun); final Set<Condition> conditions = conditionsByMSRun.get(msRun); log.info(conditions.size() + " conditions associated with MSRun " + msRun.getRunId()); log.info("conditions associated: " + getConditionString(conditionsByMSRun.get(msRun))); // check if all msruns of all conditions have been // deleted boolean allDeleted = true; if (conditions != null) { for (final Condition condition2 : conditions) { final Set<MsRun> msRunSet = msRunsByCondition.get(condition2); for (final MsRun msRun2 : msRunSet) { if (!deletedMSRuns.contains(msRun2)) { log.info(msRun2.getRunId() + " is not yet deleted... continuing the loop."); allDeleted = false; break; } } } } if (allDeleted) { log.info("Flushing session..."); ContextualSessionHandler.flush(); log.info("Clearing session..."); ContextualSessionHandler.clear(); log.info("Session clear."); ContextualSessionHandler.finishGoodTransaction(); break; } } } if (initialMSRunNumber == deletedMSRuns.size()) { break; } } ContextualSessionHandler.beginGoodTransaction(); ContextualSessionHandler.refresh(hibProject); final Set<Condition> conditions = hibProject.getConditions(); for (final Condition condition : conditions) { deleteCondition(condition, false); } for (final Condition condition : conditions) { final Sample sample = condition.getSample(); deleteSample(sample); } ContextualSessionHandler.delete(hibProject); return true; } else { throw new IllegalArgumentException(projectTag + " doesn't exist"); } } public boolean deleteProject(String projectTag) throws InterruptedException { // look into the database if a project with the same name is already // created final Project hibProject = MySQLProteinDBInterface.getDBProjectByTag(projectTag); if (hibProject != null) { log.info("deleting project " + hibProject.getTag() + " with id: " + hibProject.getId()); // get a map between MSRuns and Conditions final Map<MsRun, Set<Condition>> conditionsByMSRun = getConditionsByMSRun(hibProject); // final Map<Condition, Set<MsRun>> msRunsByCondition = getMSRunsByCondition(conditionsByMSRun); int initialMSRunNumber = 0; ContextualSessionHandler.beginGoodTransaction(); ContextualSessionHandler.refresh(hibProject); final Set<MsRun> msRuns = hibProject.getMsRuns(); boolean deleteProteins = false; if (!msRuns.isEmpty()) { for (final MsRun msRun : msRuns) { ContextualSessionHandler.beginGoodTransaction(); deleteMSRun(msRun); log.info("Flushing session..."); ContextualSessionHandler.flush(); // log.info("Clearing session..."); // ContextualSessionHandler.clear(); log.info("Session clear. Now finishing transaction"); ContextualSessionHandler.finishGoodTransaction(); log.info("Transaction finished."); } } else { // there is no msRuns, but we can delete protein, peptides and so on from // conditions deleteProteins = true; } ContextualSessionHandler.beginGoodTransaction(); if (initialMSRunNumber == 0) { initialMSRunNumber = msRuns.size(); } final Set<Condition> conditions = hibProject.getConditions(); for (final Condition condition : conditions) { deleteCondition(condition, deleteProteins); } for (final Condition condition : conditions) { final Sample sample = condition.getSample(); deleteSample(sample); } ContextualSessionHandler.delete(hibProject); return true; } else { throw new IllegalArgumentException(projectTag + " doesn't exist"); } } private String getConditionString(Set<Condition> conditions) { final List<String> list = new ArrayList<String>(); for (final Condition condition : conditions) { if (!list.contains(condition.getName())) { list.add(condition.getName()); } } final StringBuilder sb = new StringBuilder(); Collections.sort(list); for (final String conditionName : list) { sb.append(conditionName + ","); } return sb.toString(); } private Map<MsRun, Set<Condition>> getConditionsByMSRun(Project hibProject) { log.info("Getting conditions mapped to MSRuns..."); final Map<MsRun, Set<Condition>> conditionsByMSRun = new THashMap<MsRun, Set<Condition>>(); final Set<MsRun> msRuns = hibProject.getMsRuns(); for (final MsRun msRun : msRuns) { // Set<Condition> conditions = new THashSet<Condition>(); // final Set<Psm> psms = msRun.getPsms(); // for (Psm psm : psms) { // conditions.addAll(psm.getConditions()); // break; // } // psms.clear(); // System.gc(); // final Set<Protein> proteins = msRun.getProteins(); // for (Protein protein : proteins) { // conditions.addAll(protein.getConditions()); // break; // } // proteins.clear(); // System.gc(); // final Set<Peptide> peptides = msRun.getPeptides(); // for (Peptide peptide : peptides) { // conditions.addAll(peptide.getConditions()); // break; // } // peptides.clear(); // System.gc(); final List<Condition> conditions = PreparedCriteria.getConditionsByMSRunCriteria(msRun); final Set<Condition> set = new THashSet<Condition>(); set.addAll(conditions); log.info("MSRun " + msRun.getRunId() + " mapped to " + conditions.size() + " conditions"); conditionsByMSRun.put(msRun, set); if (true) { break; } } log.info(conditionsByMSRun.size() + " conditions mapped to MSRuns."); return conditionsByMSRun; } private void deleteCondition(Condition condition, boolean deleteProteins) throws InterruptedException { if (deleteProteins) { deleteProteinsFromCondition(condition); } final Set<RatioDescriptor> set = new HashSet<RatioDescriptor>(); // ratio descriptors set.addAll(condition.getRatioDescriptorsForExperimentalCondition1Id()); set.addAll(condition.getRatioDescriptorsForExperimentalCondition2Id()); for (final RatioDescriptor ratioDescriptor : set) { deleteRatioDescriptor(ratioDescriptor); } ContextualSessionHandler.delete(condition); } private void deleteProteinsFromCondition(Condition condition) throws InterruptedException { log.info("Deleting condition: " + condition.getId() + " of project " + condition.getProject().getTag()); ContextualSessionHandler.refresh(condition); final Set<Protein> proteins = condition.getProteins(); ProgressCounter counter = new ProgressCounter(proteins.size(), ProgressPrintingType.PERCENTAGE_STEPS, 0); counter.setShowRemainingTime(true); counter.setSuffix("proteins deleted"); final Iterator<Protein> iterator = proteins.iterator(); while (iterator.hasNext()) { final Protein protein = iterator.next(); counter.increment(); final String printIfNecessary = counter.printIfNecessary(); if (printIfNecessary != null && !"".equals(printIfNecessary)) { ContextualSessionHandler.flush(); log.info(printIfNecessary); } deleteProtein(protein); iterator.remove(); if (Thread.interrupted()) { throw new InterruptedException(); } } final Set<Peptide> peptides = condition.getPeptides(); counter = new ProgressCounter(peptides.size(), ProgressPrintingType.PERCENTAGE_STEPS, 0); counter.setShowRemainingTime(true); counter.setSuffix("peptides deleted"); final Iterator<Peptide> iterator2 = peptides.iterator(); while (iterator2.hasNext()) { final Peptide peptide = iterator2.next(); counter.increment(); final String print = counter.printIfNecessary(); if (print != null && !"".equals(print)) { ContextualSessionHandler.flush(); log.info(print); } deletePeptide(peptide); iterator2.remove(); if (Thread.interrupted()) { throw new InterruptedException(); } } final Set<Psm> psms = condition.getPsms(); counter = new ProgressCounter(psms.size(), ProgressPrintingType.PERCENTAGE_STEPS, 0); counter.setShowRemainingTime(true); counter.setSuffix("PSMs deleted"); final Iterator<Psm> iterator3 = psms.iterator(); while (iterator3.hasNext()) { final Psm psm = iterator3.next(); counter.increment(); final String print = counter.printIfNecessary(); if (print != null && !"".equals(print)) { ContextualSessionHandler.flush(); log.info(print); } deletePSM(psm); iterator3.remove(); if (Thread.interrupted()) { throw new InterruptedException(); } } ContextualSessionHandler.delete(condition); } private Map<Condition, Set<MsRun>> getMSRunsByCondition(Map<MsRun, Set<Condition>> conditionsByMSRun) { final Map<Condition, Set<MsRun>> msRunsByCondition = new THashMap<Condition, Set<MsRun>>(); log.info("Getting MSRuns mapped to conditions..."); final Set<MsRun> msruns = conditionsByMSRun.keySet(); for (final MsRun msrun : msruns) { final Set<Condition> conditions = conditionsByMSRun.get(msrun); for (final Condition condition2 : conditions) { if (msRunsByCondition.containsKey(condition2)) { msRunsByCondition.get(condition2).add(msrun); } else { final Set<MsRun> msRunSet = new THashSet<MsRun>(); msRunSet.add(msrun); msRunsByCondition.put(condition2, msRunSet); } } } log.info(msRunsByCondition.size() + " MSRuns mapped to conditions."); return msRunsByCondition; } private void deleteSample(Sample sample) { final Tissue tissue = sample.getTissue(); tissue.getSamples().remove(sample); if (tissue != null && tissue.getSamples().isEmpty()) { ContextualSessionHandler.delete(tissue); } final Label label = sample.getLabel(); if (label != null && label.getSamples() != null) { label.getSamples().remove(sample); if (label.getSamples().isEmpty()) { ContextualSessionHandler.delete(label); } } final Set<Organism> organisms = sample.getOrganisms(); for (final Organism organism : organisms) { if (organism.getSamples() != null) { organism.getSamples().remove(sample); if (organism.getSamples().isEmpty()) { deleteOrganism(organism); } } } ContextualSessionHandler.delete(sample); } }
33.870101
108
0.699861
34ed4ac0a6ed71cdd4d7a1b469467179dbc6b71f
695
package p05_Border_Control; public class Citizen extends BaseCitizen{ private String name; private Integer age; // private Integer id; public Citizen(String name, Integer age, String id) { super(id); this.setName(name); this.setAge(age); } public String getName() { return this.name; } private void setName(String name) { this.name = name; } public Integer getAge() { return this.age; } private void setAge(Integer age) { this.age = age; } // public Integer getId() { // return this.id; // } // // private void setId(Integer id) { // this.id = id; // } }
18.289474
57
0.564029
551c3a2dae84781f9300ac1499c32d3e75a59cb4
1,967
/******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use these files except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2014 - Juan Pino, Aurelien Waite, William Byrne *******************************************************************************/ package uk.ac.cam.eng.extraction.hadoop.merge; import java.io.IOException; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; import uk.ac.cam.eng.extraction.Rule; /** * Need a byte level comparator for rule writable. Otherwise we are unable to * add it to the HFILE * * @author Aurelien Waite * @date 28 May 2014 */ public class MergeComparator extends WritableComparator { private final DataOutputBuffer buffera = new DataOutputBuffer(); private final DataOutputBuffer bufferb = new DataOutputBuffer(); public MergeComparator() { super(Rule.class); } @Override @SuppressWarnings("rawtypes") public int compare(WritableComparable a, WritableComparable b) { try { buffera.reset(); a.write(buffera); bufferb.reset(); b.write(bufferb); return compareBytes(buffera.getData(), 0, buffera.getLength(), bufferb.getData(), 0, bufferb.getLength()); } catch (IOException e) { throw new RuntimeException(e); } } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return compareBytes(b1, s1, l1, b2, s2, l2); } }
31.222222
81
0.673615
640caf143d405cdfe124c0edac125e8432c90a3e
1,942
/** * Copyright (c) 2003-2019 The Apereo Foundation * * Licensed under the Educational Community 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://opensource.org/licenses/ecl2 * * 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.sakaiproject.onedrive.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @JsonIgnoreProperties(ignoreUnknown = true) public class OneDriveItem { @JsonProperty("id") private String oneDriveItemId; private String name; private Long size; @JsonProperty(value = "@microsoft.graph.downloadUrl")//this is always public //@JsonProperty(value = "webUrl")//this checks against onedrive permissions private String downloadUrl; private OneDriveFolder folder; private OneDriveFile file; @JsonProperty(value = "parentReference") private OneDriveParent parent; public boolean isFolder() { return folder != null; } public boolean hasChildren() { return isFolder() && folder.childCount != 0; } private int depth = 0; private boolean expanded = false; @Override public boolean equals(Object obj) { boolean retVal = false; if (obj instanceof OneDriveItem){ OneDriveItem ptr = (OneDriveItem) obj; return this.oneDriveItemId.equals(ptr.getOneDriveItemId()); } return retVal; } }
28.985075
81
0.704943
108e56256a3a1addf348c5dca4d70dc1d02ad60c
2,192
/* * MIT License * * Copyright (c) 2021 Staatsbibliothek zu Berlin - Preußischer Kulturbesitz * * 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 NON INFRINGEMENT. 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 de.staatsbibliothek.berlin.hsp.fo.discovery.ui.response; import java.io.Serializable; /** * * @author Lutz Helm {@literal <[email protected]>} * */ public class Stats implements Serializable { /** * */ private static final long serialVersionUID = 1L; private Double min; private Double max; private long count; private long missing; public Stats(Double min, Double max, long count, long missing) { super(); this.min = min; this.max = max; this.count = count; this.missing = missing; } public Double getMin() { return min; } public void setMin(Double min) { this.min = min; } public Double getMax() { return max; } public void setMax(Double max) { this.max = max; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } public long getMissing() { return missing; } public void setMissing(long missing) { this.missing = missing; } }
25.788235
81
0.703011
458fbc595d806bb32dd59bd26d3653a05167b8ec
10,192
package openfoodfacts.github.scrachx.openfood.fragments; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.view.animation.LinearOutSlowInInterpolator; import android.text.Html; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.StyleSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.hkm.slider.Animations.DescriptionAnimation; import com.hkm.slider.Indicators.PagerIndicator; import com.hkm.slider.SliderLayout; import com.hkm.slider.SliderTypes.AdjustableSlide; import com.hkm.slider.SliderTypes.BaseSliderView; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import butterknife.BindView; import openfoodfacts.github.scrachx.openfood.R; import openfoodfacts.github.scrachx.openfood.models.State; public class SummaryProductFragment extends BaseFragment { @BindView(R.id.textNameProduct) TextView nameProduct; @BindView(R.id.textBarcodeProduct) TextView barCodeProduct; @BindView(R.id.textQuantityProduct) TextView quantityProduct; @BindView(R.id.textPackagingProduct) TextView packagingProduct; @BindView(R.id.textBrandProduct) TextView brandProduct; @BindView(R.id.textManufacturingProduct) TextView manufacturingProduct; @BindView(R.id.textCityProduct) TextView cityProduct; @BindView(R.id.textStoreProduct) TextView storeProduct; @BindView(R.id.textCountryProduct) TextView countryProduct; @BindView(R.id.textCategoryProduct) TextView categoryProduct; @BindView(R.id.slider) SliderLayout sliderImages; @BindView(R.id.custom_indicator) PagerIndicator pagerIndicator; public static final Pattern CODE_PATTERN = Pattern.compile("[eE][a-zA-Z0-9]+"); public static final Pattern INGREDIENT_PATTERN = Pattern.compile("[a-zA-Z0-9(),àâçéèêëîïôûùüÿñæœ.-]+"); public static final Pattern ALLERGEN_PATTERN = Pattern.compile("[a-zA-Z0-9àâçéèêëîïôûùüÿñæœ]+"); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return createView(inflater, container, R.layout.fragment_summary_product); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Intent intent = getActivity().getIntent(); State state = (State) intent.getExtras().getSerializable("state"); ArrayList<String> urlsImages = new ArrayList<>(); if (state.getProduct().getImageUrl() != null) { urlsImages.add(state.getProduct().getImageUrl()); } if (state.getProduct().getImageIngredientsUrl() != null) { urlsImages.add(state.getProduct().getImageIngredientsUrl()); } if (state.getProduct().getImageNutritionUrl() != null) { urlsImages.add(state.getProduct().getImageNutritionUrl()); } ArrayList<AdjustableSlide> list = new ArrayList<>(); for (int h = 0; h < urlsImages.size(); h++) { AdjustableSlide textSliderView = new AdjustableSlide(view.getContext()); textSliderView .image(urlsImages.get(h)) .setScaleType(BaseSliderView.ScaleType.FitCenterCrop); list.add(textSliderView); } sliderImages.loadSliderList(list); sliderImages.setCustomAnimation(new DescriptionAnimation()); sliderImages.setSliderTransformDuration(1000, new LinearOutSlowInInterpolator()); sliderImages.setCustomIndicator(pagerIndicator); sliderImages.setDuration(5500); sliderImages.startAutoCycle(); SpannableStringBuilder txtIngredients = new SpannableStringBuilder(Html.fromHtml(state.getProduct().getIngredientsText().replace("_",""))); if(state.getProduct().getProductName() != null && !state.getProduct().getProductName().trim().isEmpty()) { nameProduct.setText(state.getProduct().getProductName()); } else { nameProduct.setVisibility(View.GONE); } if(state.getProduct().getCode() != null && !state.getProduct().getCode().trim().isEmpty()) { String result = " Halal" ; if( state.getProduct().getIngredientsText().toString().toLowerCase().contains("porc".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("Gélatine".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("E441".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("E519".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("Sulfate de cuivre".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("Phosphate d'os".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("E542".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("E519".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("vin".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("liégeois".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("animales".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("porcines".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("alcool".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("liégeois".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("animales".toLowerCase()) || state.getProduct().getIngredientsText().toString().toLowerCase().contains("porcines".toLowerCase()) ) { result = " Non Halal" ; } barCodeProduct.setText(Html.fromHtml("<b>" + getString(R.string.txtBarcode) + "</b>" + result )); if( result.toString().toLowerCase().contains( "Non".toString().toLowerCase() )){ barCodeProduct.setTextColor(Color.rgb(220,20,60)); }else { // barCodeProduct.setTextColor(Color.rgb(0,100,0)); barCodeProduct.setTextColor(Color.rgb(34,139,34)); } } else { barCodeProduct.setVisibility(View.GONE); } if(state.getProduct().getQuantity() != null && !state.getProduct().getQuantity().trim().isEmpty()) { quantityProduct.setText(Html.fromHtml("<b>" + getString(R.string.txtQuantity) + "</b>" + ' ' + state.getProduct().getQuantity())); } else { quantityProduct.setVisibility(View.GONE); } if(state.getProduct().getPackaging() != null && !state.getProduct().getPackaging().trim().isEmpty()) { packagingProduct.setText(Html.fromHtml("<b>" + getString(R.string.txtPackaging) + "</b>" + ' ' + state.getProduct().getPackaging())); } else { packagingProduct.setVisibility(View.GONE); } if(state.getProduct().getBrands() != null && !state.getProduct().getBrands().trim().isEmpty()) { brandProduct.setText(Html.fromHtml("<b>" + getString(R.string.txtBrands) + "</b>" + ' ' + state.getProduct().getBrands())); } else { brandProduct.setVisibility(View.GONE); } if(state.getProduct().getManufacturingPlaces() != null && !state.getProduct().getManufacturingPlaces().trim().isEmpty()) { manufacturingProduct.setText(Html.fromHtml("<b>" + getString(R.string.txtManufacturing) + "</b>" + ' ' + state.getProduct().getManufacturingPlaces())); } else { manufacturingProduct.setVisibility(View.GONE); } String categ; if (state.getProduct().getCategories() != null && !state.getProduct().getCategories().trim().isEmpty()) { categ = state.getProduct().getCategories().replace(",", ", "); categoryProduct.setText(Html.fromHtml("<b>" + getString(R.string.txtCategories) + "</b>" + ' ' + categ)); } else { categoryProduct.setVisibility(View.GONE); } if(state.getProduct().getCitiesTags() != null && !state.getProduct().getCitiesTags().toString().trim().equals("[]")) { cityProduct.setText(Html.fromHtml("<b>" + getString(R.string.txtCity) + "</b>" + ' ' + state.getProduct().getCitiesTags().toString().replace("[", "").replace("]", ""))); } else { cityProduct.setVisibility(View.GONE); } if(state.getProduct().getStores() != null && !state.getProduct().getStores().trim().isEmpty()) { storeProduct.setText(Html.fromHtml("<b>" + getString(R.string.txtStores) + "</b>" + ' ' + state.getProduct().getStores())); } else { storeProduct.setVisibility(View.GONE); } if(state.getProduct().getCountries() != null && !state.getProduct().getCountries().trim().isEmpty()) { countryProduct.setText(Html.fromHtml("<b>" + getString(R.string.txtCountries) + "</b>" + ' ' + state.getProduct().getCountries())); } else { countryProduct.setVisibility(View.GONE); } } @Override public void onStop() { sliderImages.stopAutoCycle(); super.onStop(); } }
50.96
181
0.638736
e2ba7479622ff4f14ee1b13882b8dea4a5a6e96e
1,737
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import java.util.concurrent.TimeUnit; public class TestBase { WebDriver wd; @BeforeSuite public void init () { wd = new ChromeDriver(); wd.navigate().to("https://contacts-app.tobbymarshall815.vercel.app/home"); wd.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); } @AfterSuite public void tearDown () { // wd.quit(); } public boolean isElementPresent(By locator) { return wd.findElements(locator).size() > 0; } public void submitRegistration () { click(By.xpath("//button[2]")); } public void fillLoginRegistrationForm(String email,String password) { type(By.xpath("//input[1]"), email); type(By.xpath("//input[2]"), password); } public void type (By locator,String text) { if(text != null){ WebElement element = wd.findElement(locator); element.click(); element.clear(); element.sendKeys(text); } } public void openLoginRegistrationForm () { click(By.xpath("//a[text()='lOGIN']")); } public void click (By locator) { wd.findElement(locator).click(); } public void submitLogin () { click(By.xpath("//button[1]")); } public void pause (int millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /*public boolean isLogged () { } */ }
24.814286
82
0.602188
725edd059282afa9b6d160e4cc0375776e4024d7
21,755
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.sunshine.app; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.wearable.watchface.CanvasWatchFaceService; import android.support.wearable.watchface.WatchFaceStyle; import android.text.format.DateFormat; import android.view.SurfaceHolder; import android.view.WindowInsets; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.wearable.DataApi; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.DataItem; import com.google.android.gms.wearable.DataItemBuffer; import com.google.android.gms.wearable.DataMapItem; import com.google.android.gms.wearable.Wearable; import java.lang.ref.WeakReference; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * Digital watch face with seconds. In ambient mode, the seconds aren't displayed. On devices with * low-bit ambient mode, the text is drawn without anti-aliasing in ambient mode. */ public class MyWatchFace extends CanvasWatchFaceService { private static final Typeface NORMAL_TYPEFACE = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL); private static final Typeface THIN_TYPEFACE = Typeface.create(Typeface.SANS_SERIF, Typeface.ITALIC); /** * Update rate in milliseconds for interactive mode. We update once a second since seconds are * displayed in interactive mode. */ private static final long INTERACTIVE_UPDATE_RATE_MS = 500; long mInteractiveUpdateRateMs = INTERACTIVE_UPDATE_RATE_MS; /** * Handler message id for updating the time periodically in interactive mode. */ private static final int MSG_UPDATE_TIME = 0; public static final String PATH_WITH_WEATHER = "/weather"; private static final String COLON_STRING = ":"; @Override public Engine onCreateEngine() { return new Engine(); } private static class EngineHandler extends Handler { private final WeakReference<MyWatchFace.Engine> mWeakReference; public EngineHandler(MyWatchFace.Engine reference) { mWeakReference = new WeakReference<>(reference); } @Override public void handleMessage(Message msg) { MyWatchFace.Engine engine = mWeakReference.get(); if (engine != null) { switch (msg.what) { case MSG_UPDATE_TIME: engine.handleUpdateTimeMessage(); break; } } } } private class Engine extends CanvasWatchFaceService.Engine implements DataApi.DataListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { final Handler mUpdateTimeHandler = new EngineHandler(this); boolean mRegisteredTimeZoneReceiver = false; int i = 10; Paint mTextPaint; boolean mAmbient; String mAmString; String mPmString; int weatherId; String Tmax = null; String Tmin = null; Paint mBackgroundPaint; Paint mDatePaint; Paint mHourPaint; Paint mMinutePaint; Paint mSecondPaint; Paint mAmPmPaint; Paint mColonPaint; float mLineHeight; float mLineWidth; boolean mShouldDrawColons; Calendar mCalendar; Date mDate; float mColonWidth; java.text.DateFormat mDateFormat; GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(MyWatchFace.this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Wearable.API) .build(); final BroadcastReceiver mTimeZoneReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mCalendar.setTimeZone(TimeZone.getDefault()); initFormats(); invalidate(); } }; float mXOffset; float mYOffset; /** * Whether the display supports fewer bits for each color in ambient mode. When true, we * disable anti-aliasing in ambient mode. */ boolean mLowBitAmbient; Bitmap ic_clear, ic_storm, ic_light_rain, ic_rain, ic_snow, ic_fog, ic_light_clouds, ic_cloudy; @Override public void onCreate(SurfaceHolder holder) { super.onCreate(holder); setWatchFaceStyle(new WatchFaceStyle.Builder(MyWatchFace.this) .setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE) .setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE) .setShowSystemUiTime(false) .build()); Resources resources = MyWatchFace.this.getResources(); mBackgroundPaint = new Paint(); mBackgroundPaint.setColor(resources.getColor(R.color.background)); mTextPaint = new Paint(); mTextPaint = createTextPaint(resources.getColor(R.color.digital_text)); mLineHeight = resources.getDimension(R.dimen.digital_line_height); mLineWidth = resources.getDimension(R.dimen.digital_line_width); mAmString = resources.getString(R.string.digital_am); mPmString = resources.getString(R.string.digital_pm); mDatePaint = createTextPaint(resources.getColor(R.color.digital_date), THIN_TYPEFACE); mHourPaint = createTextPaint(resources.getColor(R.color.digital_text)); mMinutePaint = createTextPaint(resources.getColor(R.color.digital_text)); mSecondPaint = createTextPaint(resources.getColor(R.color.digital_text)); mAmPmPaint = createTextPaint(resources.getColor(R.color.digital_am_pm)); mColonPaint = createTextPaint(resources.getColor(R.color.digital_colons)); mCalendar = Calendar.getInstance(); initFormats(); mDate = new Date(); ic_clear = BitmapFactory.decodeResource(getResources(), R.drawable.ic_clear); ic_storm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_clear); ic_light_rain = BitmapFactory.decodeResource(getResources(), R.drawable.ic_light_rain); ic_rain = BitmapFactory.decodeResource(getResources(), R.drawable.ic_rain); ic_snow = BitmapFactory.decodeResource(getResources(), R.drawable.ic_snow); ic_rain = BitmapFactory.decodeResource(getResources(), R.drawable.ic_rain); ic_snow = BitmapFactory.decodeResource(getResources(), R.drawable.ic_snow); ic_fog = BitmapFactory.decodeResource(getResources(), R.drawable.ic_fog); ic_storm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_storm); ic_clear = BitmapFactory.decodeResource(getResources(), R.drawable.ic_clear); ic_light_clouds = BitmapFactory.decodeResource(getResources(), R.drawable.ic_light_clouds); ic_cloudy = BitmapFactory.decodeResource(getResources(), R.drawable.ic_cloudy); } private void initFormats() { mDateFormat = new SimpleDateFormat("EE, dd MMM yyyy", Locale.getDefault()); mDateFormat.setCalendar(mCalendar); } @Override public void onDestroy() { mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME); super.onDestroy(); } private Paint createTextPaint(int textColor) { return createTextPaint(textColor, NORMAL_TYPEFACE); } private Paint createTextPaint(int textColor, Typeface typeface) { Paint paint = new Paint(); paint.setColor(textColor); paint.setTypeface(typeface); paint.setAntiAlias(true); return paint; } @Override public void onVisibilityChanged(boolean visible) { super.onVisibilityChanged(visible); if (visible) { registerReceiver(); mGoogleApiClient.connect(); mCalendar.setTimeZone(TimeZone.getDefault()); initFormats(); } else { unregisterReceiver(); if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { Wearable.DataApi.removeListener(mGoogleApiClient, this); mGoogleApiClient.disconnect(); } } // Whether the timer should be running depends on whether we're visible (as well as // whether we're in ambient mode), so we may need to start or stop the timer. updateTimer(); } private void registerReceiver() { if (mRegisteredTimeZoneReceiver) { return; } mRegisteredTimeZoneReceiver = true; IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED); MyWatchFace.this.registerReceiver(mTimeZoneReceiver, filter); } private void unregisterReceiver() { if (!mRegisteredTimeZoneReceiver) { return; } mRegisteredTimeZoneReceiver = false; MyWatchFace.this.unregisterReceiver(mTimeZoneReceiver); } @Override public void onApplyWindowInsets(WindowInsets insets) { super.onApplyWindowInsets(insets); // Load resources that have alternate values for round watches. Resources resources = MyWatchFace.this.getResources(); boolean isRound = insets.isRound(); mXOffset = resources.getDimension(isRound ? R.dimen.digital_x_offset_round : R.dimen.digital_x_offset); mYOffset = resources.getDimension(isRound ? R.dimen.digital_y_offset_round : R.dimen.digital_y_offset_square); float textSize = resources.getDimension(isRound ? R.dimen.digital_text_size_round : R.dimen.digital_text_size); mTextPaint.setTextSize(textSize); mColonWidth = mTextPaint.measureText(COLON_STRING); mDatePaint.setTextSize(resources.getDimension(R.dimen.digital_date_text_size)); mHourPaint.setTextSize(textSize); mMinutePaint.setTextSize(textSize); mSecondPaint.setTextSize(textSize); mAmPmPaint.setTextSize(textSize); mColonPaint.setTextSize(textSize); } @Override public void onPropertiesChanged(Bundle properties) { super.onPropertiesChanged(properties); mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false); } @Override public void onTimeTick() { super.onTimeTick(); invalidate(); } @Override public void onAmbientModeChanged(boolean inAmbientMode) { super.onAmbientModeChanged(inAmbientMode); mAmbient = inAmbientMode; if (inAmbientMode) { mDatePaint.setColor(getColor(R.color.digital_text)); mColonPaint.setColor(getColor(R.color.digital_text)); } else { mDatePaint.setColor(getColor(R.color.digital_date)); mColonPaint.setColor(getColor(R.color.digital_colons)); } if (mLowBitAmbient) { mTextPaint.setAntiAlias(!inAmbientMode); mDatePaint.setAntiAlias(!inAmbientMode); mHourPaint.setAntiAlias(!inAmbientMode); mMinutePaint.setAntiAlias(!inAmbientMode); mSecondPaint.setAntiAlias(!inAmbientMode); mAmPmPaint.setAntiAlias(!inAmbientMode); mColonPaint.setAntiAlias(!inAmbientMode); } invalidate(); // Whether the timer should be running depends on whether we're visible (as well as // whether we're in ambient mode), so we may need to start or stop the timer. updateTimer(); } private String formatTwoDigitNumber(int hour) { return String.format("%02d", hour); } private String getAmPmString(int amPm) { return amPm == Calendar.AM ? mAmString : mPmString; } @Override public void onDraw(Canvas canvas, Rect bounds) { // Draw the background. if (isInAmbientMode()) { canvas.drawColor(Color.BLACK); } else { canvas.drawRect(0, 0, bounds.width(), bounds.height(), mBackgroundPaint); } long now = System.currentTimeMillis(); mCalendar.setTimeInMillis(now); mDate.setTime(now); boolean is24Hour = DateFormat.is24HourFormat(MyWatchFace.this); // Show colons for the first half of each second so the colons blink on when the time // updates. mShouldDrawColons = (System.currentTimeMillis() % 1000) < 500; // Draw the hours. float x = (float) (mXOffset + mLineWidth); String hourString; if (is24Hour) { hourString = formatTwoDigitNumber(mCalendar.get(Calendar.HOUR_OF_DAY)); } else { int hour = mCalendar.get(Calendar.HOUR); if (hour == 0) { hour = 12; } hourString = String.valueOf(hour); } canvas.drawText(hourString, x, mYOffset, mHourPaint); x += mHourPaint.measureText(hourString); // In ambient and mute modes, always draw the first colon. Otherwise, draw the // first colon for the first half of each second. if (isInAmbientMode() || mShouldDrawColons) { canvas.drawText(COLON_STRING, x, mYOffset, mColonPaint); } x += mColonWidth; // Draw the minutes. String minuteString = formatTwoDigitNumber(mCalendar.get(Calendar.MINUTE)); canvas.drawText(minuteString, x, mYOffset, mMinutePaint); x += mMinutePaint.measureText(minuteString); if (!isInAmbientMode()) { if (mShouldDrawColons) { canvas.drawText(COLON_STRING, x, mYOffset, mColonPaint); } x += mColonWidth; canvas.drawText(formatTwoDigitNumber( mCalendar.get(Calendar.SECOND)), x, mYOffset, mSecondPaint); } else if (!is24Hour) { x += mColonWidth; canvas.drawText(getAmPmString( mCalendar.get(Calendar.AM_PM)), x, mYOffset, mAmPmPaint); } canvas.drawText( mDateFormat.format(mDate), (float) (mXOffset + mLineWidth*0.6), mYOffset + mLineHeight, mDatePaint); Bitmap bitmap = getIconResourceForWeatherCondition(weatherId); double mf = 1; if (getPeekCardPosition().isEmpty() && bitmap != null) { if (!isInAmbientMode()) { canvas.drawBitmap(bitmap, mXOffset - mLineWidth, (float) (mYOffset + mLineHeight * 1.8), null); canvas.drawLine(mXOffset + mLineWidth * 3, (float) (mYOffset + mLineHeight * 1.2), mXOffset + mLineWidth * 4, (float) (mYOffset + mLineHeight * 1.2), mDatePaint); mf = 2.5; } canvas.drawText(Tmax + " " + Tmin, (float) (mXOffset + mLineWidth * mf), (float) (mYOffset + mLineHeight * 3.2), mTextPaint); } } private Bitmap getIconResourceForWeatherCondition(int weatherId) { if (weatherId >= 200 && weatherId <= 232) { return ic_storm; } else if (weatherId >= 300 && weatherId <= 321) { return ic_light_rain; } else if (weatherId >= 500 && weatherId <= 504) { return ic_rain; } else if (weatherId == 511) { return ic_snow; } else if (weatherId >= 520 && weatherId <= 531) { return ic_rain; } else if (weatherId >= 600 && weatherId <= 622) { return ic_snow; } else if (weatherId >= 701 && weatherId <= 761) { return ic_fog; } else if (weatherId == 761 || weatherId == 781) { return ic_storm; } else if (weatherId == 800) { return ic_clear; } else if (weatherId == 801) { return ic_light_clouds; } else if (weatherId >= 802 && weatherId <= 804) { return ic_cloudy; } return null; } /** * Starts the {@link #mUpdateTimeHandler} timer if it should be running and isn't currently * or stops it if it shouldn't be running but currently is. */ private void updateTimer() { mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME); if (shouldTimerBeRunning()) { mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME); } } /** * Returns whether the {@link #mUpdateTimeHandler} timer should be running. The timer should * only run when we're visible and in interactive mode. */ private boolean shouldTimerBeRunning() { return isVisible() && !isInAmbientMode(); } /** * Handle updating the time periodically in interactive mode. */ private void handleUpdateTimeMessage() { invalidate(); if (shouldTimerBeRunning()) { long timeMs = System.currentTimeMillis(); long delayMs = mInteractiveUpdateRateMs - (timeMs % mInteractiveUpdateRateMs); mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs); } } private void getData(String data){ String[] weather = data.split("`"); weatherId = Integer.parseInt(weather[0]); Tmax =weather[1]; Tmin =weather[2]; } @Override public void onConnected(Bundle bundle) { Wearable.DataApi.addListener(mGoogleApiClient, Engine.this); updateDataItemAndUiOnStartup(); } private void updateDataItemAndUiOnStartup() { PendingResult<DataItemBuffer> results = Wearable.DataApi.getDataItems(mGoogleApiClient); results.setResultCallback(new ResultCallback<DataItemBuffer>() { @Override public void onResult(DataItemBuffer dataItems) { if (dataItems.getCount() != 0) { DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItems.get(0)); String data = dataMapItem.getDataMap().getString("key"); getData(data); } dataItems.release(); } }); } @Override public void onConnectionSuspended(int e) { } @Override public void onDataChanged(DataEventBuffer dataEventBuffer) { i++; for (DataEvent dataEvent : dataEventBuffer) { if (dataEvent.getType() != DataEvent.TYPE_CHANGED) { continue; } DataItem dataItem = dataEvent.getDataItem(); if (!dataItem.getUri().getPath().equals( MyWatchFace.PATH_WITH_WEATHER)) { continue; } DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItem); String data = dataMapItem.getDataMap().getString("key"); getData(data); } } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } } }
38.233743
129
0.601195
842da836066ee3313b2045f565688706ad0373f7
342
package com.click.house.mapper; import com.click.house.entity.UserInfo; import org.apache.ibatis.annotations.Param; import java.util.List; public interface UserInfoMapper { // 写入数据 void saveData (UserInfo userInfo) ; // ID 查询 UserInfo selectById (@Param("id") Integer id) ; // 查询全部 List<UserInfo> selectList () ; }
21.375
51
0.69883
913335947c2fb67a003ac11fdf312106acda0b20
980
package com.eduardocode.jasonviewerapi.model; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * <h1>Usuario</h1> * Modelo que representa a los usuarios admministradores de la api * * <p> * Observar que este metodo no posee una relacion explicita con el modelo role. * Esto se debe a que esa relacion ya la define spring security * * @author Eduardo Rasgado Ruiz * @version 1.0 * @since april/2019 */ @Data @Entity @Table(name = "usuario") public class Usuario { @Id @GeneratedValue( generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid2") private String id; private String username; private String nombre; private String apellido; private String password; // representa el enable en spring security private boolean status; }
25.789474
83
0.728571
1c529f57441b0e8e46ed66e7e2548a63d179c6d8
4,365
package io.github.syst3ms.skriptparser.types; import io.github.syst3ms.skriptparser.registration.SkriptRegistration; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; /** * Manages the registration and usage of {@link Type} */ @SuppressWarnings("unchecked") public class TypeManager { public static final String NULL_REPRESENTATION = "<none>"; public static final String EMPTY_REPRESENTATION = "<empty>"; private static Map<String, Type<?>> nameToType = new HashMap<>(); private static Map<Class<?>, Type<?>> classToType = new LinkedHashMap<>(); // Ordering is important for stuff like number types public static Map<Class<?>, Type<?>> getClassToTypeMap() { return classToType; } /** * Gets a {@link Type} by its exact name (the baseName parameter used in {@link Type#Type(Class, String, String)}) * @param name the name to get the Type from * @return the corresponding Type, or {@literal null} if nothing matched */ @Nullable public static Type<?> getByExactName(String name) { return nameToType.get(name); } /** * Gets a {@link Type} using its plural forms, which means this matches any alternate and/or plural form. * @param name the name to get a Type from * @return the matching Type, or {@literal null} if nothing matched */ @Nullable public static Type<?> getByName(String name) { for (Type<?> t : nameToType.values()) { String[] forms = t.getPluralForms(); if (name.equalsIgnoreCase(forms[0]) || name.equalsIgnoreCase(forms[1])) { return t; } } return null; } /** * Gets a {@link Type} from its associated {@link Class}. * @param c the Class to get the Type from * @param <T> the underlying type of the Class and the returned Type * @return the associated Type, or {@literal null} */ @Nullable public static <T> Type<T> getByClassExact(Class<T> c) { if (c.isArray()) c = (Class<T>) c.getComponentType(); return (Type<T>) classToType.get(c); } @Nullable public static <T> Type<? super T> getByClass(Class<T> c) { Type<? super T> type = getByClassExact(c); Class<? super T> superclass = c; while (superclass != null && type == null) { type = getByClassExact(superclass); superclass = superclass.getSuperclass(); } return type; } public static String toString(Object... objects) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < objects.length; i++) { if (i > 0) { sb.append(i == objects.length - 1 ? " and " : ", "); } Object o = objects[i]; if (o == null) { sb.append(NULL_REPRESENTATION); continue; } Type<?> type = getByClass(o.getClass()); if (type == null) { sb.append(Objects.toString(o)); } else { sb.append(type.getToStringFunction().apply(o)); } } return sb.length() == 0 ? EMPTY_REPRESENTATION : sb.toString(); } /** * Gets a {@link PatternType} from a name. This determines the number (single/plural) from the input. * If the input happens to be the base name of a type, then a single PatternType (as in "not plural") of the corresponding type is returned. * @param name the name input * @return a corresponding PatternType, or {@literal null} if nothing matched */ @Nullable public static PatternType<?> getPatternType(String name) { for (Type<?> t : nameToType.values()) { String[] forms = t.getPluralForms(); if (name.equalsIgnoreCase(forms[0])) { return new PatternType<>(t, true); } else if (name.equalsIgnoreCase(forms[1])) { return new PatternType<>(t, false); } } return null; } public static void register(SkriptRegistration reg) { for (Type<?> type : reg.getTypes()) { nameToType.put(type.getBaseName(), type); classToType.put(type.getTypeClass(), type); } } }
36.07438
144
0.591065
a0ebdeb6fbb3f8406a13a623b628aae1936df9b1
8,345
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Artifactory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Artifactory. If not, see <http://www.gnu.org/licenses/>. */ package org.artifactory.webapp.wicket.page.security.profile; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.IAjaxCallDecorator; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.PasswordTextField; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.time.Duration; import org.artifactory.api.security.AuthorizationService; import org.artifactory.api.security.SecurityService; import org.artifactory.api.security.UserGroupService; import org.artifactory.common.ConstantValues; import org.artifactory.common.wicket.ajax.NoAjaxIndicatorDecorator; import org.artifactory.common.wicket.behavior.CssClass; import org.artifactory.common.wicket.component.help.HelpBubble; import org.artifactory.common.wicket.component.panel.passwordstrength.PasswordStrengthComponentPanel; import org.artifactory.common.wicket.component.panel.titled.TitledPanel; import org.artifactory.security.MutableUserInfo; import org.artifactory.security.crypto.CryptoHelper; import org.artifactory.webapp.wicket.util.validation.EmailAddressValidator; import org.artifactory.webapp.wicket.util.validation.PasswordStrengthValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import javax.crypto.SecretKey; import java.security.KeyPair; /** * @author Yoav Landman */ public class ProfilePanel extends TitledPanel { private static final Logger log = LoggerFactory.getLogger(ProfilePanel.class); private static final String HIDDEN_PASSWORD = "************"; @SpringBean private UserGroupService userGroupService; @SpringBean private AuthorizationService authService; @SpringBean private SecurityService securityService; private Label encryptedPasswordLabel; private Form form; public ProfilePanel(String id, Form form, ProfileModel profile) { super(id); this.form = form; setOutputMarkupId(true); setDefaultModel(new CompoundPropertyModel<>(profile)); add(new CssClass("display:block")); WebMarkupContainer encryptedPasswordContainer = new WebMarkupContainer("encryptedPasswordContainer"); add(encryptedPasswordContainer); encryptedPasswordLabel = new Label("encryptedPassword", HIDDEN_PASSWORD); encryptedPasswordLabel.setVisible(securityService.isPasswordEncryptionEnabled()); encryptedPasswordContainer.add(encryptedPasswordLabel); encryptedPasswordContainer.add( new HelpBubble("encryptedPassword.help", new ResourceModel("encryptedPassword.help"))); encryptedPasswordContainer.setVisible(!ConstantValues.uiHideEncryptedPassword.getBoolean()); // Profile update fields are only displayed for users with permissions to do so final WebMarkupContainer updateFieldsContainer = new WebMarkupContainer("updateFieldsContainer"); updateFieldsContainer.setVisible(authService.isUpdatableProfile()); add(updateFieldsContainer); addPasswordFields(updateFieldsContainer); // Email TextField<String> emailTf = new TextField<>("email"); emailTf.setEnabled(false); emailTf.add(EmailAddressValidator.getInstance()); updateFieldsContainer.add(emailTf); } private void addPasswordFields(WebMarkupContainer updateFieldsContainer) { WebMarkupContainer passwordFieldsContainer = new WebMarkupContainer("passwordFieldsContainer"); final TextField<String> newPassword; final WebMarkupContainer strength; final TextField<String> retypedPassword; if (authService.isDisableInternalPassword()) { newPassword = new TextField<>("newPassword"); strength = new WebMarkupContainer("strengthPanel"); retypedPassword = new TextField<>("retypedPassword"); passwordFieldsContainer.setVisible(false); } else { // New password newPassword = new PasswordTextField("newPassword"); newPassword.setRequired(false); newPassword.setEnabled(false); newPassword.add(PasswordStrengthValidator.getInstance()); strength = new PasswordStrengthComponentPanel("strengthPanel", new PropertyModel(newPassword, "modelObject")); strength.setOutputMarkupId(true); newPassword.add(new AjaxFormComponentUpdatingBehavior("onkeyup") { @Override protected IAjaxCallDecorator getAjaxCallDecorator() { return new NoAjaxIndicatorDecorator(); } @Override protected void onError(AjaxRequestTarget target, RuntimeException e) { super.onError(target, e); String password = getFormComponent().getRawInput(); newPassword.setDefaultModelObject(password); target.add(strength); } @Override protected void onUpdate(AjaxRequestTarget target) { target.add(strength); } }.setThrottleDelay(Duration.seconds(0.5))); retypedPassword = new PasswordTextField("retypedPassword"); retypedPassword.setRequired(false); retypedPassword.setEnabled(false); form.add(new EqualPasswordInputValidator(newPassword, retypedPassword)); } passwordFieldsContainer.add(newPassword); passwordFieldsContainer.add(strength); passwordFieldsContainer.add(retypedPassword); updateFieldsContainer.add(passwordFieldsContainer); } private ProfileModel getUserProfile() { return (ProfileModel) getDefaultModelObject(); } @Override public String getTitle() { return ""; } public void displayEncryptedPassword(MutableUserInfo mutableUser) { // generate a new KeyPair and update the user profile regenerateKeyPair(mutableUser); // display the encrypted password if (securityService.isPasswordEncryptionEnabled()) { String currentPassword = getUserProfile().getCurrentPassword(); SecretKey secretKey = CryptoHelper.generatePbeKeyFromKeyPair(mutableUser.getPrivateKey(), mutableUser.getPublicKey(), false); String encryptedPassword = CryptoHelper.encryptSymmetric(currentPassword, secretKey, false); encryptedPasswordLabel.setDefaultModelObject(encryptedPassword); } } private void regenerateKeyPair(MutableUserInfo mutableUser) { if (!StringUtils.hasText(mutableUser.getPrivateKey())) { log.debug("Generating new KeyPair for {}", mutableUser.getUsername()); KeyPair keyPair = CryptoHelper.generateKeyPair(); mutableUser.setPrivateKey(CryptoHelper.convertToString(keyPair.getPrivate())); mutableUser.setPublicKey(CryptoHelper.convertToString(keyPair.getPublic())); userGroupService.updateUser(mutableUser, false); } } }
43.238342
109
0.722109
abe707e8c3d825d8d5be663ab83ae7a3b4418960
6,695
package com.amyliascarlet.jsontest.bvt.parser.bug; import com.amyliascarlet.lib.json.JSON; import com.amyliascarlet.lib.json.TypeReference; import junit.framework.TestCase; import java.util.List; public class Bug_for_lingzhi extends TestCase { public void test_0() throws Exception { String str = "[\n" + "{\n" + "\"isDefault\":false,\n" + "\"msgId\": \"expireTransitionChange\",\n" + "\"msgText\": \"xxx\",\n" + "\"extMsgId\": \"promptInformation\",\n" + "\"extMsgText\": \"xxx\",\n" + "\"instChangeType\": 1,\n" + "\"rule\": {\n" + "\"aliUid\":[39314],\n" + "\"regionNo\":[]\n" + "}\n" + "},\n" + "{\n" + "\"isDefault\":true,\n" + "\"msgId\": \"expireTransitionUnChange\",\n" + "\"msgText\": \"xxx\",\n" + "\"extMsgId\": \"Prompt information\",\n" + "\"extMsgText\": \"xxx\",\n" + "\"instChangeType\": 0,\n" + "\"rule\": {\n" + "\"aliUid\":[],\n" + "\"regionNo\":[]\n" + "}\n" + "},\n" + "{\n" + "\"isDefault\":false,\n" + "\"msgId\": \"expireTransitionChange\",\n" + "\"msgText\": \"xxx\",\n" + "\"extMsgId\": \"Prompt information\",\n" + "\"extMsgText\": \"你好B\",\n" + "\"instChangeType\": 1,\n" + "\"rule\": {\n" + "\"aliUid\":[111],\n" + "\"regionNo\":[]\n" + "}\n" + "}\n" + "]"; // String pstr = JSON.toJSONString(JSON.parse(str), SerializerFeature.PrettyFormat); // System.out.println(pstr); JSON.parseObject(str, new TypeReference<List<EcsTransitionDisplayedMsgConfig>>(){}); } public static class EcsTransitionDisplayedMsgConfig { /** * 是否默认文案 */ private Boolean isDefault; /** * 展示的文案Id */ private String msgId; /** * 展示的文案信息 */ private String msgText; /** * 扩展文案Id */ private String extMsgId; /** * 扩展文案信息 */ private String extMsgText; private Integer instChangeType; /** * 文案对应的规则 */ private EcsTransitionConfigRule rule; public String getMsgText() { return msgText; } public void setMsgText(String msgText) { this.msgText = msgText; } public String getMsgId() { return msgId; } public void setMsgId(String msgId) { this.msgId = msgId; } public EcsTransitionConfigRule getRule() { return rule; } public void setRule(EcsTransitionConfigRule rule) { this.rule = rule; } public Integer getInstChangeType() { return instChangeType; } public void setInstChangeType(Integer instChangeType) { this.instChangeType = instChangeType; } public Boolean getIsDefault() { return this.isDefault; } public void setIsDefault(Boolean isDefault) { this.isDefault = isDefault; } public String getExtMsgId() { return extMsgId; } public void setExtMsgId(String extMsgId) { this.extMsgId = extMsgId; } public String getExtMsgText() { return extMsgText; } public void setExtMsgText(String extMsgText) { this.extMsgText = extMsgText; } } public static class EcsTransitionConfigRule { /** 0 过保迁移, 1 非过保迁移 **/ private List<Integer> transType; /** 比如:cn-qingdao-cm5-a01 **/ private List<String> regionNo; private List<Long> aliUid; private List<String> bid; /** ecs,disk **/ private List<String> resourceType; private List<Long> zoneId; private List<Long> targetZoneId; private List<Integer> networkTransType; /** instance type 实例规格 **/ private List<String> instanceType; /** 磁盘类型 ioX **/ private List<String> ioX; private List<String> instanceId; public List<Integer> getTransType() { return transType; } public void setTransType(List<Integer> transType) { this.transType = transType; } public List<String> getRegionNo() { return regionNo; } public void setRegionNo(List<String> regionNo) { this.regionNo = regionNo; } public List<Long> getAliUid() { return aliUid; } public void setAliUid(List<Long> aliUid) { this.aliUid = aliUid; } public List<String> getBid() { return bid; } public void setBid(List<String> bid) { this.bid = bid; } public List<String> getResourceType() { return resourceType; } public void setResourceType(List<String> resourceType) { this.resourceType = resourceType; } public List<Long> getZoneId() { return zoneId; } public void setZoneId(List<Long> zoneId) { this.zoneId = zoneId; } public List<Long> getTargetZoneId() { return targetZoneId; } public void setTargetZoneId(List<Long> targetZoneId) { this.targetZoneId = targetZoneId; } public List<Integer> getNetworkTransType() { return networkTransType; } public void setNetworkTransType(List<Integer> networkTransType) { this.networkTransType = networkTransType; } public List<String> getInstanceType() { return instanceType; } public void setInstanceType(List<String> instanceType) { this.instanceType = instanceType; } public List<String> getIoX() { return ioX; } public void setIoX(List<String> ioX) { this.ioX = ioX; } public List<String> getInstanceId() { return instanceId; } public void setInstanceId(List<String> instanceId) { this.instanceId = instanceId; } } }
24.888476
92
0.490366
651fc4650e8c57e6bdd37ed9425c969531aa6023
5,233
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2020 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.core.xml; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.junit.Test; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleXMLException; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; public class XMLHandlerTest { private static final String DUMMY = "dummy"; @Test public void getTagValueWithNullNode() { assertNull( XMLHandler.getTagValue( null, "text" ) ); } /** * Default behavior, an empty XML tag in the "Filter rows" step meta will be considered {@code null}. * This will prevent filtering rows with empty values. */ @Test public void getTagValueEmptyTagYieldsNullValue() { System.setProperty( Const.KETTLE_XML_EMPTY_TAG_YIELDS_EMPTY_VALUE, "N" ); assertNull( XMLHandler.getTagValue( getNode(), "text" ) ); } /** * An empty XML tag in the "Filter rows" step meta will be considered an empty string. * This will allow filtering rows with empty values. */ @Test public void getTagValueEmptyTagYieldsEmptyValue() { System.setProperty( Const.KETTLE_XML_EMPTY_TAG_YIELDS_EMPTY_VALUE, "Y" ); assertEquals( "", XMLHandler.getTagValue( getNode(), "text" ) ); } private Node getNode() { Element first = mock( Element.class ); doReturn( null ).when( first ).getNodeValue(); Node child = mock( Node.class ); doReturn( "text" ).when( child ).getNodeName(); doReturn( first ).when( child ).getFirstChild(); doReturn( "" ).when( child ).getTextContent(); NodeList children = mock( NodeList.class ); doReturn( 1 ).when( children ).getLength(); doReturn( child ).when( children ).item( 0 ); Node node = mock( Node.class ); doReturn( children ).when( node ).getChildNodes(); return node; } @Test public void checkFile_FileDoesNotExist() throws Exception { FileObject fileObjectMock = mock( FileObject.class ); doReturn( false ).when( fileObjectMock ).exists(); doReturn( false ).when( fileObjectMock ).isFile(); assertFalse( XMLHandler.checkFile( fileObjectMock ) ); } @Test public void checkFile_IsFile() throws Exception { FileObject fileObjectMock = mock( FileObject.class ); doReturn( true ).when( fileObjectMock ).exists(); doReturn( true ).when( fileObjectMock ).isFile(); assertTrue( XMLHandler.checkFile( fileObjectMock ) ); } @Test public void checkFile_IsNotFile() throws Exception { FileObject fileObjectMock = mock( FileObject.class ); doReturn( true ).when( fileObjectMock ).exists(); doReturn( false ).when( fileObjectMock ).isFile(); assertFalse( XMLHandler.checkFile( fileObjectMock ) ); } @Test( expected = KettleXMLException.class ) public void checkFile_Exception() throws Exception { FileObject fileObjectMock = mock( FileObject.class ); doReturn( true ).when( fileObjectMock ).exists(); doThrow( new FileSystemException( DUMMY ) ).when( fileObjectMock ).isFile(); XMLHandler.checkFile( fileObjectMock ); } @Test public void loadFile_NoFile() throws Exception { FileObject fileObjectMock = mock( FileObject.class ); doReturn( true ).when( fileObjectMock ).exists(); doReturn( false ).when( fileObjectMock ).isFile(); try { XMLHandler.loadXMLFile( fileObjectMock ); } catch ( KettleXMLException e ) { System.out.println( e.getMessage() ); assertTrue( e.getMessage().contains( "does not exists" ) ); } } @Test public void loadFile_ExceptionCheckingFile() throws Exception { FileObject fileObjectMock = mock( FileObject.class ); doReturn( true ).when( fileObjectMock ).exists(); doThrow( new FileSystemException( DUMMY ) ).when( fileObjectMock ).isFile(); try { XMLHandler.loadXMLFile( fileObjectMock ); } catch ( KettleXMLException e ) { System.out.println( e.getMessage() ); assertTrue( e.getMessage().contains( "Unable to check if file" ) ); } } }
33.980519
103
0.674374
1ecf515c72728c3630bf9419329b4126aeebb07c
2,624
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qlangtech.tis.plugin.datax; import com.alibaba.fastjson.JSONObject; import com.qlangtech.tis.runtime.module.misc.VisualType; import com.qlangtech.tis.solrdao.ISchemaField; import com.qlangtech.tis.solrdao.pojo.BasicSchemaField; /** * @author: 百岁([email protected]) * @create: 2021-06-11 16:38 **/ public class ESField extends BasicSchemaField { private VisualType type; public VisualType getType() { return type; } public void setType(VisualType type) { this.type = type; } @Override public String getTisFieldTypeName() { return type.getType(); } @Override public boolean isDynamic() { return false; } @Override public void serialVisualType2Json(JSONObject f) { if (this.getType() == null) { throw new IllegalStateException("field:" + this.getName() + " 's fieldType is can not be null"); } VisualType esType = this.getType(); String type = esType.type; EsTokenizerType tokenizerType = EsTokenizerType.parse(this.getTokenizerType()); if (tokenizerType == null) { // 非分词字段 if (esType.isSplit()) { setStringType(f, type, EsTokenizerType.getTokenizerType().name()); } else { f.put("split", false); VisualType vtype = EsTokenizerType.visualTypeMap.get(type); if (vtype != null) { f.put(ISchemaField.KEY_FIELD_TYPE, vtype.getType()); return; } f.put(ISchemaField.KEY_FIELD_TYPE, type); } } else { // 分词字段 setStringType(f, tokenizerType.getKey(), EsTokenizerType.getTokenizerType().name()); } } }
32.8
108
0.636052
93cf7a764b85fedb0ccd7eda9654fdb47de2c0fd
1,287
package sepm.ss17.e1526280.service; import sepm.ss17.e1526280.dto.Box; import sepm.ss17.e1526280.dto.Range; import sepm.ss17.e1526280.dto.StatisticRow; import java.util.Date; import java.util.List; import java.util.concurrent.CompletableFuture; /** * This interface does Provide the basic functionality for the statistical methods * * @author Raphael Ludwig * @version 16.03.17 */ public interface StatisticalService { /** * Queries for the list of Boxes all statistic rows form the start to the end date * @param boxes list of boxes which should be queried * @param start start date * @param end end date * @return a future with the list of the results */ CompletableFuture<List<StatisticRow>> query(List<Box> boxes, Date start, Date end); /** * Queries for the list of Boxes for the statistic * @param boxes list of boxes which should be queried * @return a future with the list of the results */ CompletableFuture<List<StatisticRow>> query(List<Box> boxes); /** * @return Gets the worst row from all the rows */ Box getWorst(List<StatisticRow> rows, Range range); /** * @return Gets the best row from all the rows */ Box getBest(List<StatisticRow> rows, Range range); }
28.6
87
0.693862
d3cd47d09509c0527cc646f662e9e7d3fa5de01e
3,000
package org.jadice.font.sfntly.table.opentype; import org.jadice.font.sfntly.data.ReadableFontData; import org.jadice.font.sfntly.data.WritableFontData; import org.jadice.font.sfntly.table.opentype.classdef.InnerArrayFmt1; import org.jadice.font.sfntly.table.opentype.component.RangeRecordTable; import org.jadice.font.sfntly.table.opentype.component.RecordsTable; public class ClassDefTable extends SubstSubtable { public final RecordsTable<?> array; private final boolean dataIsCanonical; // ////////////// // Constructors public ClassDefTable(ReadableFontData data, int base, boolean dataIsCanonical) { super(data, base, dataIsCanonical); this.dataIsCanonical = dataIsCanonical; switch (format) { case 1: array = new InnerArrayFmt1(data, headerSize(), dataIsCanonical); break; case 2: array = new RangeRecordTable(data, headerSize(), dataIsCanonical); break; default: throw new IllegalArgumentException("class def format " + format + " unexpected"); } } // //////////////////////////////////////// // Utility methods specific to this class public InnerArrayFmt1 fmt1Table() { switch (format) { case 1: return (InnerArrayFmt1) array; default: throw new IllegalArgumentException("unexpected format table requested: " + format); } } public RangeRecordTable fmt2Table() { switch (format) { case 2: return (RangeRecordTable) array; default: throw new IllegalArgumentException("unexpected format table requested: " + format); } } public static class Builder extends SubstSubtable.Builder<ClassDefTable> { private final RecordsTable.Builder<?, ?> arrayBuilder; protected Builder(ReadableFontData data, boolean dataIsCanonical) { super(data, dataIsCanonical); switch (format) { case 1: arrayBuilder = new InnerArrayFmt1.Builder(data, headerSize(), dataIsCanonical); break; case 2: arrayBuilder = new RangeRecordTable.Builder(data, headerSize(), dataIsCanonical); break; default: throw new IllegalArgumentException("class def format " + format + " unexpected"); } } protected Builder(ClassDefTable table) { this(table.readFontData(), table.dataIsCanonical); } @Override public int subDataSizeToSerialize() { return super.subDataSizeToSerialize() + arrayBuilder.subDataSizeToSerialize(); } @Override public int subSerialize(WritableFontData newData) { int newOffset = super.subSerialize(newData); return arrayBuilder.subSerialize(newData.slice(newOffset)); } // /////////////////// // Overriden methods @Override public ClassDefTable subBuildTable(ReadableFontData data) { return new ClassDefTable(data, 0, false); } @Override public void subDataSet() { super.subDataSet(); arrayBuilder.subDataSet(); } } }
30
91
0.669333
2fe93448e31a4992fa8348fd62327d162aca574a
27,233
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2019-Present Datadog, Inc. * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.datadog.api.v1.client.model; import com.datadog.api.v1.client.JSON; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.core.GenericType; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") @JsonDeserialize( using = NotebookCellCreateRequestAttributes.NotebookCellCreateRequestAttributesDeserializer.class) @JsonSerialize( using = NotebookCellCreateRequestAttributes.NotebookCellCreateRequestAttributesSerializer.class) public class NotebookCellCreateRequestAttributes extends AbstractOpenApiSchema { private static final Logger log = Logger.getLogger(NotebookCellCreateRequestAttributes.class.getName()); @JsonIgnore public boolean unparsed = false; public static class NotebookCellCreateRequestAttributesSerializer extends StdSerializer<NotebookCellCreateRequestAttributes> { public NotebookCellCreateRequestAttributesSerializer( Class<NotebookCellCreateRequestAttributes> t) { super(t); } public NotebookCellCreateRequestAttributesSerializer() { this(null); } @Override public void serialize( NotebookCellCreateRequestAttributes value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeObject(value.getActualInstance()); } } public static class NotebookCellCreateRequestAttributesDeserializer extends StdDeserializer<NotebookCellCreateRequestAttributes> { public NotebookCellCreateRequestAttributesDeserializer() { this(NotebookCellCreateRequestAttributes.class); } public NotebookCellCreateRequestAttributesDeserializer(Class<?> vc) { super(vc); } @Override public NotebookCellCreateRequestAttributes deserialize( JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode tree = jp.readValueAsTree(); Object deserialized = null; Object tmp = null; boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); int match = 0; JsonToken token = tree.traverse(jp.getCodec()).nextToken(); // deserialize NotebookMarkdownCellAttributes try { boolean attemptParsing = true; // ensure that we respect type coercion as set on the client ObjectMapper if (NotebookMarkdownCellAttributes.class.equals(Integer.class) || NotebookMarkdownCellAttributes.class.equals(Long.class) || NotebookMarkdownCellAttributes.class.equals(Float.class) || NotebookMarkdownCellAttributes.class.equals(Double.class) || NotebookMarkdownCellAttributes.class.equals(Boolean.class) || NotebookMarkdownCellAttributes.class.equals(String.class)) { attemptParsing = typeCoercion; if (!attemptParsing) { attemptParsing |= ((NotebookMarkdownCellAttributes.class.equals(Integer.class) || NotebookMarkdownCellAttributes.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); attemptParsing |= ((NotebookMarkdownCellAttributes.class.equals(Float.class) || NotebookMarkdownCellAttributes.class.equals(Double.class)) && (token == JsonToken.VALUE_NUMBER_FLOAT || token == JsonToken.VALUE_NUMBER_INT)); attemptParsing |= (NotebookMarkdownCellAttributes.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); attemptParsing |= (NotebookMarkdownCellAttributes.class.equals(String.class) && token == JsonToken.VALUE_STRING); } } if (attemptParsing) { tmp = tree.traverse(jp.getCodec()).readValueAs(NotebookMarkdownCellAttributes.class); // TODO: there is no validation against JSON schema constraints // (min, max, enum, pattern...), this does not perform a strict JSON // validation, which means the 'match' count may be higher than it should be. if (!((NotebookMarkdownCellAttributes) tmp).unparsed) { deserialized = tmp; match++; } log.log(Level.FINER, "Input data matches schema 'NotebookMarkdownCellAttributes'"); } } catch (Exception e) { // deserialization failed, continue log.log( Level.FINER, "Input data does not match schema 'NotebookMarkdownCellAttributes'", e); } // deserialize NotebookTimeseriesCellAttributes try { boolean attemptParsing = true; // ensure that we respect type coercion as set on the client ObjectMapper if (NotebookTimeseriesCellAttributes.class.equals(Integer.class) || NotebookTimeseriesCellAttributes.class.equals(Long.class) || NotebookTimeseriesCellAttributes.class.equals(Float.class) || NotebookTimeseriesCellAttributes.class.equals(Double.class) || NotebookTimeseriesCellAttributes.class.equals(Boolean.class) || NotebookTimeseriesCellAttributes.class.equals(String.class)) { attemptParsing = typeCoercion; if (!attemptParsing) { attemptParsing |= ((NotebookTimeseriesCellAttributes.class.equals(Integer.class) || NotebookTimeseriesCellAttributes.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); attemptParsing |= ((NotebookTimeseriesCellAttributes.class.equals(Float.class) || NotebookTimeseriesCellAttributes.class.equals(Double.class)) && (token == JsonToken.VALUE_NUMBER_FLOAT || token == JsonToken.VALUE_NUMBER_INT)); attemptParsing |= (NotebookTimeseriesCellAttributes.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); attemptParsing |= (NotebookTimeseriesCellAttributes.class.equals(String.class) && token == JsonToken.VALUE_STRING); } } if (attemptParsing) { tmp = tree.traverse(jp.getCodec()).readValueAs(NotebookTimeseriesCellAttributes.class); // TODO: there is no validation against JSON schema constraints // (min, max, enum, pattern...), this does not perform a strict JSON // validation, which means the 'match' count may be higher than it should be. if (!((NotebookTimeseriesCellAttributes) tmp).unparsed) { deserialized = tmp; match++; } log.log(Level.FINER, "Input data matches schema 'NotebookTimeseriesCellAttributes'"); } } catch (Exception e) { // deserialization failed, continue log.log( Level.FINER, "Input data does not match schema 'NotebookTimeseriesCellAttributes'", e); } // deserialize NotebookToplistCellAttributes try { boolean attemptParsing = true; // ensure that we respect type coercion as set on the client ObjectMapper if (NotebookToplistCellAttributes.class.equals(Integer.class) || NotebookToplistCellAttributes.class.equals(Long.class) || NotebookToplistCellAttributes.class.equals(Float.class) || NotebookToplistCellAttributes.class.equals(Double.class) || NotebookToplistCellAttributes.class.equals(Boolean.class) || NotebookToplistCellAttributes.class.equals(String.class)) { attemptParsing = typeCoercion; if (!attemptParsing) { attemptParsing |= ((NotebookToplistCellAttributes.class.equals(Integer.class) || NotebookToplistCellAttributes.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); attemptParsing |= ((NotebookToplistCellAttributes.class.equals(Float.class) || NotebookToplistCellAttributes.class.equals(Double.class)) && (token == JsonToken.VALUE_NUMBER_FLOAT || token == JsonToken.VALUE_NUMBER_INT)); attemptParsing |= (NotebookToplistCellAttributes.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); attemptParsing |= (NotebookToplistCellAttributes.class.equals(String.class) && token == JsonToken.VALUE_STRING); } } if (attemptParsing) { tmp = tree.traverse(jp.getCodec()).readValueAs(NotebookToplistCellAttributes.class); // TODO: there is no validation against JSON schema constraints // (min, max, enum, pattern...), this does not perform a strict JSON // validation, which means the 'match' count may be higher than it should be. if (!((NotebookToplistCellAttributes) tmp).unparsed) { deserialized = tmp; match++; } log.log(Level.FINER, "Input data matches schema 'NotebookToplistCellAttributes'"); } } catch (Exception e) { // deserialization failed, continue log.log(Level.FINER, "Input data does not match schema 'NotebookToplistCellAttributes'", e); } // deserialize NotebookHeatMapCellAttributes try { boolean attemptParsing = true; // ensure that we respect type coercion as set on the client ObjectMapper if (NotebookHeatMapCellAttributes.class.equals(Integer.class) || NotebookHeatMapCellAttributes.class.equals(Long.class) || NotebookHeatMapCellAttributes.class.equals(Float.class) || NotebookHeatMapCellAttributes.class.equals(Double.class) || NotebookHeatMapCellAttributes.class.equals(Boolean.class) || NotebookHeatMapCellAttributes.class.equals(String.class)) { attemptParsing = typeCoercion; if (!attemptParsing) { attemptParsing |= ((NotebookHeatMapCellAttributes.class.equals(Integer.class) || NotebookHeatMapCellAttributes.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); attemptParsing |= ((NotebookHeatMapCellAttributes.class.equals(Float.class) || NotebookHeatMapCellAttributes.class.equals(Double.class)) && (token == JsonToken.VALUE_NUMBER_FLOAT || token == JsonToken.VALUE_NUMBER_INT)); attemptParsing |= (NotebookHeatMapCellAttributes.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); attemptParsing |= (NotebookHeatMapCellAttributes.class.equals(String.class) && token == JsonToken.VALUE_STRING); } } if (attemptParsing) { tmp = tree.traverse(jp.getCodec()).readValueAs(NotebookHeatMapCellAttributes.class); // TODO: there is no validation against JSON schema constraints // (min, max, enum, pattern...), this does not perform a strict JSON // validation, which means the 'match' count may be higher than it should be. if (!((NotebookHeatMapCellAttributes) tmp).unparsed) { deserialized = tmp; match++; } log.log(Level.FINER, "Input data matches schema 'NotebookHeatMapCellAttributes'"); } } catch (Exception e) { // deserialization failed, continue log.log(Level.FINER, "Input data does not match schema 'NotebookHeatMapCellAttributes'", e); } // deserialize NotebookDistributionCellAttributes try { boolean attemptParsing = true; // ensure that we respect type coercion as set on the client ObjectMapper if (NotebookDistributionCellAttributes.class.equals(Integer.class) || NotebookDistributionCellAttributes.class.equals(Long.class) || NotebookDistributionCellAttributes.class.equals(Float.class) || NotebookDistributionCellAttributes.class.equals(Double.class) || NotebookDistributionCellAttributes.class.equals(Boolean.class) || NotebookDistributionCellAttributes.class.equals(String.class)) { attemptParsing = typeCoercion; if (!attemptParsing) { attemptParsing |= ((NotebookDistributionCellAttributes.class.equals(Integer.class) || NotebookDistributionCellAttributes.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); attemptParsing |= ((NotebookDistributionCellAttributes.class.equals(Float.class) || NotebookDistributionCellAttributes.class.equals(Double.class)) && (token == JsonToken.VALUE_NUMBER_FLOAT || token == JsonToken.VALUE_NUMBER_INT)); attemptParsing |= (NotebookDistributionCellAttributes.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); attemptParsing |= (NotebookDistributionCellAttributes.class.equals(String.class) && token == JsonToken.VALUE_STRING); } } if (attemptParsing) { tmp = tree.traverse(jp.getCodec()).readValueAs(NotebookDistributionCellAttributes.class); // TODO: there is no validation against JSON schema constraints // (min, max, enum, pattern...), this does not perform a strict JSON // validation, which means the 'match' count may be higher than it should be. if (!((NotebookDistributionCellAttributes) tmp).unparsed) { deserialized = tmp; match++; } log.log(Level.FINER, "Input data matches schema 'NotebookDistributionCellAttributes'"); } } catch (Exception e) { // deserialization failed, continue log.log( Level.FINER, "Input data does not match schema 'NotebookDistributionCellAttributes'", e); } // deserialize NotebookLogStreamCellAttributes try { boolean attemptParsing = true; // ensure that we respect type coercion as set on the client ObjectMapper if (NotebookLogStreamCellAttributes.class.equals(Integer.class) || NotebookLogStreamCellAttributes.class.equals(Long.class) || NotebookLogStreamCellAttributes.class.equals(Float.class) || NotebookLogStreamCellAttributes.class.equals(Double.class) || NotebookLogStreamCellAttributes.class.equals(Boolean.class) || NotebookLogStreamCellAttributes.class.equals(String.class)) { attemptParsing = typeCoercion; if (!attemptParsing) { attemptParsing |= ((NotebookLogStreamCellAttributes.class.equals(Integer.class) || NotebookLogStreamCellAttributes.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); attemptParsing |= ((NotebookLogStreamCellAttributes.class.equals(Float.class) || NotebookLogStreamCellAttributes.class.equals(Double.class)) && (token == JsonToken.VALUE_NUMBER_FLOAT || token == JsonToken.VALUE_NUMBER_INT)); attemptParsing |= (NotebookLogStreamCellAttributes.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); attemptParsing |= (NotebookLogStreamCellAttributes.class.equals(String.class) && token == JsonToken.VALUE_STRING); } } if (attemptParsing) { tmp = tree.traverse(jp.getCodec()).readValueAs(NotebookLogStreamCellAttributes.class); // TODO: there is no validation against JSON schema constraints // (min, max, enum, pattern...), this does not perform a strict JSON // validation, which means the 'match' count may be higher than it should be. if (!((NotebookLogStreamCellAttributes) tmp).unparsed) { deserialized = tmp; match++; } log.log(Level.FINER, "Input data matches schema 'NotebookLogStreamCellAttributes'"); } } catch (Exception e) { // deserialization failed, continue log.log( Level.FINER, "Input data does not match schema 'NotebookLogStreamCellAttributes'", e); } NotebookCellCreateRequestAttributes ret = new NotebookCellCreateRequestAttributes(); if (match == 1) { ret.setActualInstance(deserialized); } else { Map<String, Object> res = new ObjectMapper() .readValue( tree.traverse(jp.getCodec()).readValueAsTree().toString(), new TypeReference<Map<String, Object>>() {}); ret.setActualInstance(new UnparsedObject(res)); } return ret; } /** Handle deserialization of the 'null' value. */ @Override public NotebookCellCreateRequestAttributes getNullValue(DeserializationContext ctxt) throws JsonMappingException { throw new JsonMappingException( ctxt.getParser(), "NotebookCellCreateRequestAttributes cannot be null"); } } // store a list of schema names defined in oneOf public static final Map<String, GenericType> schemas = new HashMap<String, GenericType>(); public NotebookCellCreateRequestAttributes() { super("oneOf", Boolean.FALSE); } public NotebookCellCreateRequestAttributes(NotebookDistributionCellAttributes o) { super("oneOf", Boolean.FALSE); setActualInstance(o); } public NotebookCellCreateRequestAttributes(NotebookHeatMapCellAttributes o) { super("oneOf", Boolean.FALSE); setActualInstance(o); } public NotebookCellCreateRequestAttributes(NotebookLogStreamCellAttributes o) { super("oneOf", Boolean.FALSE); setActualInstance(o); } public NotebookCellCreateRequestAttributes(NotebookMarkdownCellAttributes o) { super("oneOf", Boolean.FALSE); setActualInstance(o); } public NotebookCellCreateRequestAttributes(NotebookTimeseriesCellAttributes o) { super("oneOf", Boolean.FALSE); setActualInstance(o); } public NotebookCellCreateRequestAttributes(NotebookToplistCellAttributes o) { super("oneOf", Boolean.FALSE); setActualInstance(o); } static { schemas.put( "NotebookDistributionCellAttributes", new GenericType<NotebookDistributionCellAttributes>() {}); schemas.put( "NotebookHeatMapCellAttributes", new GenericType<NotebookHeatMapCellAttributes>() {}); schemas.put( "NotebookLogStreamCellAttributes", new GenericType<NotebookLogStreamCellAttributes>() {}); schemas.put( "NotebookMarkdownCellAttributes", new GenericType<NotebookMarkdownCellAttributes>() {}); schemas.put( "NotebookTimeseriesCellAttributes", new GenericType<NotebookTimeseriesCellAttributes>() {}); schemas.put( "NotebookToplistCellAttributes", new GenericType<NotebookToplistCellAttributes>() {}); JSON.registerDescendants( NotebookCellCreateRequestAttributes.class, Collections.unmodifiableMap(schemas)); } @Override public Map<String, GenericType> getSchemas() { return NotebookCellCreateRequestAttributes.schemas; } /** * Set the instance that matches the oneOf child schema, check the instance parameter is valid * against the oneOf child schemas: NotebookDistributionCellAttributes, * NotebookHeatMapCellAttributes, NotebookLogStreamCellAttributes, NotebookMarkdownCellAttributes, * NotebookTimeseriesCellAttributes, NotebookToplistCellAttributes * * <p>It could be an instance of the 'oneOf' schemas. The oneOf child schemas may themselves be a * composed schema (allOf, anyOf, oneOf). */ @Override public void setActualInstance(Object instance) { if (JSON.isInstanceOf( NotebookDistributionCellAttributes.class, instance, new HashSet<Class<?>>())) { super.setActualInstance(instance); return; } if (JSON.isInstanceOf(NotebookHeatMapCellAttributes.class, instance, new HashSet<Class<?>>())) { super.setActualInstance(instance); return; } if (JSON.isInstanceOf( NotebookLogStreamCellAttributes.class, instance, new HashSet<Class<?>>())) { super.setActualInstance(instance); return; } if (JSON.isInstanceOf( NotebookMarkdownCellAttributes.class, instance, new HashSet<Class<?>>())) { super.setActualInstance(instance); return; } if (JSON.isInstanceOf( NotebookTimeseriesCellAttributes.class, instance, new HashSet<Class<?>>())) { super.setActualInstance(instance); return; } if (JSON.isInstanceOf(NotebookToplistCellAttributes.class, instance, new HashSet<Class<?>>())) { super.setActualInstance(instance); return; } if (JSON.isInstanceOf(UnparsedObject.class, instance, new HashSet<Class<?>>())) { super.setActualInstance(instance); return; } throw new RuntimeException( "Invalid instance type. Must be NotebookDistributionCellAttributes," + " NotebookHeatMapCellAttributes, NotebookLogStreamCellAttributes," + " NotebookMarkdownCellAttributes, NotebookTimeseriesCellAttributes," + " NotebookToplistCellAttributes"); } /** * Get the actual instance, which can be the following: NotebookDistributionCellAttributes, * NotebookHeatMapCellAttributes, NotebookLogStreamCellAttributes, NotebookMarkdownCellAttributes, * NotebookTimeseriesCellAttributes, NotebookToplistCellAttributes * * @return The actual instance (NotebookDistributionCellAttributes, NotebookHeatMapCellAttributes, * NotebookLogStreamCellAttributes, NotebookMarkdownCellAttributes, * NotebookTimeseriesCellAttributes, NotebookToplistCellAttributes) */ @Override public Object getActualInstance() { return super.getActualInstance(); } /** * Get the actual instance of `NotebookDistributionCellAttributes`. If the actual instance is not * `NotebookDistributionCellAttributes`, the ClassCastException will be thrown. * * @return The actual instance of `NotebookDistributionCellAttributes` * @throws ClassCastException if the instance is not `NotebookDistributionCellAttributes` */ public NotebookDistributionCellAttributes getNotebookDistributionCellAttributes() throws ClassCastException { return (NotebookDistributionCellAttributes) super.getActualInstance(); } /** * Get the actual instance of `NotebookHeatMapCellAttributes`. If the actual instance is not * `NotebookHeatMapCellAttributes`, the ClassCastException will be thrown. * * @return The actual instance of `NotebookHeatMapCellAttributes` * @throws ClassCastException if the instance is not `NotebookHeatMapCellAttributes` */ public NotebookHeatMapCellAttributes getNotebookHeatMapCellAttributes() throws ClassCastException { return (NotebookHeatMapCellAttributes) super.getActualInstance(); } /** * Get the actual instance of `NotebookLogStreamCellAttributes`. If the actual instance is not * `NotebookLogStreamCellAttributes`, the ClassCastException will be thrown. * * @return The actual instance of `NotebookLogStreamCellAttributes` * @throws ClassCastException if the instance is not `NotebookLogStreamCellAttributes` */ public NotebookLogStreamCellAttributes getNotebookLogStreamCellAttributes() throws ClassCastException { return (NotebookLogStreamCellAttributes) super.getActualInstance(); } /** * Get the actual instance of `NotebookMarkdownCellAttributes`. If the actual instance is not * `NotebookMarkdownCellAttributes`, the ClassCastException will be thrown. * * @return The actual instance of `NotebookMarkdownCellAttributes` * @throws ClassCastException if the instance is not `NotebookMarkdownCellAttributes` */ public NotebookMarkdownCellAttributes getNotebookMarkdownCellAttributes() throws ClassCastException { return (NotebookMarkdownCellAttributes) super.getActualInstance(); } /** * Get the actual instance of `NotebookTimeseriesCellAttributes`. If the actual instance is not * `NotebookTimeseriesCellAttributes`, the ClassCastException will be thrown. * * @return The actual instance of `NotebookTimeseriesCellAttributes` * @throws ClassCastException if the instance is not `NotebookTimeseriesCellAttributes` */ public NotebookTimeseriesCellAttributes getNotebookTimeseriesCellAttributes() throws ClassCastException { return (NotebookTimeseriesCellAttributes) super.getActualInstance(); } /** * Get the actual instance of `NotebookToplistCellAttributes`. If the actual instance is not * `NotebookToplistCellAttributes`, the ClassCastException will be thrown. * * @return The actual instance of `NotebookToplistCellAttributes` * @throws ClassCastException if the instance is not `NotebookToplistCellAttributes` */ public NotebookToplistCellAttributes getNotebookToplistCellAttributes() throws ClassCastException { return (NotebookToplistCellAttributes) super.getActualInstance(); } }
46.157627
109
0.682518
c650d0205eb493ce8efc5ca24a5487da0c33f8d7
831
package com.bai.ding.goods.service; import com.bai.ding.common.Result; import com.bai.ding.goods.models.GoodsCategory; import com.bai.ding.goods.models.condition.QueryCategoryCondition; /** * @author BaiDing * @date 2020/3/24 14:41 */ public interface GoodsCategoryService { /** * 根据条件查询商品分类 * * @param condition * @return */ Result getGoodsCategoryAll(QueryCategoryCondition condition); /** * 删除分类,同时会删除子分类 * * @param id * @return */ Result deleteGoodsCategory(long id); /** * 添加分类 * * @param goodsCategory * @return */ Result addGoodsCategory(GoodsCategory goodsCategory); /** * 编辑分类 主要编辑分类名称 * * @param goodsCategory * @return */ Result editGoodsCategory(GoodsCategory goodsCategory); }
18.466667
66
0.626955
f2fc758d339b1e77fb17c130d32588228511bdae
356
/* * * * Copyright 2020 New Relic Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * */ package com.newrelic.agent; public class Duration { public long startTime; public long endTime; public Duration(long startTime, long endTime) { this.startTime = startTime; this.endTime = endTime; } }
17.8
64
0.657303
e41750c7700633ff5008b7847d483b03f419c0e7
2,712
package com.ruoyi.shareproject.daily.service.impl; import java.util.List; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.shareproject.daily.domain.TLpMonthlyTargetDaily; import com.ruoyi.shareproject.daily.mapper.TLpMonthlyTargetDailyMapper; import com.ruoyi.shareproject.daily.service.ITLpMonthlyTargetDailyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.common.core.text.Convert; /** * 【日报管理-月度指标】Service业务层处理 * * @author gaohg * @date 2020-10-26 */ @Service public class TLpMonthlyTargetDailyServiceImpl implements ITLpMonthlyTargetDailyService { @Autowired private TLpMonthlyTargetDailyMapper tLpMonthlyTargetDailyMapper; /** * 查询【日报管理-月度指标】 * * @param id 【日报管理-月度指标】ID * @return 【日报管理-月度指标】 */ @Override public TLpMonthlyTargetDaily selectTLpMonthlyTargetDailyById(Long id) { return tLpMonthlyTargetDailyMapper.selectTLpMonthlyTargetDailyById(id); } /** * 查询【日报管理-月度指标】列表 * * @param tLpMonthlyTargetDaily 【日报管理-月度指标】 * @return 【日报管理-月度指标】 */ @Override public List<TLpMonthlyTargetDaily> selectTLpMonthlyTargetDailyList(TLpMonthlyTargetDaily tLpMonthlyTargetDaily) { return tLpMonthlyTargetDailyMapper.selectTLpMonthlyTargetDailyList(tLpMonthlyTargetDaily); } /** * 新增【日报管理-月度指标】 * * @param tLpMonthlyTargetDaily 【日报管理-月度指标】 * @return 结果 */ @Override public int insertTLpMonthlyTargetDaily(TLpMonthlyTargetDaily tLpMonthlyTargetDaily) { tLpMonthlyTargetDaily.setCreateTime(DateUtils.getNowDate()); return tLpMonthlyTargetDailyMapper.insertTLpMonthlyTargetDaily(tLpMonthlyTargetDaily); } /** * 修改【日报管理-月度指标】 * * @param tLpMonthlyTargetDaily 【日报管理-月度指标】 * @return 结果 */ @Override public int updateTLpMonthlyTargetDaily(TLpMonthlyTargetDaily tLpMonthlyTargetDaily) { tLpMonthlyTargetDaily.setUpdateTime(DateUtils.getNowDate()); return tLpMonthlyTargetDailyMapper.updateTLpMonthlyTargetDaily(tLpMonthlyTargetDaily); } /** * 删除【日报管理-月度指标】对象 * * @param ids 需要删除的数据ID * @return 结果 */ @Override public int deleteTLpMonthlyTargetDailyByIds(String ids) { return tLpMonthlyTargetDailyMapper.deleteTLpMonthlyTargetDailyByIds(Convert.toStrArray(ids)); } /** * 删除【日报管理-月度指标】信息 * * @param id 【日报管理-月度指标】ID * @return 结果 */ @Override public int deleteTLpMonthlyTargetDailyById(Long id) { return tLpMonthlyTargetDailyMapper.deleteTLpMonthlyTargetDailyById(id); } }
27.673469
115
0.713127
81aa4eaff9567c9922c80cef982f03c77cca0373
2,355
/* * Copyright (c) 2015, Alachisoft. 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.alachisoft.tayzgrid.common.datastructures; public class VirtualIndex implements java.lang.Comparable { private static final int maxSize = 79 * 1024; private int x, y; public VirtualIndex() { } public VirtualIndex(int index) { IncrementBy(index); } public final void Increment() { x++; if (x == maxSize) { x = 0; y++; } } public final void IncrementBy(int count) { int number = (this.y * maxSize) + this.x + count; this.x = number % maxSize; this.y = number / maxSize; } public final int getXIndex() { return x; } public final int getYIndex() { return y; } public final int getIndexValue() { return (y * maxSize) + x; } public final VirtualIndex clone() { VirtualIndex clone = new VirtualIndex(); clone.x = x; clone.y = y; return clone; } //<editor-fold defaultstate="collapsed" desc="IComparable"> public final int compareTo(Object obj) { VirtualIndex other = null; if (obj instanceof VirtualIndex) { other = (VirtualIndex) ((obj instanceof VirtualIndex) ? obj : null); } else if (obj instanceof Integer) { other = new VirtualIndex((Integer) obj); } else { return -1; } if (other.getIndexValue() == getIndexValue()) { return 0; } else if (other.getIndexValue() > getIndexValue()) { return -1; } else { return 1; } } //</editor-fold> }
22.216981
80
0.566879
94b6452e3941dc4c4afd7f4f8f15341b10dcb5bb
771
package com.scriptbasic.interfaces; import com.scriptbasic.api.ScriptBasicException; /** * This is the exception that the BASIC program throws when there is some error during the execution. This is also * the exception that extension functions should throw if they can not perform the proper action. */ public class BasicRuntimeException extends ScriptBasicException { private static final long serialVersionUID = -2861269478069129351L; public BasicRuntimeException() { } public BasicRuntimeException(final String arg0) { super(arg0); } public BasicRuntimeException(final Throwable arg0) { super(arg0); } public BasicRuntimeException(final String arg0, final Throwable arg1) { super(arg0, arg1); } }
26.586207
114
0.734112
2e68c722b95cfaa9c45c23638babb6d4c82eb349
3,829
/** * Copyright (c) 2013 Perforce Software. All rights reserved. */ package com.perforce.p4java.tests.dev.unit.features131; import com.perforce.p4java.exception.P4JavaException; import com.perforce.p4java.server.CmdSpec; import com.perforce.p4java.server.callback.IFilterCallback; import com.perforce.p4java.tests.UnicodeServerRule; import com.perforce.p4java.tests.dev.annotations.Jobs; import com.perforce.p4java.tests.dev.annotations.TestId; import com.perforce.p4java.tests.dev.unit.P4JavaRshTestCase; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Test describe changelist with many files using IStreamingCallback */ @Jobs({ "job065303" }) @TestId("Dev131_FilterCallbackTest") public class FilterCallbackTest extends P4JavaRshTestCase { @ClassRule public static UnicodeServerRule p4d = new UnicodeServerRule("r16.1", FilterCallbackTest.class.getSimpleName()); String serverMessage = null; long completedTime = 0; public static class SimpleCallbackHandler implements IFilterCallback { private final int limit; private int count = 0; private Map<String, String> doNotSkipKeysMap; public SimpleCallbackHandler(int limit) { this.limit = limit; this.doNotSkipKeysMap = new HashMap<>(); this.doNotSkipKeysMap.put("func", null); doNotSkipKeysMap = new HashMap<>(); doNotSkipKeysMap.put("unicode", ""); doNotSkipKeysMap.put("serveAddress", ""); doNotSkipKeysMap.put("token", ""); doNotSkipKeysMap.put("confirm", ""); doNotSkipKeysMap.put("himark", ""); doNotSkipKeysMap.put("fseq", ""); } @Override public void reset() {} @Override public boolean skip(String key, Object value, final AtomicBoolean skipSubsequent) throws P4JavaException { if (this.count++ >= this.limit) { skipSubsequent.set(true); } return false; } public Map<String, String> getDoNotSkipKeysMap() throws P4JavaException { return this.doNotSkipKeysMap; } } /** * @Before annotation to a method to be run before each test in a class. */ @Before public void setUp() { // initialization code (before each test). try { Properties props = new Properties(); props.put("enableProgress", "true"); setupServer(p4d.getRSHURL(), userName, password, true, props); String[] s = new String[20]; for (int i = 0; i < 20; i++) { s[i] = "test" + i; } client = getClient(server); createTextFilesOnServer(client, s, "multiple files changelist"); } catch (Exception e) { fail("Unexpected exception: " + e.getLocalizedMessage()); } } /** * @After annotation to a method to be run after each test in a class. */ @After public void tearDown() { // cleanup code (after each test). if (server != null) { this.endServerSession(server); } } /** * Test describe changelist with many files using IStreamingCallback */ @Test public void testDescribeChangelistWithManyFiles() { int limit = 1; try { SimpleCallbackHandler handler = new SimpleCallbackHandler(limit); List<Map<String, Object>> resultsList = server.execInputStringMapCmdList(CmdSpec.DESCRIBE.toString(), new String[] { "-s", "30125" }, null, handler); assertNotNull(resultsList); assertTrue(resultsList.size() > 0); assertNotNull(resultsList.get(0)); for (Map<String, Object> resultmap : resultsList) { assertTrue(resultmap.size() == limit); } } catch (P4JavaException e) { e.printStackTrace(); fail("Unexpected exception: " + e.getLocalizedMessage()); } } }
28.362963
152
0.715853
c4ff0e562afca56185d0b8fe16b102e682fdbdf5
119
package net.npg.abattle.communication.command.impl; @SuppressWarnings("all") public class CommandQueueHelper { }
19.833333
52
0.773109
20c398de770a3406d7c564db821398a64ae8bc83
5,773
package org.multiverse.commitbarriers; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.multiverse.TestThread; import org.multiverse.api.Txn; import org.multiverse.api.callables.TxnVoidCallable; import org.multiverse.api.exceptions.DeadTxnException; import org.multiverse.stms.gamma.GammaStm; import org.multiverse.stms.gamma.transactionalobjects.GammaTxnInteger; import static org.junit.Assert.*; import static org.multiverse.TestUtils.*; import static org.multiverse.api.TxnThreadLocal.clearThreadLocalTxn; public class CountDownCommitBarrier_joinCommitTest { private CountDownCommitBarrier barrier; private GammaStm stm; @Before public void setUp() { stm = new GammaStm(); clearThreadLocalTxn(); clearCurrentThreadInterruptedStatus(); } @After public void tearDown() { clearCurrentThreadInterruptedStatus(); } @Test public void whenNullTransaction() throws InterruptedException { barrier = new CountDownCommitBarrier(1); try { barrier.joinCommit(null); fail(); } catch (NullPointerException expected) { } assertTrue(barrier.isClosed()); assertEquals(0, barrier.getNumberWaiting()); } @Test public void whenLastOneEntering() throws InterruptedException { barrier = new CountDownCommitBarrier(1); Txn tx = stm.newTxnFactoryBuilder() .setSpeculative(false) .newTransactionFactory() .newTxn(); barrier.joinCommit(tx); assertIsCommitted(tx); assertTrue(barrier.isCommitted()); assertEquals(0, barrier.getNumberWaiting()); } @Test public void whenAbortedWhileWaiting() throws InterruptedException { barrier = new CountDownCommitBarrier(2); final GammaTxnInteger ref = stm.getDefaultRefFactory().newTxnInteger(0); TestThread t = new TestThread() { @Override public void doRun() throws Exception { stm.getDefaultTxnExecutor().execute(new TxnVoidCallable() { @Override public void call(Txn tx) throws Exception { ref.set(tx, 10); barrier.joinCommit(tx); } }); } }; t.setPrintStackTrace(false); t.start(); sleepMs(1000); assertAlive(t); assertTrue(barrier.isClosed()); barrier.abort(); t.join(); t.assertFailedWithException(IllegalStateException.class); assertTrue(barrier.isAborted()); assertEquals(0, ref.atomicGet()); } @Test public void whenCommittedWhileWaiting() { barrier = new CountDownCommitBarrier(3); JoinCommitThread t1 = new JoinCommitThread(stm, barrier); JoinCommitThread t2 = new JoinCommitThread(stm, barrier); startAll(t1, t2); sleepMs(500); barrier.countDown(); joinAll(t1, t2); assertTrue(barrier.isCommitted()); } @Test public void whenInterruptedWhileWaiting() throws InterruptedException { barrier = new CountDownCommitBarrier(2); final GammaTxnInteger ref = stm.getDefaultRefFactory().newTxnInteger(0); TestThread t = new TestThread() { @Override public void doRun() throws Exception { stm.getDefaultTxnExecutor().executeChecked(new TxnVoidCallable() { @Override public void call(Txn tx) throws Exception { ref.set(tx, 10); barrier.joinCommit(tx); } }); } }; t.setPrintStackTrace(false); t.start(); sleepMs(500); t.interrupt(); t.join(); t.assertFailedWithException(InterruptedException.class); assertEquals(0, ref.atomicGet()); assertTrue(barrier.isAborted()); } @Test public void whenTransactionAlreadyCommitted() throws InterruptedException { barrier = new CountDownCommitBarrier(1); Txn tx = stm.newDefaultTxn(); tx.commit(); try { barrier.joinCommit(tx); fail(); } catch (DeadTxnException expected) { } assertIsCommitted(tx); assertTrue(barrier.isClosed()); } @Test public void whenTransactionAlreadyAborted_thenDeadTxnException() throws InterruptedException { barrier = new CountDownCommitBarrier(1); Txn tx = stm.newDefaultTxn(); tx.abort(); try { barrier.joinCommit(tx); fail(); } catch (DeadTxnException expected) { } assertIsAborted(tx); assertTrue(barrier.isClosed()); } @Test public void whenAborted_thenCommitBarrierOpenException() throws InterruptedException { barrier = new CountDownCommitBarrier(1); barrier.abort(); Txn tx = stm.newDefaultTxn(); try { barrier.joinCommit(tx); fail(); } catch (CommitBarrierOpenException expected) { } assertTrue(barrier.isAborted()); assertEquals(0, barrier.getNumberWaiting()); } @Test public void whenCommitted_thenCommitBarrierOpenException() throws InterruptedException { barrier = new CountDownCommitBarrier(0); Txn tx = stm.newDefaultTxn(); try { barrier.joinCommit(tx); fail(); } catch (CommitBarrierOpenException expected) { } assertTrue(barrier.isCommitted()); assertEquals(0, barrier.getNumberWaiting()); } }
27.490476
98
0.605751
7f576b38f87a10bf0ba13df9c36d5e084c2701c7
2,583
/* The MIT License (MIT) Copyright (c) 2019 Sentaroh 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.sentaroh.android.ZipUtility3; import android.app.Activity; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.sentaroh.android.Utilities3.Widget.CustomSpinnerAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZipFileSelectorAdapter extends CustomSpinnerAdapter { final private static Logger log= LoggerFactory.getLogger(ZipFileSelectorAdapter.class); private Activity mActivity=null; public ZipFileSelectorAdapter(Activity c, int textViewResourceId) { super(c, textViewResourceId); mActivity=c; } @Override public void add(String item) { super.add(item); } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view; if (convertView == null) { view=(TextView)super.getView(position,convertView,parent); } else { view = (TextView)convertView; } String fp=getItem(position); String fn=""; if (fp.lastIndexOf("/")>=0) fn=fp.substring(fp.lastIndexOf("/")+1); else fn=fp; view.setText(fn); view.setCompoundDrawablePadding(10); view.setCompoundDrawablesWithIntrinsicBounds( mActivity.getResources().getDrawable(android.R.drawable.arrow_down_float), null, null, null); setSelectedPosition(position); return view; } }
34.905405
91
0.729772
788c259aa4970b35a7c9bbdd7f29b6502ae37301
15,860
package com.politechnika.shootingrange.fragments; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.util.Log; import android.view.View; import android.widget.Toast; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.politechnika.shootingrange.activities.MainActivity; import com.politechnika.shootingrange.constants.UrlConstants; import com.politechnika.shootingrange.models.Event; import com.politechnika.shootingrange.models.MainReferee; import com.politechnika.shootingrange.models.Rater; import com.politechnika.shootingrange.models.TypeOfCompetition; import com.politechnika.shootingrange.utils.EventCardAdapter; import com.politechnika.shootingrange.utils.RecyclerItemTouchHelper; import com.politechnika.shootingrange.utils.RequestHandler; import com.politechnika.shootingrange.utils.RequestUtil; import com.politechnika.shootingrange.utils.ServerCallback; import com.politechnika.shootingrange.utils.SharedPrefManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import butterknife.BindView; import com.politechnika.shootingrange.R; import com.politechnika.shootingrange.utils.ToastUtils; public class UserEventsFragment extends BaseFragment implements RecyclerView.OnScrollChangeListener, RecyclerItemTouchHelper.RecyclerItemTouchHelperListener, MainActivity.DataUpdateListener{ private List<Event> listEvents; @BindView(R.id.user_recyclerView) RecyclerView recyclerView; @BindView(R.id.coordinatorLayout) CoordinatorLayout coordinatorLayout; @Nullable @BindView(R.id.incoming_recyclerView) RecyclerView incomingEventsRecyclerView; private RecyclerView.LayoutManager layoutManager; private EventCardAdapter adapter; public UserEventsFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(getClassTag(), "onCreate: "); setFragmentCreated(true); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(getContext()); recyclerView.setLayoutManager(layoutManager); listEvents = new ArrayList<>(); //Adding an scroll change listener to recyclerview recyclerView.setOnScrollChangeListener(this); //initializing our adapter adapter = new EventCardAdapter(listEvents, getContext(), this); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); // Adding adapter to recyclerview recyclerView.setAdapter(adapter); // adding item touch helper // only ItemTouchHelper.LEFT added to detect Right to Left swipe // if you want both Right -> Left and Left -> Right // add pass ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT as param ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new RecyclerItemTouchHelper(0, ItemTouchHelper.LEFT, this); new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView); // .setOnDataChangedListener(new BaseFragment.OnDataChangedListener() { // @Override // public void onDataChanged() { // Log.d(getClassTag(), "onDataChanged: "); // // } // }); getData(); } @Override public void onAttach(Context context) { super.onAttach(context); ((MainActivity) getActivity()).registerDataUpdateListener(this); } @Override public void onDestroyView() { super.onDestroyView(); ((MainActivity) getActivity()).unregisterDataUpdateListener(this); } /** * callback when recycler view is swiped * item will be removed on swiped * undo option will be provided in snackbar to restore the item */ @Override public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction, int position) { if (viewHolder instanceof EventCardAdapter.ViewHolder) { if (direction == ItemTouchHelper.LEFT){ final Event deletedItem = listEvents.get(viewHolder.getAdapterPosition()); // TODO check if event is not outdated, inform user SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.GERMANY); Date currentDate = new Date(); Date eventDate = null; try { eventDate = sdf.parse(deletedItem.getCompetitionDate()); } catch (ParseException e) { e.printStackTrace(); } if (currentDate.before(eventDate)){ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); //alert for confirm to delete builder.setMessage("Are you sure to unregister?"); //set message builder.setPositiveButton("UNREGISTER", new DialogInterface.OnClickListener() { //when click on DELETE @Override public void onClick(DialogInterface dialog, int which) { Log.d(getClassTag(), "UNREGISTER"); showProgressBar(); // get the removed item name to display it in snack bar final String name = listEvents.get(viewHolder.getAdapterPosition()).getCompetitionName(); // remove the item from recycler view adapter.removeItem(viewHolder.getAdapterPosition()); RequestUtil requestUtil = new RequestUtil(getActivity(), getContext()); requestUtil.unregisterFromEvent(deletedItem.getIdCompetition(), new ServerCallback() { @Override public void onSuccess(String response) { hideProgressBar(); try { JSONObject obj = new JSONObject(response); if (!obj.getBoolean("error")) { Log.d(getClassTag(), "registerUserToEvent:onSuccess: Error: " + obj.getString("message")); // inform parent classes that you registered and have to change views ((MainActivity) getActivity()).incomingEventsDataUpdated(); //create snackbar// showing snack bar with Undo option Snackbar snackbar = Snackbar .make(coordinatorLayout, "You have unregistered from " + name + " competition!", Snackbar.LENGTH_LONG); snackbar.show(); } else { Log.d(getClassTag(), "registerUserToEvent:onSuccess: Error: " + obj.getString("message")); Toast.makeText(getContext(), obj.getString("message"), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { Log.d(getClassTag(), "registerUserToEvent:onSuccess: Unknown error: " + e.getMessage()); e.printStackTrace(); } } @Override public void onError(Exception exception) { Toast.makeText(getContext(), exception.getMessage(), Toast.LENGTH_LONG).show(); } }); return; } }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { //not removing items if cancel is done @Override public void onClick(DialogInterface dialog, int which) { Log.d(getClassTag(), "CANCEL"); // Animating back into original position adapter.notifyItemChanged(viewHolder.getAdapterPosition()); return; } }).setCancelable(false).show(); } else { //create snackbar// showing snack bar with Undo option Snackbar snackbar = Snackbar .make(coordinatorLayout, "This event is outdated. You can't delete this event.", Snackbar.LENGTH_LONG); snackbar.show(); adapter.notifyItemChanged(viewHolder.getAdapterPosition()); } } } } @Override protected int getFragmentLayout() { return R.layout.fragment_user_events; } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); Log.d(getClassTag(), "setUserVisibleHint: " + isVisibleToUser); if (isVisibleToUser && isFragmentCreated()) { // when switching fragments it can be used } } //Request to get json from server we are passing an integer here //This integer will used to specify the page number for the request ?page = requestcount //This method would return a JsonArrayRequest that will be added to the request queue private JsonArrayRequest getDataFromServer() { Log.d(getClassTag(), "getDataFromServer: start"); //Displaying Progressbar showProgressBar(); //JsonArrayRequest of volley JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(UrlConstants.URL_GET_USER_EVENTS + "?username=" + SharedPrefManager.getInstance(getContext()).getUser().getUsername(), new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d(getClassTag(), "getDataFromServer: onResponse: "); //Calling method parseData to parse the json response parseData(response); //Hiding the progressbar hideProgressBar(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(getClassTag(), "getDataFromServer: onErrorResponse: " + error.getMessage()); //If an error occurs that means end of the list has reached ToastUtils.showShortMessage("No More Items Available", getActivity()); hideProgressBar(); } }); //Returning the request return jsonArrayRequest; } //This method will get data from the web api private void getData() { Log.d(getClassTag(), " getData() : getting data"); RequestHandler.getInstance(getContext()).addToRequestQueue(getDataFromServer(), getClassTag()); } public void updateData(){ Log.d(getClassTag(), "updateData"); adapter.clearList(); getData(); } private void parseData(JSONArray array) { Log.d(getClassTag(), "parseData: "); for (int i = 0; i < array.length(); i++) { Event event = new Event(); MainReferee mainReferee; Rater rater; TypeOfCompetition typeOfCompetition; JSONObject json = null; try { // getting object element from array json = array.getJSONObject(i); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setDateFormat("yy/M/d/ hh:mm:ss"); Gson gson = gsonBuilder.create(); mainReferee = gson.fromJson(json.getJSONObject("mainReferee").toString(), MainReferee.class); rater = gson.fromJson(json.getJSONObject("rater").toString(), Rater.class); typeOfCompetition = gson.fromJson(json.getJSONObject("typeOfCompetition").toString(), TypeOfCompetition.class); //Adding data to the event object event.setMainReferee(mainReferee); event.setRater(rater); event.setTypeOfCompetition(typeOfCompetition); event.setIdCompetition(json.getString(Event.TAG_ID_COMPETITION)); event.setThumbnailUrl(UrlConstants.URL_THUMBNAIL + json.getString(Event.TAG_THUMBNAIL_URL)); event.setCompetitionName(json.getString(Event.TAG_EVENT_NAME)); event.setCompetitionDescription(json.getString(Event.TAG_EVENT_DESCRIPTION)); event.setCompetitionDate(json.getString(Event.TAG_EVENT_DATE)); event.setPrice(Integer.parseInt(json.getString(Event.TAG_PRICE))); event.setNumberOfCompetitors(Integer.parseInt(json.getString(Event.TAG_NUMBER_OF_COMPETITORS))); event.setAvailable(false); Log.d(getClassTag(), event.toString()); } catch (JSONException e) { e.printStackTrace(); } listEvents.add(event); } //Notifying the adapter that data has been added or changed adapter.notifyDataSetChanged(); } //This method would check that the recyclerview scroll has reached the bottom or not private boolean isLastItemDisplaying(RecyclerView recyclerView) { Log.d(getClassTag(), "isLastItemDisplaying: "); if (recyclerView.getAdapter().getItemCount() != 0) { int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition(); if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1) return true; } return false; } @Override public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { Log.d(getClassTag(), "onScrollChange: "); if (isLastItemDisplaying(recyclerView)) { } } @Override public void onUserEventsDataUpdate() { Log.d(getClassTag(), "DataUpdateListener: onUserEventsDataUpdate: updating data"); updateData(); } @Override public void onIncomingEventsDataUpdate() { } }
44.055556
190
0.610656
26bd302d8e8fd9c005e0449ed238381e4540886a
1,521
/* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.annotation; import org.springframework.core.type.filter.AssignableTypeFilter; /** * Enumeration of the type filters that may be used in conjunction with * {@link ComponentScan @ComponentScan}. * * @author Mark Fisher * @author Juergen Hoeller * @author Chris Beams * @since 2.5 * @see ComponentScan * @see ComponentScan#includeFilters() * @see ComponentScan#excludeFilters() * @see org.springframework.core.type.filter.TypeFilter */ public enum FilterType { /** * Filter candidates marked with a given annotation. * @see org.springframework.core.type.filter.AnnotationTypeFilter */ ANNOTATION, /** * Filter candidates assignable to a given type. * @see AssignableTypeFilter */ ASSIGNABLE_TYPE, /** Filter candidates using a given custom * {@link org.springframework.core.type.filter.TypeFilter} implementation */ CUSTOM }
27.654545
75
0.741617
693a9d69d4992c8e46ffdc04e1d5f9842ab72afa
3,604
package com.zmj.qvod.view.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.widget.NestedScrollView; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.widget.ImageView; import android.widget.TextView; import com.jaeger.library.StatusBarUtil; import com.jude.beam.bijection.RequiresPresenter; import com.jude.beam.expansion.BeamBaseActivity; import com.jude.easyrecyclerview.EasyRecyclerView; import com.jude.utils.JUtils; import com.weavey.loading.lib.LoadingLayout; import com.zmj.qvod.R; import com.zmj.qvod.module.bean.HotMovieBean; import com.zmj.qvod.presenter.MovieDetailsPresenter; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by matt on 2017/4/6. */ @RequiresPresenter(MovieDetailsPresenter.class) public class MovieDetailsActivity extends BeamBaseActivity<MovieDetailsPresenter> { @BindView(R.id.iv_movie_pic) public ImageView ivMoviePic; @BindView(R.id.iv_dim_bg) public ImageView ivDimBg; @BindView(R.id.tv_details_title) public TextView tvDetailsTitle; @BindView(R.id.tv_details_direct) public TextView tvDetailsDirect; @BindView(R.id.tv_details_actor) public TextView tvDetailsActor; @BindView(R.id.tv_details_type) public TextView tvDetailsType; @BindView(R.id.tv_details_date) public TextView tvDetailsDate; @BindView(R.id.tv_details_country) public TextView tvDetailsCountry; @BindView(R.id.toolbar) public Toolbar toolBar; @BindView(R.id.nsv_title) public NestedScrollView nsvTitle; @BindView(R.id.iv_toolbar_bg) public ImageView ivToolbarBg; @BindView(R.id.tv_movie_call) public TextView tvMovieCall; @BindView(R.id.tv_movie_intro) public TextView tvMovieIntro; @BindView(R.id.erv_movie_list) public EasyRecyclerView recyclerView; @BindView(R.id.ll_movie_loading) public LoadingLayout llLoading; public static void startAction(Activity context, HotMovieBean.SubjectsBean positionData, ImageView imageView) { Intent intent = new Intent(context, MovieDetailsActivity.class); intent.putExtra("positionData", positionData); ActivityOptionsCompat compat = ActivityOptionsCompat.makeSceneTransitionAnimation( context, imageView, context.getResources().getString(R.string.transition_movie_img)); ActivityCompat.startActivity(context, intent, compat.toBundle()); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details_movie); ButterKnife.bind(this); // StatusBarUtil.setTranslucentForImageView(this, 0, toolBar); // onSetToolbar(toolBar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { //是否显示默认Title actionBar.setDisplayShowTitleEnabled(true); //是否显示返回键 actionBar.setDisplayHomeAsUpEnabled(true); } // initLoading(); } private void initLoading() { //网络错误之类的 if (!JUtils.isNetWorkAvilable()) { llLoading.setStatus(LoadingLayout.No_Network); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_more, menu); return true; } }
33.682243
115
0.727802
da5b9070854a99f414ae007731154a885adc36d2
31
enum test probe test test probe
31
31
0.83871
5c6a402488c956655c1e96cadb21ef340b6be7a9
2,529
/** * The MIT License (MIT) * * Copyright (c) 2015-2021 Mickael Jeanroy * * 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.github.mjeanroy.maven.plugins.node.commands; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class CommandTest { @Test public void it_should_create_a_command_with_an_executable() { Command command = new Command("foo"); assertThat(command.getExecutable()).isEqualTo("foo"); assertThat(command.getArguments()).isNotNull().isEmpty(); } @Test public void it_should_create_a_command_and_add_arguments() { Command command = new Command("foo"); command.addArgument("arg1"); command.addArgument("arg2"); command.addArgument("arg2"); command.addArgument("arg3"); assertThat(command.getArguments()) .isNotNull() .isNotEmpty() .hasSize(3) .extractingResultOf("toString") .containsExactly("arg1", "arg2", "arg3"); } @Test public void it_should_different_arguments_instances() { Command command = new Command("foo"); command.addArgument("arg1"); command.addArgument("arg2"); command.addArgument("arg2"); command.addArgument("arg2"); assertThat(command.getArguments()).isNotSameAs(command.getArguments()); } @Test public void it_should_display_command() { Command command = new Command("npm"); command.addArgument("--no-color"); command.addArgument("clean"); assertThat(command.toString()) .isNotNull() .isNotEmpty() .isEqualTo("npm --no-color clean"); } }
33.276316
83
0.7414
725c8d0099395a8cf3f55ca063b316f3c2e3056b
5,822
package com.example.duy.calculator.history; import android.app.Activity; import android.content.Intent; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.duy.calculator.DLog; import com.example.duy.calculator.R; import com.example.duy.calculator.data.Database; import com.example.duy.calculator.math_eval.Tokenizer; import com.example.duy.calculator.utils.ClipboardManager; import com.example.duy.calculator.utils.MyClipboard; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; /** * Adapter history for recycle view */ public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.ViewHolder> { private ArrayList<HistoryEntry> itemHistories = new ArrayList<>(); private Activity context; private HistoryListener listener = null; private Database database; private Tokenizer tokenizer; public HistoryAdapter(Activity context, Tokenizer tokenizer) { this.context = context; database = new Database(context); this.itemHistories = database.getAllItemHistory(); this.tokenizer = tokenizer; for (HistoryEntry entry : itemHistories) { DLog.i("HistoryEntry : " + entry.toString()); } } public ArrayList<HistoryEntry> getItemHistories() { return itemHistories; } public void setItemHistories(ArrayList<HistoryEntry> itemHistories) { this.itemHistories = itemHistories; } public HistoryListener getListener() { return listener; } public void setListener(HistoryListener listener) { this.listener = listener; } public void addHistory(HistoryEntry historyEntry) { itemHistories.add(historyEntry); database.removeItemHistory(historyEntry.getTime()); notifyItemInserted(itemHistories.size() - 1); } public void removeHistory(HistoryEntry historyEntry, int position) { itemHistories.remove(historyEntry); database.removeItemHistory(historyEntry.getTime()); notifyItemRemoved(position); } public void removeHistory(int position) { itemHistories.remove(position); notifyItemRemoved(position); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.history_entry, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { final HistoryEntry historyEntry = itemHistories.get(position); holder.txtMath.setText(tokenizer.getLocalizedExpression(historyEntry.getMath())); holder.txtMath.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (listener != null) listener.onItemLongClickListener(v, historyEntry); return false; } }); holder.txtMath.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listener != null) listener.onItemClickListener(v, historyEntry); } }); holder.txtResult.setText(historyEntry.getResult()); holder.txtResult.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (listener != null) listener.onItemLongClickListener(v, historyEntry); return false; } }); holder.txtResult.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listener != null) listener.onItemClickListener(v, historyEntry); } }); holder.imgCopy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ClipboardManager.setClipboard(context, historyEntry.getMath()); } }); holder.imgShare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_TEXT, historyEntry.getMath() + " = " + historyEntry.getResult()); intent.setType("text/plain"); context.startActivity(intent); } }); } @Override public int getItemCount() { return itemHistories.size(); } public HistoryEntry getItem(int index) { return itemHistories.get(index); } public void clear() { itemHistories.clear(); notifyItemRangeRemoved(0, getItemCount()); } public interface HistoryListener { void onItemClickListener(View view, HistoryEntry historyEntry); void onItemLongClickListener(View view, HistoryEntry historyEntry); } public class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.txt_math) TextView txtMath; @BindView(R.id.txt_result) TextView txtResult; @BindView(R.id.card_view) CardView cardView; // @BindView(R.id.tex_result) // MathView texResult; @BindView(R.id.img_share_item) ImageView imgShare; @BindView(R.id.img_copy_item) ImageView imgCopy; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
31.989011
110
0.657506
74611b3b1c2a621cc7d91a47586cbfcea48f006c
2,942
package com.clakestudio.pc.everyday.data; import android.os.AsyncTask; import java.lang.ref.WeakReference; import java.util.List; /** * Created by Jan on 8/30/2018. */ public class DayRepository { private final DayDao dayDao; private static DayRepository INSTANCE = null; private DayRepository(DayDao dayDao) { this.dayDao = dayDao; } public static DayRepository getInstance(DayDao dayDao) { if (INSTANCE == null) { INSTANCE = new DayRepository(dayDao); } return INSTANCE; } private List<Day> getDays() { return dayDao.getDayList(); } public void getDays(final AsyncAccessor asyncAccessor) { AsyncGetDays asyncGetDays = new AsyncGetDays(dayDao, asyncAccessor); asyncGetDays.execute(); } public Day getDayById(String dayId) { return dayDao.getDayById(dayId); } public Day getDayByDate(String date) { return dayDao.getDayByDate(date); } public void addNewDay(final Day day) { AsyncAddNewDay asyncAddNewDay = new AsyncAddNewDay(dayDao); asyncAddNewDay.execute(day); } public int deleteDayById(String dayId) { return dayDao.deleteByDayId(dayId); } public void updateDay(String title, String note, String dayId) { dayDao.updateDay(title, note, dayId); } } /** * Do not know whether this approach with acynctask is good -> gonna do more research in case of memory leaks etc * - > created weak references * - > basically this asyncTasks runs only in ShowDaysActivity and dayInfo are passed to other activities by Intent * -> the passing data by Intent approach is actually not the best solution because we are simply decomposing objects, but in this particular * -> use case (aka application) we do that once or twice so it is not that annoying **/ class AsyncGetDays extends AsyncTask<Void, Void, List<Day>> { private WeakReference<AsyncAccessor> asyncAccessorWeakReference; private WeakReference<DayDao> dayDaoWeakReference; AsyncGetDays(DayDao dayDao, AsyncAccessor asyncAccessor) { asyncAccessorWeakReference = new WeakReference<>(asyncAccessor); dayDaoWeakReference = new WeakReference<>(dayDao); } @Override protected List<Day> doInBackground(Void... voids) { return this.dayDaoWeakReference.get().getDayList(); } @Override protected void onPostExecute(List<Day> days) { asyncAccessorWeakReference.get().getDays(days); } } /** * Weak reference, not a long running task * * */ class AsyncAddNewDay extends AsyncTask<Day, Void, Void> { private WeakReference<DayDao> dayDaoWeakReference; AsyncAddNewDay(DayDao dayDao) { dayDaoWeakReference = new WeakReference<>(dayDao); } @Override protected Void doInBackground(Day... days) { dayDaoWeakReference.get().insertDay(days[0]); return null; } }
26.745455
141
0.688647
5c485267d46992c1c0d9d0f347fee9538ab8814b
2,668
package net.pl3x.bukkit.ridables.command; import net.minecraft.server.v1_13_R2.Entity; import net.pl3x.bukkit.ridables.Ridables; import net.pl3x.bukkit.ridables.configuration.Config; import net.pl3x.bukkit.ridables.configuration.Lang; import net.pl3x.bukkit.ridables.entity.RidableEntity; import net.pl3x.bukkit.ridables.entity.RidableType; import net.pl3x.bukkit.ridables.util.Logger; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.bukkit.craftbukkit.v1_13_R2.entity.CraftEntity; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class CmdRidables implements TabExecutor { private final Ridables plugin; public CmdRidables(Ridables plugin) { this.plugin = plugin; } @Override public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) { if (args.length == 1) { return Stream.of("reload") .filter(cmd -> cmd.startsWith(args[0].toLowerCase())) .collect(Collectors.toList()); } return null; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!sender.hasPermission("command.ridables")) { Logger.debug("Perm Check: " + sender.getName() + " does NOT have permission for /ridables command"); Lang.send(sender, Lang.COMMAND_NO_PERMISSION); return true; } if (args.length > 0 && args[0].equalsIgnoreCase("reload")) { Lang.send(sender, Lang.RELOADING_CONFIG); Config.reload(); Lang.send(sender, Lang.RELOADING_LANG); Lang.reload(); Lang.send(sender, Lang.RELOADING_MOB_CONFIGS); RidableType.BY_BUKKIT_TYPE.forEach((bukkit, ridable) -> { if (ridable.getConfig() != null) { ridable.getConfig().reload(); } }); Lang.send(sender, Lang.RELOADING_MOB_ATTRIBUTES); Bukkit.getWorlds().forEach(world -> world.getEntities().forEach(entity -> { Entity nmsEntity = ((CraftEntity) entity).getHandle(); if (nmsEntity instanceof RidableEntity) { ((RidableEntity) nmsEntity).reloadAttributes(); } })); Lang.send(sender, Lang.RELOAD_COMPLETE); return true; } Lang.send(sender, "&e[&3Ridables&e]&a v" + plugin.getDescription().getVersion()); return true; } }
35.573333
112
0.636057
53b358b9b22dcd93a064ddd15401034825640a58
1,444
package edu.byu.edge.coreIdentity.client.impl; import edu.byu.edge.coreIdentity.client.CoreIdentityClient; import edu.byu.edge.coreIdentity.client.exceptions.RestHttpException; import edu.byu.edge.coreIdentity.domain.CoreIdentity; import edu.byu.wso2.core.provider.TokenHeaderProvider; import org.springframework.cache.annotation.Cacheable; import java.io.IOException; /** * Created by Scott Hutchings on 5/9/2017. * edge-clients */ public class CachedCoreIdentityClient extends CoreIdentityClientImpl implements CoreIdentityClient { public CachedCoreIdentityClient(TokenHeaderProvider tokenHeaderProvider) { super(tokenHeaderProvider); } public CachedCoreIdentityClient(TokenHeaderProvider tokenHeaderProvider, String baseUrl) { super(tokenHeaderProvider, baseUrl); } @Override @Cacheable(value = "coreIdentityCache", unless = "#result == null") public CoreIdentity getCoreIdentityByPersonId(String personId) throws RestHttpException, IOException { return super.getCoreIdentityByPersonId(personId); } @Override @Cacheable(value = "coreIdentityCache", unless = "#result == null") public CoreIdentity getCoreIdentityByByuId(String byuId) { return super.getCoreIdentityByByuId(byuId); } @Override @Cacheable(value = "coreIdentityCache", unless = "#result == null") public CoreIdentity getCoreIdentityByNetId(String netId) throws IOException, RestHttpException { return super.getCoreIdentityByNetId(netId); } }
34.380952
103
0.807479
9e2649e206fa31820ade87c05087121df72ebaa3
1,667
package language.arith; import language.Operand; import language.Operator; /** * The {@code NegateOperator} is an operator that performs negation on a single integer * @author jcollard * */ public class NegateOperator implements Operator<Integer> { Integer result; // TODO Have you taken a look at the PlusOperator yet? // You will notice that it extends the abstract class BinaryOperator. // You should take a moment and review those classes and how they // relate to before trying to // implement this one. Although it is not required, // it might be a good idea to first write // an abstract class called UnaryOperator, paralleling // BinaryOperator, that abstracts out all the bits common // across UnaryOperators. /** * {@inheritDoc} */ @Override public int getNumberOfArguments() { // TODO See the comment at the top of this class. return 1; // negation only has one operand } /** * {@inheritDoc} */ @Override public Operand<Integer> performOperation() { // TODO See the comment at the top of this class. return new Operand<Integer>(result); } /** * {@inheritDoc} */ @Override public void setOperand(int i, Operand<Integer> operand) { // TODO See the comment at the top of this class. // TODO Negation on an integer is simply flipping its sign // So the negation of some int value i is -i. if (!(i == 0 || i == 1)) { throw new IllegalArgumentException("Unary operator should not except input to position" + i); } else if (operand == null) { throw new NullPointerException("No null values"); } result = operand.getValue() * - 1; } public String toString() { return "!"; } }
26.046875
96
0.693461
fb9215a624c7dc7412af95a638f629fde5219029
625
package com.loserico.pattern.behavioral.state; import lombok.Data; /** * <p> * Copyright: (C), 2020/1/31 11:05 * <p> * <p> * Company: Sexy Uncle Inc. * * @author Rico Yu [email protected] * @version 1.0 */ @Data public class DeliveryContext { private PackageState currentState; private String packageId; public DeliveryContext(PackageState packageState, String packageId) { this.currentState = packageState; this.packageId = packageId; if (this.currentState == null) { this.currentState = AcknowledgedState.instance(); } } public void update() { currentState.updateState(this); } }
17.857143
70
0.6976
d3abf8a24f39d8a97b96363e3f139dedba5b3f2a
978
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 行业代扣合约版解约 * * @author auto create * @since 1.0, 2021-12-20 11:08:29 */ public class AlipayEbppInstserviceContractdeductUnsignModel extends AlipayObject { private static final long serialVersionUID = 3828448816824969618L; /** * 代扣签约协议号 */ @ApiField("agreement_id") private String agreementId; /** * 用户户号 */ @ApiField("bill_key") private String billKey; /** * 用户签约的支付宝账号id */ @ApiField("user_id") private String userId; public String getAgreementId() { return this.agreementId; } public void setAgreementId(String agreementId) { this.agreementId = agreementId; } public String getBillKey() { return this.billKey; } public void setBillKey(String billKey) { this.billKey = billKey; } public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } }
17.464286
82
0.716769
8286280c4322ff2703be4f90547fa0a25a81a0a6
3,747
package by.htp.itacademy.multidimarray; import by.htp.itacademy.util.*; public class MultiDimArrayP4 { public static void main(String[] args) { // task31(); // task32(); // task33(); // task34(); // task35(); // task36(); // task37(); task38(); // task39(); // task40(); } // Task #31 // 31. Сформировать матрицу из чисел от 0 до 999, вывести ее на экран. Посчитать количество двузначных чисел в ней. private static void task31() { System.out.println("\n>> Task #31"); // Skipped } // Task #32 // 32. Отсортировать строки матрицы по возрастанию и убыванию значений элементов. private static void task32() { System.out.println("\n>> Task #32"); // Skipped } // Task #33 // 33. Отсотрировать стобцы матрицы по возрастанию и убыванию значений эементов. private static void task33() { System.out.println("\n>> Task #33"); // Skipped } // Task #34 // 34. Сформировать случайную матрицу m x n, состоящую из нулей и единиц, причем в каждом столбце число единиц равно номеру столбца. private static void task34() { System.out.println("\n>> Task #34"); // Skipped } // Task #35 // 35. Найдите наибольший элемент матрицы и заменить все нечетные элементы на него. private static void task35() { System.out.println("\n>> Task #35"); // Skipped } // Task #36 // 36. Операция сглаживания матрицы дает новую матрицу того же размера, каждый элемент которой // получается как среднее арифметическое соседей соответствующего элемента исходной матрицы. // Построить результат сглаживания заданной матрицы private static void task36() { System.out.println("\n>> Task #36"); // Interesting to solve // TODO } // Task #37 // 37. Переставить строки матрицы случайным образом. private static void task37() { System.out.println("\n>> Task #37"); // Skipped } // Task #38 // 38. Найдите сумму двух матриц private static void task38() { System.out.println("\n>> Task #38"); // Qty of Rows int rows = 4; // Qty of Columns int columns = 5; // array 1 int[][] array1 = new int[rows][columns]; // array2 int[][] array2 = new int[rows][columns]; // result array int[][] arrayResult = new int[rows][columns]; // arrays init and sum for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { array1[i][j] = Util.getRandomNumber(-10, 35); array2[i][j] = Util.getRandomNumber(-20, 40); arrayResult[i][j] = array1[i][j] + array2[i][j]; } } Util.print2DimArray(array1); System.out.println("<---------------------->"); Util.print2DimArray(array2); System.out.println("<---------------------->"); Util.print2DimArray(arrayResult); } // Task #39 // 39. Найдите произведение двух матриц. private static void task39() { System.out.println("\n>> Task #39"); // Skipped } // Task #40 // 40. Магическим квадратом порядка n называется квадратная матрица размера nxn, составленная // из чисел 1, 2, 3, ..., n2 так, что суммы по каждому столбцу, каждой строке и каждой из двух // больших диагоналей равны между собой. Построить такой квадрат. Пример магического квадрата порядка 3: private static void task40() { System.out.println("\n>> Task #40"); int arrayDim = 4; int[][] arrayMagic = new int[arrayDim][arrayDim]; // Interesting to solve // TODO } }
24.019231
132
0.573259
d16c2298fc98a9b69f33aecbca6ae3b3d315ba1e
70
package com.jeeplus.modules.esign.service; public class AService { }
14
42
0.785714
fb318ac2879ae27d3fe121b63579b1320f1606e7
21,403
/* * Copyright (c) 2017 Leonardo Pessoa * https://github.com/lmpessoa/java-services * * 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.lmpessoa.services.internal.routing; import static com.lmpessoa.services.routing.HttpMethod.DELETE; import static com.lmpessoa.services.routing.HttpMethod.PATCH; import static com.lmpessoa.services.routing.HttpMethod.POST; import static com.lmpessoa.services.routing.HttpMethod.PUT; import static com.lmpessoa.services.services.Reuse.ALWAYS; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Iterator; import java.util.function.Supplier; import javax.validation.Valid; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.Email; import javax.validation.constraints.Size; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import com.lmpessoa.services.BadRequestException; import com.lmpessoa.services.ContentType; import com.lmpessoa.services.MethodNotAllowedException; import com.lmpessoa.services.NotFoundException; import com.lmpessoa.services.NotImplementedException; import com.lmpessoa.services.Put; import com.lmpessoa.services.Query; import com.lmpessoa.services.Route; import com.lmpessoa.services.hosting.HttpRequest; import com.lmpessoa.services.internal.hosting.HttpRequestBuilder; import com.lmpessoa.services.internal.services.ServiceMap; import com.lmpessoa.services.internal.validating.ValidationService; import com.lmpessoa.services.routing.RouteMatch; import com.lmpessoa.services.services.Service; import com.lmpessoa.services.validating.ErrorSet; import com.lmpessoa.services.validating.IValidationService; public final class RouteTableMatcherTest { @Rule public ExpectedException thrown = ExpectedException.none(); private ServiceMap serviceMap; private RouteTable table; @Before public void setup() { serviceMap = new ServiceMap(); serviceMap.put(IValidationService.class, ValidationService.instance()); table = new RouteTable(serviceMap); table.put("", TestResource.class); } @Test public void testMatchesGetRoot() throws NoSuchMethodException, IOException { RouteMatch result = table.matches(new HttpRequestBuilder().setPath("/test").build()); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("get"), route.getMethod()); assertArrayEquals(new Object[0], route.getMethodArgs()); assertEquals("GET/Test", result.invoke()); } @Test public void testMatchesGetOneArg() throws NoSuchMethodException, IOException { RouteMatch result = table.matches(new HttpRequestBuilder().setPath("/test/7").build()); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("get", int.class), route.getMethod()); assertArrayEquals(new Object[] { 7 }, route.getMethodArgs()); assertEquals("GET/7", result.invoke()); } @Test public void testMatchesConstrainedRoute() throws NoSuchMethodException, IOException { RouteMatch result = table.matches(new HttpRequestBuilder().setPath("/test/abcd").build()); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("get", String.class), route.getMethod()); assertArrayEquals(new Object[] { "abcd" }, route.getMethodArgs()); assertEquals("GET/abcd", result.invoke()); } @Test public void testMatchesConstrainedRouteTooShort() throws NoSuchMethodException, IOException { // With the advent of catchall route tests, this test no longer throws a 404 error RouteMatch result = table.matches(new HttpRequestBuilder().setPath("/test/ab").build()); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("get", String[].class), route.getMethod()); assertArrayEquals(new Object[] { new String[] { "ab" } }, route.getMethodArgs()); assertEquals("GET/ab", route.invoke()); } @Test public void testMatchesConstrainedRouteTooLong() throws NoSuchMethodException, IOException { // With the advent of catchall route tests, this test no longer throws a 404 error RouteMatch result = table.matches(new HttpRequestBuilder().setPath("/test/abcdefg").build()); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("get", String[].class), route.getMethod()); assertArrayEquals(new Object[] { new String[] { "abcdefg" } }, route.getMethodArgs()); assertEquals("GET/abcdefg", route.invoke()); } @Test public void testMatchesGetTwoArgs() throws NoSuchMethodException, IOException { RouteMatch result = table.matches(new HttpRequestBuilder().setPath("/test/6/9").build()); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("get", int.class, int.class), route.getMethod()); assertArrayEquals(new Object[] { 6, 9 }, route.getMethodArgs()); assertEquals("GET/6+9", result.invoke()); } @Test public void testMatchesPostRoot() throws NoSuchMethodException, IOException { RouteMatch result = table .matches(new HttpRequestBuilder().setMethod(POST).setPath("/test").build()); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("post"), route.getMethod()); assertArrayEquals(new Object[0], route.getMethodArgs()); assertEquals("POST/Test", result.invoke()); } @Test public void testMatchesPostOneArg() throws NoSuchMethodException, IOException { RouteMatch result = table .matches(new HttpRequestBuilder().setMethod(POST).setPath("/test/7").build()); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("post", int.class), route.getMethod()); assertArrayEquals(new Object[] { 7 }, route.getMethodArgs()); assertEquals("POST/7", result.invoke()); } @Test public void testMatchesUnregisteredPath() throws IOException { thrown.expect(NotFoundException.class); RouteMatch result = table.matches(new HttpRequestBuilder().setPath("/none").build()); result.invoke(); } @Test public void testMatchesUnregisteredMethod() throws IOException { thrown.expect(MethodNotAllowedException.class); RouteMatch result = table .matches(new HttpRequestBuilder().setMethod(DELETE).setPath("/test/7").build()); result.invoke(); } @Test public void testMatchesHttpException() throws NoSuchMethodException, IOException { thrown.expect(NotImplementedException.class); RouteMatch result = table .matches(new HttpRequestBuilder().setMethod(PATCH).setPath("/test").build()); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("patch"), route.getMethod()); result.invoke(); } @Test public void testMatchesWithService() throws NoSuchMethodException, IOException { Message message = new Message(); serviceMap.put(Message.class, message); table.put("", ServiceTestResource.class); RouteMatch result = table.matches(new HttpRequestBuilder().setPath("/service").build()); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(ServiceTestResource.class, route.getResourceClass()); assertEquals(ServiceTestResource.class.getMethod("get"), route.getMethod()); assertArrayEquals(new Object[] { message }, route.getConstructorArgs()); assertEquals(message.get(), result.invoke()); } @Test public void testMatchesWithoutContent() throws NoSuchMethodException, IOException { HttpRequest request = new HttpRequestBuilder().setMethod(PUT).setPath("/test/12").build(); RouteMatch result = table.matches(request); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("put", ContentObject.class, int.class), route.getMethod()); assertEquals(2, route.getMethodArgs().length); assertEquals(12, route.getMethodArgs()[1]); assertNull(route.getMethodArgs()[0]); } @Test public void testMatchesWithContent() throws NoSuchMethodException, IOException { HttpRequest request = new HttpRequestBuilder().setMethod(PUT) .setPath("/test/12") .setBody("id=12&name=Test&email=test.com&checked=false") .setContentType(ContentType.FORM) .build(); RouteMatch result = table.matches(request); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("put", ContentObject.class, int.class), route.getMethod()); assertEquals(2, route.getMethodArgs().length); assertEquals(12, route.getMethodArgs()[1]); Object obj = route.getMethodArgs()[0]; assertNotNull(obj); assertTrue(obj instanceof ContentObject); ContentObject cobj = (ContentObject) obj; assertEquals(12, cobj.id); assertEquals("Test", cobj.name); assertEquals("test.com", cobj.email); assertFalse(cobj.checked); } @Test public void testMatchesWithInvalidContent() throws NoSuchMethodException, IOException { HttpRequest request = new HttpRequestBuilder().setMethod(PUT) .setPath("/test/valid/12") .setBody("id=12&name=Test&[email protected]") .setContentType(ContentType.FORM) .build(); RouteMatch result = table.matches(request); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("valid", ContentObject.class, int.class), route.getMethod()); assertEquals(2, route.getMethodArgs().length); assertEquals(12, route.getMethodArgs()[1]); Object obj = route.getMethodArgs()[0]; assertNotNull(obj); assertTrue(obj instanceof ContentObject); ContentObject cobj = (ContentObject) obj; assertEquals(12, cobj.id); assertEquals("Test", cobj.name); assertEquals("[email protected]", cobj.email); assertFalse(cobj.checked); try { result.invoke(); throw new IllegalStateException(); } catch (BadRequestException e) { assertNotNull(e.getErrors()); assertFalse(e.getErrors().isEmpty()); Iterator<ErrorSet.Entry> messages = e.getErrors().iterator(); ErrorSet.Entry message = messages.next(); assertEquals("content.checked", message.getPathEntry()); assertEquals("false", message.getInvalidValue()); assertEquals("{javax.validation.constraints.AssertTrue.message}", message.getMessageTemplate()); assertFalse(messages.hasNext()); } catch (Exception e) { Assert.fail(); } } @Test public void testMatchesWithValidContent() throws NoSuchMethodException, IOException { HttpRequest request = new HttpRequestBuilder().setMethod(PUT) .setPath("/test/valid/12") .setBody("id=12&name=Test&[email protected]&checked=true") .setContentType(ContentType.FORM) .build(); RouteMatch result = table.matches(request); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("valid", ContentObject.class, int.class), route.getMethod()); assertEquals(2, route.getMethodArgs().length); assertEquals(12, route.getMethodArgs()[1]); Object obj = route.getMethodArgs()[0]; assertNotNull(obj); assertTrue(obj instanceof ContentObject); ContentObject cobj = (ContentObject) obj; assertEquals(12, cobj.id); assertEquals("Test", cobj.name); assertEquals("[email protected]", cobj.email); assertTrue(cobj.checked); result.invoke(); } @Test public void testMatchesWithQueryParam() throws NoSuchMethodException, IOException { HttpRequest request = new HttpRequestBuilder().setPath("/test/query") .setQueryString("type=class&id=7") .build(); RouteMatch result = table.matches(request); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("getNew", Integer.class), route.getMethod()); assertArrayEquals(new Object[] { 7 }, route.getMethodArgs()); Object invokeResult = route.invoke(); assertTrue(invokeResult instanceof String); assertEquals("7", invokeResult); } @Test public void testMatchesWithMissingQueryParam() throws NoSuchMethodException, IOException { HttpRequest request = new HttpRequestBuilder().setPath("/test/query") .setQueryString("type=class&ids=7") .build(); RouteMatch result = table.matches(request); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("getNew", Integer.class), route.getMethod()); assertArrayEquals(new Object[] { null }, route.getMethodArgs()); Object invokeResult = route.invoke(); assertTrue(invokeResult instanceof String); assertEquals("null", invokeResult); } @Test public void testMatchesWithWrongQueryParam() throws NoSuchMethodException, IOException { thrown.expect(BadRequestException.class); HttpRequest request = new HttpRequestBuilder().setPath("/test/query/12") .setQueryString("id=class") .build(); RouteMatch result = table.matches(request); assertTrue(result instanceof BadRequestException); BadRequestException exception = (BadRequestException) result; assertEquals(TestResource.class, exception.getResourceClass()); assertEquals(TestResource.class.getMethod("getNew", int.class, int.class), exception.getMethod()); exception.invoke(); } @Test public void testMatchCatchAllWithNoPath() throws NoSuchMethodException, IOException { HttpRequest request = new HttpRequestBuilder().setPath("/test/catchall").build(); RouteMatch result = table.matches(request); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("catchall", String[].class), route.getMethod()); assertArrayEquals(new Object[] { new String[0] }, route.getMethodArgs()); } @Test public void testMatchCatchAllWithSinglePath() throws NoSuchMethodException, IOException { HttpRequest request = new HttpRequestBuilder().setPath("/test/catchall/7").build(); RouteMatch result = table.matches(request); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("catchall", String[].class), route.getMethod()); assertArrayEquals(new Object[] { new String[] { "7" } }, route.getMethodArgs()); } @Test public void testMatchCatchAllWithMultiplePath() throws NoSuchMethodException, IOException { HttpRequest request = new HttpRequestBuilder().setPath("/test/catchall/path/to/real/object") .build(); RouteMatch result = table.matches(request); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("catchall", String[].class), route.getMethod()); assertArrayEquals(new Object[] { new String[] { "path", "to", "real", "object" } }, route.getMethodArgs()); } @Test public void testMatchCatchAllWithOtherMethods() throws NoSuchMethodException, IOException { HttpRequest request = new HttpRequestBuilder().setPath("/test/path/to/real/object").build(); RouteMatch result = table.matches(request); assertTrue(result instanceof MatchedRoute); MatchedRoute route = (MatchedRoute) result; assertEquals(TestResource.class, route.getResourceClass()); assertEquals(TestResource.class.getMethod("get", String[].class), route.getMethod()); assertArrayEquals(new Object[] { new String[] { "path", "to", "real", "object" } }, route.getMethodArgs()); } public static class ContentObject { public int id; public String name; @Email public String email; @AssertTrue public boolean checked; } public static class TestResource { public String get() { return "GET/Test"; } public String get(int i) { return "GET/" + i; } public String get(@Size(min = 3, max = 6) String s) { return "GET/" + s; } public String get(String... path) { return "GET/" + String.join(",", path); } public String get(int i, int j) { return "GET/" + i + "+" + j; } @Route("query") public String getNew(@Query Integer id) { return String.valueOf(id); } @Route("query/{0}") public String getNew(int cid, @Query int id) { return String.valueOf(cid + id); } public String post() { return "POST/Test"; } public String post(int i) { return "POST/" + i; } public void patch() { throw new NotImplementedException(); } public void put(ContentObject content, int i) { // Nothing to do here } @Put @Route("valid/{1}") public void valid(@Valid ContentObject content, int i) { // Nothing to do here } @Route("catchall/{0}") public void catchall(String... path) { // Nothing to do here } } @Service(reuse = ALWAYS) static class Message implements Supplier<String> { @Override public String get() { return "Message"; } } @Route("service") public static class ServiceTestResource { private Message message; public ServiceTestResource(Message message) { this.message = message; } public String get() { return message.get(); } } }
41.238921
99
0.694809
6de5d025d15b7c6214efabf65c2e7cb6b288a008
710
import com.fasterxml.jackson.databind.node.ObjectNode; import junit.framework.TestCase; import org.gitana.platform.client.Driver; import org.gitana.platform.client.node.BaseNode; import org.gitana.platform.client.node.Node; import org.gitana.platform.client.support.DriverContext; import org.gitana.platform.client.support.Remote; import org.gitana.platform.client.support.Response; import org.gitana.platform.support.QueryBuilder; import org.gitana.platform.support.ResultMap; import org.junit.Test; import java.io.InputStream; public class Tests extends TestCase { @Test public void testGitana() throws Exception { TestGitana testGitana = new TestGitana(); testGitana.run(); } }
33.809524
56
0.790141