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
be67b56a308292cc0704b26cf474430efb59ba24
2,454
package com.sevenmap.data.parsers.osm.Structure.Node; import java.util.ArrayList; import java.util.Objects; import com.sevenmap.data.parsers.osm.Annotations.XMLAttribute; import com.sevenmap.data.parsers.osm.Annotations.XMLElement; import com.sevenmap.data.parsers.osm.Structure.Metadata.Metadata; import com.sevenmap.data.parsers.osm.Structure.Tag.Tag; public class Node { @XMLAttribute(unique = true) private long id; @XMLAttribute private Double lat; @XMLAttribute private Double lon; @XMLAttribute private Metadata met; @XMLElement(tag = "tag", valueType = Tag.class) private ArrayList<Tag> tags; public Node() { } public Node(long id, Double lat, Double lon, Metadata met, ArrayList<Tag> tags) { this.id = id; this.lat = lat; this.lon = lon; this.met = met; this.tags = tags; } public long getId() { return this.id; } public void setId(long id) { this.id = id; } public Double getLat() { return this.lat; } public void setLat(Double lat) { this.lat = lat; } public Double getLon() { return this.lon; } public void setLon(Double lon) { this.lon = lon; } public Metadata getMet() { return this.met; } public void setMet(Metadata met) { this.met = met; } public ArrayList<Tag> getTags() { return this.tags; } public void setTags(ArrayList<Tag> tags) { this.tags = tags; } public Node id(long id) { setId(id); return this; } public Node lat(Double lat) { setLat(lat); return this; } public Node lon(Double lon) { setLon(lon); return this; } public Node met(Metadata met) { setMet(met); return this; } public Node tags(ArrayList<Tag> tags) { setTags(tags); return this; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Node)) { return false; } Node node = (Node) o; return Objects.equals(id, node.id) && Objects.equals(lat, node.lat) && Objects.equals(lon, node.lon) && Objects.equals(met, node.met) && Objects.equals(tags, node.tags); } @Override public int hashCode() { return Objects.hash(id, lat, lon, met, tags); } @Override public String toString() { return "{" + " id='" + getId() + "'" + ", lat='" + getLat() + "'" + ", lon='" + getLon() + "'" + ", met='" + getMet() + "'" + ", tags='" + getTags() + "'" + "}"; } }
19.790323
110
0.616137
b12933cad7243bb67c9574b98cfcb4a8c48f03cc
1,877
package test; import java.util.Map; /** * @Author: 杨长江 * @Description: * @Date: 2019/3/20 9:34 */ public class Parm { private int a; private String b; private Map<String,Object> p ; private San san; public Parm(int a, String b, Map<String, Object> p, San san) { this.a = a; this.b = b; this.p = p; this.san = san; } public int getA() { return a; } public void setA(int a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } public Map<String, Object> getP() { return p; } public void setP(Map<String, Object> p) { this.p = p; } public San getSan() { return san; } public void setSan(San san) { this.san = san; } @Override public String toString() { return "Parm{" + "a=" + a + ", b='" + b + '\'' + ", p=" + p + ", san=" + san + '}'; } } class San { private String name; private int age; private boolean sex; public San(String name, int age, boolean sex) { this.name = name; this.age = age; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isSex() { return sex; } public void setSex(boolean sex) { this.sex = sex; } @Override public String toString() { return "San{" + "name='" + name + '\'' + ", age=" + age + ", sex=" + sex + '}'; } }
16.758929
66
0.449121
016c23b0c46405e2046b8e08b1f189faff6a760b
3,873
package ch.admin.geo.schemas.bj.tgbv.gbbasistypen._2; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for MutationType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="MutationType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element ref="{http://schemas.geo.admin.ch/BJ/TGBV/GBBasisTypen/2.1}Anmeldung"/&gt; * &lt;element ref="{http://schemas.geo.admin.ch/BJ/TGBV/GBBasisTypen/2.1}Mutationsinhalt" minOccurs="0"/&gt; * &lt;element ref="{http://schemas.geo.admin.ch/BJ/TGBV/GBBasisTypen/2.1}extensions" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MutationType", propOrder = { "anmeldung", "mutationsinhalt", "extensions" }) public class MutationType { @XmlElement(name = "Anmeldung", required = true) protected Anmeldung anmeldung; @XmlElement(name = "Mutationsinhalt") protected Mutationsinhalt mutationsinhalt; protected Extensions extensions; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; /** * Gets the value of the anmeldung property. * * @return * possible object is * {@link Anmeldung } * */ public Anmeldung getAnmeldung() { return anmeldung; } /** * Sets the value of the anmeldung property. * * @param value * allowed object is * {@link Anmeldung } * */ public void setAnmeldung(Anmeldung value) { this.anmeldung = value; } /** * Gets the value of the mutationsinhalt property. * * @return * possible object is * {@link Mutationsinhalt } * */ public Mutationsinhalt getMutationsinhalt() { return mutationsinhalt; } /** * Sets the value of the mutationsinhalt property. * * @param value * allowed object is * {@link Mutationsinhalt } * */ public void setMutationsinhalt(Mutationsinhalt value) { this.mutationsinhalt = value; } /** * Gets the value of the extensions property. * * @return * possible object is * {@link Extensions } * */ public Extensions getExtensions() { return extensions; } /** * Sets the value of the extensions property. * * @param value * allowed object is * {@link Extensions } * */ public void setExtensions(Extensions value) { this.extensions = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
25.313725
117
0.603408
40f166172cb6b64f7d9cf866ee397853965ce1a1
1,187
package com.xhh.demo.http.observer; import java.util.Enumeration; import java.util.Vector; /** * 具体主题(ConcreteSubject)角色 * * <p>保存对具体观察者对象有用的内部状态;在这种内部状态改变时给其观察者发出一个通知;具体主题角色又叫作具体被观察者角色 * * @author tiger * @version 1.0.0 createTime: 15/3/6 上午9:09 * @since 1.6 */ public class ConcreteSubject implements Subject { /** * 增加一个观察者 * * @param observer 观察者 */ @Override public void attach(Observer observer) { observersVector.addElement(observer); } /** * 删除一个观察者 * * @param observer 观察者 */ @Override public void detach(Observer observer) { observersVector.removeElement(observer); } /** * 通知观察者 */ @Override public void notifyObservers() { Enumeration enumeration = observers(); while (enumeration.hasMoreElements()) { ((Observer)enumeration.nextElement()).update(); } } /** * 数据转换 * * @return Enumeration */ public Enumeration observers() { return ((Vector)observersVector.clone()).elements(); } /** 存储观察者 */ private Vector<Observer> observersVector = new Vector<Observer>(); }
19.783333
70
0.604044
9246b614a2243185558027b5276d874acb9cc56b
3,998
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.glass.glassdesign2.menu; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.android.glass.glassdesign2.R; import com.example.android.glass.glassdesign2.SplashActivity; import com.example.android.glass.glassdesign2.databinding.MenuItemBinding; import java.util.List; /** * Adapter for the menu horizontal recycler view. */ public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> { private final List<GlassMenuItem> menuItems; private final Context context; MenuAdapter(List<GlassMenuItem> menuItems, Context context) { this.menuItems = menuItems; this.context = context; } @NonNull @Override public MenuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new MenuViewHolder(MenuItemBinding.inflate( LayoutInflater.from(parent.getContext()), parent, false)); } @Override public void onBindViewHolder(@NonNull MenuViewHolder menuViewHolder, int position) { menuViewHolder.bind(menuItems.get(position)); setFadeAnimation(menuViewHolder.itemView); TextView textView = menuViewHolder.binding.textView; ImageView imageView = menuViewHolder.binding.imageView; /* switch (SplashActivity.color_code){ case 1: textView.setTextColor(context.getResources().getColor(R.color.design_green)); imageView.setColorFilter(context.getResources().getColor(R.color.design_green)); break; case 2: textView.setTextColor(context.getResources().getColor(R.color.design_red)); imageView.setColorFilter(context.getResources().getColor(R.color.design_red)); break; case 3: textView.setTextColor(context.getResources().getColor(R.color.design_yellow)); imageView.setColorFilter(context.getResources().getColor(R.color.design_yellow)); break; case 4: textView.setTextColor(context.getResources().getColor(R.color.design_blue)); imageView.setColorFilter(context.getResources().getColor(R.color.design_blue)); break; case 5: textView.setTextColor(context.getResources().getColor(R.color.design_orange)); imageView.setColorFilter(context.getResources().getColor(R.color.design_orange)); break; case 6: textView.setTextColor(context.getResources().getColor(R.color.design_purple)); imageView.setColorFilter(context.getResources().getColor(R.color.design_purple)); break; } */ } @Override public int getItemCount() { return menuItems.size(); } static class MenuViewHolder extends RecyclerView.ViewHolder { private MenuItemBinding binding; public MenuViewHolder(@NonNull MenuItemBinding binding) { super(binding.getRoot()); this.binding = binding; } public void bind(GlassMenuItem glassMenuItem) { binding.setItem(glassMenuItem); binding.executePendingBindings(); } } public void setFadeAnimation(View view) { AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f); anim.setDuration(500); view.startAnimation(anim); } }
30.992248
89
0.736618
08bd299b31cae2049bf2c5a809d0c953b94f8f7e
2,736
package spacepirates.breadbox; import org.junit.*; import static org.junit.Assert.*; import spacepirates.breadbox.model.LocationDatabase; import spacepirates.breadbox.model.Location; import java.util.ArrayList; import java.util.List; public class GetLocationByNameTest { private final Location nullLocation = new Location.LocationBuilder("No Locations") .type("none") .latitude(0.0) .longitude(0.0) .address("Not Found") .phoneNumber("000-000-0000") .build(); @Test public void NoLocationsReturnsNullLocation() { LocationDatabase db = new LocationDatabase(new ArrayList<Location>()); assertEquals(nullLocation, db.getLocationByName("Alex")); } @Test public void LookForLocationNotInDatabase() { Location fun = new Location.LocationBuilder("No Locations") .type("none") .latitude(0.0) .longitude(0.0) .address("Not Found") .phoneNumber("000-000-0000") .build(); ArrayList<Location> ls = new ArrayList<>(); ls.add(fun); LocationDatabase db = new LocationDatabase(ls); assertEquals(db.getLocationByName("Boring"), nullLocation); } @Test public void FindLocationInListOfOne() { Location fun = new Location.LocationBuilder("No Locations") .type("none") .latitude(0.0) .longitude(0.0) .address("Not Found") .phoneNumber("000-000-0000") .build(); ArrayList<Location> ls = new ArrayList<>(); ls.add(fun); LocationDatabase db = new LocationDatabase(ls); assertEquals(db.getLocationByName("Fun Location"), fun); } @Test public void FindLocationInLongList() { ArrayList<Location> longList = new ArrayList<>(); String name = "L"; for (int i = 0; i < 100; i++, name += "L") { longList.add(new Location.LocationBuilder("No Locations") .type("none") .latitude(0.0) .longitude(0.0) .address("Not Found") .phoneNumber("000-000-0000") .build()); } Location last = new Location.LocationBuilder("Last One") .type("none") .latitude(0.0) .longitude(0.0) .address("Not Found") .phoneNumber("000-000-0000") .build(); longList.add(last); LocationDatabase db = new LocationDatabase(longList); assertEquals(last, db.getLocationByName("Last One")); } }
33.777778
86
0.553728
5e6b3b286013b640de0da199b774e75c8ff75302
6,524
package org.checkerframework.checker.regex.classic; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import org.checkerframework.checker.regex.qual.Regex; import org.checkerframework.dataflow.analysis.ConditionalTransferResult; import org.checkerframework.dataflow.analysis.RegularTransferResult; import org.checkerframework.dataflow.analysis.TransferInput; import org.checkerframework.dataflow.analysis.TransferResult; import org.checkerframework.dataflow.analysis.FlowExpressions.Receiver; import org.checkerframework.dataflow.cfg.node.ClassNameNode; import org.checkerframework.dataflow.cfg.node.IntegerLiteralNode; import org.checkerframework.dataflow.cfg.node.MethodAccessNode; import org.checkerframework.dataflow.cfg.node.MethodInvocationNode; import org.checkerframework.dataflow.cfg.node.Node; import org.checkerframework.framework.flow.CFAbstractTransfer; import org.checkerframework.framework.flow.CFStore; import org.checkerframework.framework.flow.CFValue; import org.checkerframework.framework.util.FlowExpressionParseUtil; import org.checkerframework.framework.util.FlowExpressionParseUtil.FlowExpressionContext; import org.checkerframework.framework.util.FlowExpressionParseUtil.FlowExpressionParseException; import org.checkerframework.javacutil.AnnotationUtils; import org.checkerframework.javacutil.ElementUtils; public class RegexTransfer extends CFAbstractTransfer<CFValue, CFStore, RegexTransfer> { private static final String IS_REGEX_METHOD_NAME = "isRegex"; private static final String AS_REGEX_METHOD_NAME = "asRegex"; /** Like super.analysis, but more specific type. */ protected RegexAnalysis analysis; public RegexTransfer(RegexAnalysis analysis) { super(analysis); this.analysis = analysis; } // TODO: These are special cases for isRegex(String, int) and asRegex(String, int). // They should be replaced by adding an @EnsuresQualifierIf annotation that supports // specifying attributes. @Override public TransferResult<CFValue, CFStore> visitMethodInvocation( MethodInvocationNode n, TransferInput<CFValue, CFStore> in) { RegexClassicAnnotatedTypeFactory factory = (RegexClassicAnnotatedTypeFactory) analysis .getTypeFactory(); TransferResult<CFValue, CFStore> result = super.visitMethodInvocation( n, in); // refine result for some helper methods MethodAccessNode target = n.getTarget(); ExecutableElement method = target.getMethod(); Node receiver = target.getReceiver(); if (!(receiver instanceof ClassNameNode)) { return result; } ClassNameNode cn = (ClassNameNode) receiver; String receiverName = cn.getElement().toString(); if (isRegexUtil(receiverName)) { if (ElementUtils.matchesElement(method, IS_REGEX_METHOD_NAME, String.class, int.class)) { // RegexUtil.isRegex(s, groups) method // (No special case is needed for isRegex(String) because of // the annotation on that method's definition.) CFStore thenStore = result.getRegularStore(); CFStore elseStore = thenStore.copy(); ConditionalTransferResult<CFValue, CFStore> newResult = new ConditionalTransferResult<>( result.getResultValue(), thenStore, elseStore); FlowExpressionContext context = FlowExpressionParseUtil .buildFlowExprContextForUse(n, factory.getContext()); try { Receiver firstParam = FlowExpressionParseUtil.parse( "#1", context, factory.getPath(n.getTree())); // add annotation with correct group count (if possible, // regex annotation without count otherwise) Node count = n.getArgument(1); if (count instanceof IntegerLiteralNode) { IntegerLiteralNode iln = (IntegerLiteralNode) count; Integer groupCount = iln.getValue(); AnnotationMirror regexAnnotation = factory.createRegexAnnotation(groupCount); thenStore.insertValue(firstParam, regexAnnotation); } else { AnnotationMirror regexAnnotation = AnnotationUtils .fromClass(factory.getElementUtils(), Regex.class); thenStore.insertValue(firstParam, regexAnnotation); } } catch (FlowExpressionParseException e) { assert false; } return newResult; } else if (ElementUtils.matchesElement(method, AS_REGEX_METHOD_NAME, String.class, int.class)) { // RegexUtil.asRegex(s, groups) method // (No special case is needed for asRegex(String) because of // the annotation on that method's definition.) // add annotation with correct group count (if possible, // regex annotation without count otherwise) AnnotationMirror regexAnnotation; Node count = n.getArgument(1); if (count instanceof IntegerLiteralNode) { IntegerLiteralNode iln = (IntegerLiteralNode) count; Integer groupCount = iln.getValue(); regexAnnotation = factory .createRegexAnnotation(groupCount); } else { regexAnnotation = AnnotationUtils.fromClass( factory.getElementUtils(), Regex.class); } CFValue newResultValue = analysis .createSingleAnnotationValue(regexAnnotation, result.getResultValue().getType() .getUnderlyingType()); return new RegularTransferResult<>(newResultValue, result.getRegularStore()); } } return result; }; /** * Returns true if the given receiver is a class named "RegexUtil". */ private boolean isRegexUtil(String receiver) { return receiver.equals("RegexUtil") || receiver.endsWith(".RegexUtil"); } }
48.686567
104
0.641478
aa1504cf3cf2a5cbd54c0771092a14129d094b87
1,843
/****************************************************************************** * ~ Copyright (c) 2018 [[email protected] | https://github.com/Jasonandy] * * ~ * * ~ 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 cn.ucaner.netty.rpc.test.client; import java.util.List; /** * @Package:cn.ucaner.netty.rpc.test.client * @ClassName:PersonService * @Description: <p> PersonService </p> * @Author: - luxiaoxun https://github.com/luxiaoxun/NettyRpc * @Modify By: * @Modify marker: * @version V1.0 */ public interface PersonService { /** * @Description: GetTestPerson * @param name * @param num * @return List<Person> */ List<Person> GetTestPerson(String name, int num); /** * @Description: sayHelloNettyRpc * @Autor: Jason - [email protected] */ void sayHelloNettyRpc(int num); }
40.955556
80
0.480738
22b538c83d25a029266583e1e6402d9b74e10b7c
2,003
package email.tianlangstudio.aliyun.com.common.domain; import java.util.HashMap; /** * @ClassName: AjaxResult * @Description: TODO(ajax操作消息提醒) * @author fuce * @date 2018年8月18日 * */ public class AjaxResult extends HashMap<String, Object> { private static final long serialVersionUID = 1L; /** * 初始化一个新创建的 Message 对象 */ public AjaxResult() { } /** * 返回错误消息 * * @return 错误消息 */ public static AjaxResult error() { return error(1, "操作失败"); } /** * 返回错误消息 * * @param msg 内容 * @return 错误消息 */ public static AjaxResult error(String msg) { return error(500, msg); } /** * 返回错误消息 * * @param code 错误码 * @param msg 内容 * @return 错误消息 */ public static AjaxResult error(int code, String msg) { AjaxResult json = new AjaxResult(); json.put("code", code); json.put("msg", msg); return json; } /** * 返回成功消息 * * @param msg 内容 * @return 成功消息 */ public static AjaxResult success(String msg) { AjaxResult json = new AjaxResult(); json.put("msg", msg); json.put("code", 200); json.put("success", true); return json; } /** * 返回成功消息 * * @return 成功消息 */ public static AjaxResult success() { return AjaxResult.success("操作成功"); } public static AjaxResult successData(int code, Object value){ AjaxResult json = new AjaxResult(); json.put("code", code); json.put("data", value); return json; } public static AjaxResult successData(Object value){ return success().put("data", value); } /** * 返回成功消息 * * @param key 键值 * @param value 内容 * @return 成功消息 */ @Override public AjaxResult put(String key, Object value) { super.put(key, value); return this; } }
18.209091
65
0.528208
5cfd37844027478194beea4f71f1f5ccab303ed7
331
package com.wfl.emps; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringbootempApplication { public static void main(String[] args) { SpringApplication.run(SpringbootempApplication.class, args); } }
23.642857
68
0.794562
479425ff7068e8c94e70a8628f86add39c90985b
460
package com.dungeonstory.ui.view.admin.grid; import com.dungeonstory.backend.data.CreatureType; import com.dungeonstory.ui.util.DSTheme; public class CreatureTypeGrid extends DSGrid<CreatureType> { private static final long serialVersionUID = 7979077646352869311L; public CreatureTypeGrid() { super(); addColumn(CreatureType::getName).setCaption("Nom").setId("name").setStyleGenerator(item -> DSTheme.TEXT_CENTER_ALIGNED); } }
28.75
128
0.758696
7fc201c5243804873ba59750f07ebd1a8bff80b0
16,758
/* * Copyright (C) 2016 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.android.tv.dvr.ui; import android.annotation.TargetApi; import android.app.FragmentManager; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.util.LongSparseArray; import androidx.leanback.app.GuidedStepFragment; import androidx.leanback.widget.GuidanceStylist.Guidance; import androidx.leanback.widget.GuidedAction; import androidx.leanback.widget.GuidedActionsStylist; import com.android.tv.R; import com.android.tv.TvSingletons; import com.android.tv.data.ChannelDataManager; import com.android.tv.data.ChannelImpl; import com.android.tv.data.api.Channel; import com.android.tv.data.api.Program; import com.android.tv.dvr.DvrDataManager; import com.android.tv.dvr.DvrManager; import com.android.tv.dvr.data.ScheduledRecording; import com.android.tv.dvr.data.SeasonEpisodeNumber; import com.android.tv.dvr.data.SeriesRecording; import com.android.tv.dvr.data.SeriesRecording.ChannelOption; import com.android.tv.dvr.recorder.SeriesRecordingScheduler; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** Fragment for DVR series recording settings. */ @TargetApi(Build.VERSION_CODES.N) @SuppressWarnings("AndroidApiChecker") // TODO(b/32513850) remove when error prone is updated public class DvrSeriesSettingsFragment extends GuidedStepFragment implements DvrDataManager.SeriesRecordingListener { private static final String TAG = "SeriesSettingsFragment"; private static final long ACTION_ID_PRIORITY = 10; private static final long ACTION_ID_CHANNEL = 11; private static final long SUB_ACTION_ID_CHANNEL_ALL = 102; // Each channel's action id = SUB_ACTION_ID_CHANNEL_ONE_BASE + channel id private static final long SUB_ACTION_ID_CHANNEL_ONE_BASE = 500; private DvrDataManager mDvrDataManager; private SeriesRecording mSeriesRecording; private long mSeriesRecordingId; @ChannelOption int mChannelOption; private long mSelectedChannelId; private int mBackStackCount; private boolean mShowViewScheduleOptionInDialog; private Program mCurrentProgram; private String mFragmentTitle; private String mSeriesRecordingTitle; private String mProrityActionTitle; private String mProrityActionHighestText; private String mProrityActionLowestText; private String mChannelsActionTitle; private String mChannelsActionAllText; private LongSparseArray<Channel> mId2Channel = new LongSparseArray<>(); private List<Channel> mChannels = new ArrayList<>(); private List<Program> mPrograms; private GuidedAction mPriorityGuidedAction; private GuidedAction mChannelsGuidedAction; @Override public void onAttach(Context context) { super.onAttach(context); mBackStackCount = getFragmentManager().getBackStackEntryCount(); mDvrDataManager = TvSingletons.getSingletons(context).getDvrDataManager(); mSeriesRecordingId = getArguments().getLong(DvrSeriesSettingsActivity.SERIES_RECORDING_ID); mSeriesRecording = mDvrDataManager.getSeriesRecording(mSeriesRecordingId); if (mSeriesRecording == null) { getActivity().finish(); return; } mSeriesRecordingTitle = mSeriesRecording.getTitle(); mShowViewScheduleOptionInDialog = getArguments() .getBoolean(DvrSeriesSettingsActivity.SHOW_VIEW_SCHEDULE_OPTION_IN_DIALOG); mCurrentProgram = getArguments().getParcelable(DvrSeriesSettingsActivity.CURRENT_PROGRAM); mDvrDataManager.addSeriesRecordingListener(this); mPrograms = (List<Program>) BigArguments.getArgument(DvrSeriesSettingsActivity.PROGRAM_LIST); BigArguments.reset(); if (mPrograms == null) { getActivity().finish(); return; } Set<Long> channelIds = new HashSet<>(); ChannelDataManager channelDataManager = TvSingletons.getSingletons(context).getChannelDataManager(); for (Program program : mPrograms) { long channelId = program.getChannelId(); if (channelIds.add(channelId)) { Channel channel = channelDataManager.getChannel(channelId); if (channel != null) { mId2Channel.put(channel.getId(), channel); mChannels.add(channel); } } } mChannelOption = mSeriesRecording.getChannelOption(); mSelectedChannelId = Channel.INVALID_ID; if (mChannelOption == SeriesRecording.OPTION_CHANNEL_ONE) { Channel channel = channelDataManager.getChannel(mSeriesRecording.getChannelId()); if (channel != null) { mSelectedChannelId = channel.getId(); } else { mChannelOption = SeriesRecording.OPTION_CHANNEL_ALL; } } mChannels.sort(ChannelImpl.CHANNEL_NUMBER_COMPARATOR); mFragmentTitle = getString(R.string.dvr_series_settings_title); mProrityActionTitle = getString(R.string.dvr_series_settings_priority); mProrityActionHighestText = getString(R.string.dvr_series_settings_priority_highest); mProrityActionLowestText = getString(R.string.dvr_series_settings_priority_lowest); mChannelsActionTitle = getString(R.string.dvr_series_settings_channels); mChannelsActionAllText = getString(R.string.dvr_series_settings_channels_all); } @Override public void onResume() { super.onResume(); // To avoid the order of series's priority has changed, but series doesn't get update. updatePriorityGuidedAction(); } @Override public void onDetach() { super.onDetach(); mDvrDataManager.removeSeriesRecordingListener(this); } @Override public void onDestroy() { if (getFragmentManager().getBackStackEntryCount() == mBackStackCount && getArguments() .getBoolean(DvrSeriesSettingsActivity.REMOVE_EMPTY_SERIES_RECORDING)) { mDvrDataManager.checkAndRemoveEmptySeriesRecording(mSeriesRecordingId); } super.onDestroy(); } @Override public Guidance onCreateGuidance(Bundle savedInstanceState) { String title = mFragmentTitle; return new Guidance(title, null, mSeriesRecordingTitle, null); } @Override public void onCreateActions(List<GuidedAction> actions, Bundle savedInstanceState) { mPriorityGuidedAction = new GuidedAction.Builder(getActivity()) .id(ACTION_ID_PRIORITY) .title(mProrityActionTitle) .build(); actions.add(mPriorityGuidedAction); mChannelsGuidedAction = new GuidedAction.Builder(getActivity()) .id(ACTION_ID_CHANNEL) .title(mChannelsActionTitle) .subActions(buildChannelSubAction()) .build(); actions.add(mChannelsGuidedAction); updateChannelsGuidedAction(false); } @Override public void onCreateButtonActions(List<GuidedAction> actions, Bundle savedInstanceState) { actions.add( new GuidedAction.Builder(getActivity()) .clickAction(GuidedAction.ACTION_ID_OK) .build()); actions.add( new GuidedAction.Builder(getActivity()) .clickAction(GuidedAction.ACTION_ID_CANCEL) .build()); } @Override public void onGuidedActionClicked(GuidedAction action) { long actionId = action.getId(); if (actionId == GuidedAction.ACTION_ID_OK) { if (mChannelOption != mSeriesRecording.getChannelOption() || mSeriesRecording.isStopped() || (mChannelOption == SeriesRecording.OPTION_CHANNEL_ONE && mSeriesRecording.getChannelId() != mSelectedChannelId)) { SeriesRecording.Builder builder = SeriesRecording.buildFrom(mSeriesRecording) .setChannelOption(mChannelOption) .setState(SeriesRecording.STATE_SERIES_NORMAL); if (mSelectedChannelId != Channel.INVALID_ID) { builder.setChannelId(mSelectedChannelId); } DvrManager dvrManager = TvSingletons.getSingletons(getContext()).getDvrManager(); dvrManager.updateSeriesRecording(builder.build()); if (mCurrentProgram != null && (mChannelOption == SeriesRecording.OPTION_CHANNEL_ALL || mSelectedChannelId == mCurrentProgram.getChannelId())) { dvrManager.addSchedule(mCurrentProgram); } updateSchedulesToSeries(); showConfirmDialog(); } else { showConfirmDialog(); } } else if (actionId == GuidedAction.ACTION_ID_CANCEL) { finishGuidedStepFragments(); } else if (actionId == ACTION_ID_PRIORITY) { FragmentManager fragmentManager = getFragmentManager(); DvrPrioritySettingsFragment fragment = new DvrPrioritySettingsFragment(); Bundle args = new Bundle(); args.putLong( DvrPrioritySettingsFragment.COME_FROM_SERIES_RECORDING_ID, mSeriesRecording.getId()); fragment.setArguments(args); GuidedStepFragment.add(fragmentManager, fragment, R.id.dvr_settings_view_frame); } } @Override public boolean onSubGuidedActionClicked(GuidedAction action) { long actionId = action.getId(); if (actionId == SUB_ACTION_ID_CHANNEL_ALL) { mChannelOption = SeriesRecording.OPTION_CHANNEL_ALL; mSelectedChannelId = Channel.INVALID_ID; updateChannelsGuidedAction(true); return true; } else if (actionId > SUB_ACTION_ID_CHANNEL_ONE_BASE) { mChannelOption = SeriesRecording.OPTION_CHANNEL_ONE; mSelectedChannelId = actionId - SUB_ACTION_ID_CHANNEL_ONE_BASE; updateChannelsGuidedAction(true); return true; } return false; } @Override public GuidedActionsStylist onCreateButtonActionsStylist() { return new DvrGuidedActionsStylist(true); } private void updateChannelsGuidedAction(boolean notifyActionChanged) { if (mChannelOption == SeriesRecording.OPTION_CHANNEL_ALL) { mChannelsGuidedAction.setDescription(mChannelsActionAllText); } else if (mId2Channel.get(mSelectedChannelId) != null) { mChannelsGuidedAction.setDescription( mId2Channel.get(mSelectedChannelId).getDisplayText()); } if (notifyActionChanged) { notifyActionChanged(findActionPositionById(ACTION_ID_CHANNEL)); } } private void updatePriorityGuidedAction() { int totalSeriesCount = 0; int priorityOrder = 0; for (SeriesRecording seriesRecording : mDvrDataManager.getSeriesRecordings()) { if (seriesRecording.getState() == SeriesRecording.STATE_SERIES_NORMAL || seriesRecording.getId() == mSeriesRecording.getId()) { ++totalSeriesCount; } if (seriesRecording.getState() == SeriesRecording.STATE_SERIES_NORMAL && seriesRecording.getId() != mSeriesRecording.getId() && seriesRecording.getPriority() > mSeriesRecording.getPriority()) { ++priorityOrder; } } if (priorityOrder == 0) { mPriorityGuidedAction.setDescription(mProrityActionHighestText); } else if (priorityOrder >= totalSeriesCount - 1) { mPriorityGuidedAction.setDescription(mProrityActionLowestText); } else { mPriorityGuidedAction.setDescription( getString(R.string.dvr_series_settings_priority_rank, priorityOrder + 1)); } notifyActionChanged(findActionPositionById(ACTION_ID_PRIORITY)); } private void updateSchedulesToSeries() { List<Program> recordingCandidates = new ArrayList<>(); Set<SeasonEpisodeNumber> scheduledEpisodes = new HashSet<>(); for (ScheduledRecording r : mDvrDataManager.getScheduledRecordings(mSeriesRecordingId)) { if (r.getState() != ScheduledRecording.STATE_RECORDING_FAILED && r.getState() != ScheduledRecording.STATE_RECORDING_CLIPPED) { scheduledEpisodes.add( new SeasonEpisodeNumber( r.getSeriesRecordingId(), r.getSeasonNumber(), r.getEpisodeNumber())); } } for (Program program : mPrograms) { // Removes current programs and scheduled episodes out, matches the channel option. if (program.getStartTimeUtcMillis() >= System.currentTimeMillis() && mSeriesRecording.matchProgram(program) && !scheduledEpisodes.contains( new SeasonEpisodeNumber( mSeriesRecordingId, program.getSeasonNumber(), program.getEpisodeNumber()))) { recordingCandidates.add(program); } } if (recordingCandidates.isEmpty()) { return; } List<Program> programsToSchedule = SeriesRecordingScheduler.pickOneProgramPerEpisode( mDvrDataManager, Collections.singletonList(mSeriesRecording), recordingCandidates) .get(mSeriesRecordingId); if (!programsToSchedule.isEmpty()) { TvSingletons.getSingletons(getContext()) .getDvrManager() .addScheduleToSeriesRecording(mSeriesRecording, programsToSchedule); } } private List<GuidedAction> buildChannelSubAction() { List<GuidedAction> channelSubActions = new ArrayList<>(); channelSubActions.add( new GuidedAction.Builder(getActivity()) .id(SUB_ACTION_ID_CHANNEL_ALL) .title(mChannelsActionAllText) .build()); for (Channel channel : mChannels) { channelSubActions.add( new GuidedAction.Builder(getActivity()) .id(SUB_ACTION_ID_CHANNEL_ONE_BASE + channel.getId()) .title(channel.getDisplayText()) .build()); } return channelSubActions; } private void showConfirmDialog() { DvrUiHelper.startSeriesScheduledDialogActivity( getContext(), mSeriesRecording, mShowViewScheduleOptionInDialog, mPrograms); finishGuidedStepFragments(); } @Override public void onSeriesRecordingAdded(SeriesRecording... seriesRecordings) {} @Override public void onSeriesRecordingRemoved(SeriesRecording... seriesRecordings) { for (SeriesRecording series : seriesRecordings) { if (series.getId() == mSeriesRecording.getId()) { finishGuidedStepFragments(); return; } } } @Override public void onSeriesRecordingChanged(SeriesRecording... seriesRecordings) { for (SeriesRecording seriesRecording : seriesRecordings) { if (seriesRecording.getId() == mSeriesRecordingId) { mSeriesRecording = seriesRecording; updatePriorityGuidedAction(); return; } } } }
42.75
99
0.641306
380b51a08f28df45f9b0a1c4a80ca0d230b05311
1,469
package net.officefloor.nosql.cosmosdb.test; import java.util.concurrent.atomic.AtomicInteger; import com.azure.cosmos.CosmosDatabase; import net.officefloor.frame.api.manage.OfficeFloor; /** * Reference to a test {@link CosmosDatabase}. * * @author Daniel Sagenschneider */ public class CosmosTestDatabase { /** * Test {@link CosmosDatabase} prefix. */ private static final String TEST_DATABASE_PREFIX = "Test" + OfficeFloor.class.getSimpleName(); /** * Next unique index for a test {@link CosmosDatabase}. */ private static final AtomicInteger nextUniqueId = new AtomicInteger(0); /** * Generates the next test {@link CosmosDatabase} Id. * * @return Next test {@link CosmosDatabase} Id. */ private static String generateNextTestDatabaseId() { return TEST_DATABASE_PREFIX + nextUniqueId.incrementAndGet() + "Time" + System.currentTimeMillis(); } /** * Id of the test {@link CosmosDatabase}. */ private final String databaseId; /** * Instantiate. * * @param databaseId Allow specifying the {@link CosmosDatabase} Id. */ public CosmosTestDatabase(String databaseId) { this.databaseId = databaseId; } /** * Instantiate for new {@link CosmosDatabase} Id. */ public CosmosTestDatabase() { this(generateNextTestDatabaseId()); } /** * Obtains the test {@link CosmosDatabase} Id. * * @return Test {@link CosmosDatabase} Id. */ public String getTestDatabaseId() { return this.databaseId; } }
22.6
101
0.710007
5625d4234e47270157080c809d41bd984ec00bd2
8,995
/* * Copyright (c) 2017 Nova Ordis LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.novaordis.windows.netstat; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.text.ParseException; import java.text.SimpleDateFormat; 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 java.util.regex.Matcher; import java.util.regex.Pattern; /** * Windows netstat output parsing logic. * * @author Ovidiu Feodorov <[email protected]> * @since 9/9/17 */ public class Netstat { // Constants ------------------------------------------------------------------------------------------------------- public static final Map<String, Integer> STANDARD_PORTS = new HashMap<>(); public static final Set<String> LOCAL_HOST_ADDRESSES = new HashSet<>(); static { STANDARD_PORTS.put("ingreslock", 1524); STANDARD_PORTS.put("ms-sql-s", 1433); STANDARD_PORTS.put("nfsd-status", 1110); STANDARD_PORTS.put("ms-sna-base", 1478); STANDARD_PORTS.put("ms-sna-server", 1477); STANDARD_PORTS.put("wins", 1512); STANDARD_PORTS.put("pptconference", 1711); STANDARD_PORTS.put("pptp", 1723); STANDARD_PORTS.put("msiccp", 1731); STANDARD_PORTS.put("remote-winsock", 1745); STANDARD_PORTS.put("ms-streaming", 1755); STANDARD_PORTS.put("msmq", 1801); STANDARD_PORTS.put("msnp", 1863); STANDARD_PORTS.put("ssdp", 1900); STANDARD_PORTS.put("knetd", 2053); STANDARD_PORTS.put("man", 9535); // LOCAL_HOST_ADDRESSES.add("GBDC1-PLMPRD-1"); // LOCAL_HOST_ADDRESSES.add("10.103.0.130"); // LOCAL_HOST_ADDRESSES.add("127.0.0.1"); } // Static ---------------------------------------------------------------------------------------------------------- private static boolean headerDisplayed = false; public static void parse(String[] args) throws Exception { String filename = args[0]; File f = new File(filename); BufferedReader br = new BufferedReader(new FileReader(f)); String line; int lineNumber = 0; TimestampInfo currentTimestampInfo = null; Connection current = null; List<Connection> connections = new ArrayList<>(); while((line = br.readLine()) != null) { lineNumber ++; line = line.trim(); if (line.isEmpty()) { continue; } if (TimestampInfo.isDateLine(line)) { // // display the statistics for the previous reading // if (currentTimestampInfo != null) { displayStatistics(currentTimestampInfo, connections); // // reset data and prepare it for the next reading // connections.clear(); } currentTimestampInfo = new TimestampInfo(line); } else if (TimestampInfo.isTimeLine(line)) { //noinspection ConstantConditions currentTimestampInfo.setTime(line); } else if (line.startsWith(ConnectionType.TCP.name())) { if (current != null) { // // new connection report starts, save the current one // connections.add(current); } current = new Connection(lineNumber, line); } else if (current != null) { current.add(lineNumber, line); } } br.close(); if (currentTimestampInfo != null) { // // display statistics for the last reading // displayStatistics(currentTimestampInfo, connections); } } private static void displayStatistics(TimestampInfo ti, List<Connection> connections) { ConnectionState[] states = { ConnectionState.ESTABLISHED, ConnectionState.LISTENING, ConnectionState.TIME_WAIT, ConnectionState.CLOSED, ConnectionState.CLOSE_WAIT, ConnectionState.CLOSING, ConnectionState.FIN_WAIT_1, ConnectionState.FIN_WAIT_2, ConnectionState.LAST_ACK, ConnectionState.SYN_RECEIVED, ConnectionState.SYN_SENT, }; if (!headerDisplayed) { headerDisplayed = true; System.out.print("# time, "); for(ConnectionState s: states) { System.out.print(s.name() + " (total), "); } for(ConnectionState s: states) { System.out.print(s.name() + " (java), "); } System.out.println(); } System.out.print(TimestampInfo.TIMESTAMP_OUTPUT_FORMAT.format(ti.getTimestamp()) + ", "); for(ConnectionState s: states) { int c = getCount(connections, s, null); System.out.print(c + ", "); } for(ConnectionState s: states) { int c = getCount(connections, s, "java.exe"); System.out.print(c + ", "); } System.out.println(); } /** * @param process may be null, and in this case all connections in the given state are counted. */ private static int getCount(List<Connection> connections, ConnectionState state, String process) { int count = 0; for(Connection c: connections) { ConnectionState s = c.getState(); if (!s.equals(state)) { continue; } if (process == null) { count++; } else { String cp = c.getProcess(); if (process.equals(cp)) { count ++; } } } return count; } // Attributes ------------------------------------------------------------------------------------------------------ // Constructors ---------------------------------------------------------------------------------------------------- // Public ---------------------------------------------------------------------------------------------------------- // Package protected ----------------------------------------------------------------------------------------------- // Protected ------------------------------------------------------------------------------------------------------- // Private --------------------------------------------------------------------------------------------------------- // Inner classes --------------------------------------------------------------------------------------------------- private static class TimestampInfo { public static final Pattern DATE_PATTERN = Pattern.compile("^[0-3][0-9]/[0-1][0-9]/\\d\\d\\d\\d.*"); public static final Pattern TIME_PATTERN = Pattern.compile("^[0-2]\\d:\\d\\d.*"); public static final SimpleDateFormat TIMESTAMP_INPUT_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm"); public static final SimpleDateFormat TIMESTAMP_OUTPUT_FORMAT = new SimpleDateFormat("MM/dd/YY HH:mm"); /** * Return true if the line starts with date info. */ public static boolean isDateLine(String line) { Matcher m = DATE_PATTERN.matcher(line); return m.matches(); } /** * Return true if the line starts with date info. */ public static boolean isTimeLine(String line) { Matcher m = TIME_PATTERN.matcher(line); return m.matches(); } private String dateString; private String timeString; private long timestamp; public TimestampInfo(String line) { this.dateString = line.trim(); } public void setTime(String line) throws ParseException { this.timeString = line.trim(); String s = dateString + " " + timeString; this.timestamp = TIMESTAMP_INPUT_FORMAT.parse(s).getTime(); } public long getTimestamp() { return timestamp; } } }
28.738019
120
0.504058
830347079d8cf8844db7586debaccd81cb53ab5c
20,378
package com.moesif.servlet; import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import java.lang.*; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.moesif.api.models.*; import com.moesif.api.MoesifAPIClient; import com.moesif.api.http.client.APICallBack; import com.moesif.api.http.client.HttpContext; import com.moesif.api.controllers.APIController; import com.moesif.api.IpAddress; import com.moesif.api.BodyParser; import com.moesif.servlet.wrappers.LoggingHttpServletRequestWrapper; import com.moesif.servlet.wrappers.LoggingHttpServletResponseWrapper; import org.apache.commons.lang3.StringUtils; public class MoesifFilter implements Filter { private static final Logger logger = Logger.getLogger(MoesifFilter.class.toString()); private String applicationId; private MoesifConfiguration config; private MoesifAPIClient moesifApi; private boolean debug; private boolean logBody; private BatchProcessor batchProcessor = null; // Manages queue & provides a taskRunner to send events in batches. private int sendBatchJobAliveCounter = 0; // counter to check scheduled job is alive or not. // Timer for various tasks Timer updateConfigTimer = null; Timer sendBatchEventTimer = null; /** * Default Constructor, please set ApplicationId before use. */ public MoesifFilter() { this.setDebug(false); this.setLogBody(true); this.setConfigure( new MoesifConfigurationAdapter() ); } /** * Constructor * @param applicationId Required parameter: obtained from your moesif Account. */ public MoesifFilter(String applicationId) { this.setDebug(false); this.setLogBody(true); this.setConfigure( new MoesifConfigurationAdapter() ); this.setApplicationId(applicationId); } /** * Constructor * @param applicationId Required parameter: obtained from your moesif Account. * @param debug Flag for turning debug messages on. */ public MoesifFilter(String applicationId, boolean debug) { this.setDebug(debug); this.setLogBody(true); this.setConfigure( new MoesifConfigurationAdapter() ); this.setApplicationId(applicationId); } /** * Constructor * @param applicationId Required parameter: obtained from your moesif Account. * @param config MoesifConfiguration Object. */ public MoesifFilter(String applicationId, MoesifConfiguration config) { this.setDebug(false); this.setLogBody(true); this.setConfigure(config); this.setApplicationId(applicationId); } /** * Constructor * @param applicationId Required parameter: obtained from your moesif Account. * @param config MoesifConfiguration Object * @param debug boolean */ public MoesifFilter(String applicationId, MoesifConfiguration config, boolean debug) { this.setDebug(debug); this.setLogBody(true); this.setConfigure(config); this.setApplicationId(applicationId); } /** * Sets the Moesif Application Id. * @param applicationId Required parameter: obtained from your moesif Account. */ public void setApplicationId(String applicationId) { this.applicationId = applicationId; this.createMoesifApiClient(); } /*** * Creates Moesif API client for given application id. */ private void createMoesifApiClient() { this.moesifApi = new MoesifAPIClient(this.applicationId); } /** * Sets the MoesifConfiguration * @param config MoesifConfiguration Object */ public void setConfigure(MoesifConfiguration config) { this.config = config; } /** * Sets the debug flag * @param debug boolean */ public void setDebug(boolean debug) { this.debug = debug; } /** * Sets the logBody flag * @param logBody boolean */ public void setLogBody(boolean logBody) { this.logBody = logBody; } /** * Get the underlying APIController * @return Returns the APIController instance */ public APIController getAPI() { if (moesifApi != null) { return moesifApi.getAPI(); } return null; } @Override public void init(FilterConfig filterConfig) throws ServletException { logger.info("Initialized Moesif filter"); String appId = filterConfig.getInitParameter("application-id"); if (appId != null) { this.setApplicationId(appId); } String debug = filterConfig.getInitParameter("debug"); if (debug != null) { if (debug.equals("true")) { this.setDebug(true); } } String logBody = filterConfig.getInitParameter("logBody"); if (logBody != null) { if (logBody.equals("false")) { this.setLogBody(false); } } // Setup app config manager and run it immediately to load app config. AppConfigManager.getInstance().setMoesifApiClient(this.moesifApi, this.debug); AppConfigManager.getInstance().run(); // Initialize the batch event processor and timer tasks. this.initBatchProcessorAndStartJobs(); } @Override public void destroy() { // Drain the queue and stop the timer tasks. this.drainQueueAndStopJobs(); if (debug) { logger.info("Destroyed Moesif filter"); } } public void updateUser(UserModel userModel) throws Throwable{ if (this.moesifApi != null) { String userId = userModel.getUserId(); if (userId != null && !userId.isEmpty()) { try { moesifApi.getAPI().updateUser(userModel); } catch(Exception e) { if (debug) { logger.warning("Update User to Moesif failed " + e.toString()); } } } else { throw new IllegalArgumentException("To update an user, an userId field is required"); } } else { logger.warning("The application Id should be set before using MoesifFilter"); } } public void updateUsersBatch(List<UserModel> usersModel) throws Throwable{ List<UserModel> users = new ArrayList<UserModel>(); if (this.moesifApi != null) { for (UserModel user : usersModel) { String userId = user.getUserId(); if (userId != null && !userId.isEmpty()) { users.add(user); } else { throw new IllegalArgumentException("To update an user, an userId field is required"); } } } else { logger.warning("The application Id should be set before using MoesifFilter"); } if (!users.isEmpty()) { try { moesifApi.getAPI().updateUsersBatch(users); } catch (Exception e) { if (debug) { logger.warning("Update User to Moesif failed " + e.toString()); } } } } public void updateCompany(CompanyModel companyModel) throws Throwable{ if (this.moesifApi != null) { String companyId = companyModel.getCompanyId(); if (companyId != null && !companyId.isEmpty()) { try { moesifApi.getAPI().updateCompany(companyModel); } catch(Exception e) { if (debug) { logger.warning("Update Company to Moesif failed " + e.toString()); } } } else { throw new IllegalArgumentException("To update a company, a companyId field is required"); } } else { logger.warning("The application Id should be set before using MoesifFilter"); } } public void updateCompaniesBatch(List<CompanyModel> companiesModel) throws Throwable{ List<CompanyModel> companies = new ArrayList<CompanyModel>(); if (this.moesifApi != null) { for (CompanyModel company : companiesModel) { String companyId = company.getCompanyId(); if (companyId != null && !companyId.isEmpty()) { companies.add(company); } else { throw new IllegalArgumentException("To update a company, a companyId field is required"); } } } else { logger.warning("The application Id should be set before using MoesifFilter"); } if (!companies.isEmpty()) { try { moesifApi.getAPI().updateCompaniesBatch(companies); } catch (Exception e) { if (debug) { logger.warning("Update Companies to Moesif failed " + e.toString()); } } } } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (debug) { logger.info("filtering request"); } Date startDate = new Date(); if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { logger.warning("MoesifFilter was called for non HTTP requests"); filterChain.doFilter(request, response); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (config.skip(httpRequest, httpResponse)) { filterChain.doFilter(httpRequest, httpResponse); if (debug) { logger.warning("skipping request"); } return; } LoggingHttpServletRequestWrapper requestWrapper = new LoggingHttpServletRequestWrapper(httpRequest); LoggingHttpServletResponseWrapper responseWrapper = new LoggingHttpServletResponseWrapper(httpResponse); // Initialize transactionId String transactionId = null; if (!config.disableTransactionId) { String reqTransId = requestWrapper.getHeader("X-Moesif-Transaction-Id"); if (reqTransId != null && !reqTransId.isEmpty()) { transactionId = reqTransId; } else { transactionId = UUID.randomUUID().toString(); } // Add Transaction Id to the response model and response sent to the client responseWrapper.addHeader("X-Moesif-Transaction-Id", transactionId); } EventRequestModel eventRequestModel = getEventRequestModel(requestWrapper, startDate, config.getApiVersion(httpRequest, httpResponse), transactionId); // pass to next step in the chain. try { filterChain.doFilter(requestWrapper, responseWrapper); } finally { Date endDate = new Date(); EventResponseModel eventResponseModel = getEventResponseModel(responseWrapper, endDate); if (!(responseWrapper.getResponse() instanceof LoggingHttpServletResponseWrapper)) { sendEvent( eventRequestModel, eventResponseModel, config.identifyUser(httpRequest, httpResponse), config.identifyCompany(httpRequest, httpResponse), config.getSessionToken(httpRequest, httpResponse), config.getTags(httpRequest, httpResponse), config.getMetadata(httpRequest, httpResponse) ); } } } private EventRequestModel getEventRequestModel(LoggingHttpServletRequestWrapper requestWrapper, Date date, String apiVersion, String transactionId) { EventRequestBuilder eventRequestBuilder = new EventRequestBuilder(); // Add Transaction Id to the request model Map<String, String> reqHeaders = new HashMap<String, String>(0); if (transactionId != null) { reqHeaders = requestWrapper.addHeader("X-Moesif-Transaction-Id", transactionId); } else { reqHeaders = requestWrapper.getHeaders(); } eventRequestBuilder .time(date) .uri(getFullURL(requestWrapper)) .headers(reqHeaders) .verb(requestWrapper.getMethod()) .ipAddress(IpAddress.getClientIp( requestWrapper.getHeaders(), requestWrapper.getRemoteAddr() )); if (StringUtils.isNotEmpty(apiVersion)) { eventRequestBuilder.apiVersion(apiVersion); } String content = requestWrapper.getContent(); if (logBody && content != null && !content.isEmpty()) { BodyParser.BodyWrapper bodyWrapper = BodyParser.parseBody(requestWrapper.getHeaders(), content); eventRequestBuilder.body(bodyWrapper.body); eventRequestBuilder.transferEncoding(bodyWrapper.transferEncoding); } return eventRequestBuilder.build(); } private EventResponseModel getEventResponseModel(LoggingHttpServletResponseWrapper responseWrapper, Date date) { EventResponseBuilder eventResponseBuilder = new EventResponseBuilder(); eventResponseBuilder .time(date) .status(responseWrapper.getStatus()) .headers(responseWrapper.getHeaders()); String content = responseWrapper.getContent(); if (logBody && content != null && !content.isEmpty()) { BodyParser.BodyWrapper bodyWrapper = BodyParser.parseBody(responseWrapper.getHeaders(), content); eventResponseBuilder.body(bodyWrapper.body); eventResponseBuilder.transferEncoding(bodyWrapper.transferEncoding); } return eventResponseBuilder.build(); } /*** * Method to initialize the batch event processor and create jobs for automatic update of * app config and send events in batches. * Batch event processor maintains batch queue and a taskRunner method to * run scheduled task periodically to send events in batches. */ private void initBatchProcessorAndStartJobs() { // Create event batch processor for queueing and batching the events. this.batchProcessor = new BatchProcessor(this.moesifApi, this.config, this.debug); // Initialize the timer tasks - Create scheduled jobs this.scheduleAppConfigJob(); this.scheduleBatchEventsJob(); } /*** * Method to stop the scheduled jobs and drain the batch queue. * Batch event processor sends the leftover events present in queue * before stopping the scheduled jobs. */ public void drainQueueAndStopJobs() { // Cleanup/transfer the leftover queue events, if any before destroying the filter. this.batchProcessor.run(); // it's ok to run in main thread on destroy. // Stop the scheduled jobs try { if (debug) { logger.info("Stopping scheduled jobs."); } this.resetJobTimer(this.updateConfigTimer); this.resetJobTimer(this.sendBatchEventTimer); } catch (Exception e) { // ignore the error. } } /** * Method to create scheduled job for updating config periodically. */ private void scheduleAppConfigJob() { // Make sure there is none before creating the timer this.resetJobTimer(this.updateConfigTimer); this.updateConfigTimer = new Timer("moesif_update_config_job"); updateConfigTimer.schedule( AppConfigManager.getInstance(), 0, (long) this.batchProcessor.getUpdateConfigTime() * 1000 ); } /** * Method to create scheduled job for sending batch events periodically. */ private void scheduleBatchEventsJob() { // Make sure there is none before creating the timer this.resetJobTimer(this.sendBatchEventTimer); this.sendBatchEventTimer = new Timer("moesif_events_batch_job"); sendBatchEventTimer.schedule( this.batchProcessor, 0, (long) this.batchProcessor.getBatchMaxTime() * 1000 ); } /** * Method to reset scheduled job timer. * @param timer : Timer */ private void resetJobTimer(Timer timer) { if (timer != null) { timer.cancel(); timer.purge(); timer = null; } } private void rescheduleSendEventsJobIfNeeded() { // Check if batchJob is already running then return if (this.batchProcessor.isJobRunning()) { if (debug) { String msg = String.format("Send event job is in-progress."); logger.info(msg); } return; } // Check if we need to reschedule job to send batch events // if the last job runtime is more than 5 minutes. final long MAX_TARDINESS_SEND_EVENT_JOB = this.config.batchMaxTime * 60; // in seconds final long diff = new Date().getTime() - this.batchProcessor.scheduledExecutionTime(); final long seconds = TimeUnit.MILLISECONDS.toSeconds(diff); // Check Event job if (seconds > MAX_TARDINESS_SEND_EVENT_JOB) { if (debug) { String msg = String.format("Last send batchEvents job was executed %d minutes ago. Rescheduling job..", seconds/60); logger.info(msg); } // Restart send batch event job. scheduleBatchEventsJob(); } if (debug) { String msg = String.format("Last send batchEvents job was executed %d seconds ago.", seconds); logger.info(msg); } } /*** * Method to add event into a queue for batch-based event transfer. * The method can be used to just send the batched events, by passing EventModel as null. * @param maskedEvent: EventModel */ private void addEventToQueue(EventModel maskedEvent) { try { this.batchProcessor.addEvent(maskedEvent); sendBatchJobAliveCounter++; // Check send batchEvent job periodically based on counter if rescheduling is needed. if (sendBatchJobAliveCounter > 100) { if (this.debug) { logger.info("Check for liveness of taskRunner."); } this.rescheduleSendEventsJobIfNeeded(); sendBatchJobAliveCounter = 0; } } catch (Throwable e) { logger.warning("Failed to add event to the queue. " + e.toString()); } } private void sendEvent(EventRequestModel eventRequestModel, EventResponseModel eventResponseModel, String userId, String companyId, String sessionToken, String tags, Object metadata) { EventBuilder eb = new EventBuilder(); eb.request(eventRequestModel); eb.response(eventResponseModel); eb.direction("Incoming"); if (userId != null) { eb.userId(userId); } if (companyId != null) { eb.companyId(companyId); } if (sessionToken != null) { eb.sessionToken(sessionToken); } if (tags != null) { eb.tags(tags); } if (metadata != null) { eb.metadata(metadata); } EventModel event = eb.build(); if (this.moesifApi != null) { // actually send the event here. APICallBack<Object> callBack = new APICallBack<Object>() { public void onSuccess(HttpContext context, Object response) { if (debug) { logger.info("send to Moesif success"); } } public void onFailure(HttpContext context, Throwable error) { if (debug) { logger.info("send to Moesif error "); logger.info( error.toString()); } } }; try { EventModel maskedEvent = config.maskContent(event); if (maskedEvent == null) { logger.severe("maskContent() returned a null object, not allowed"); } // Generate random number double randomPercentage = Math.random() * 100; int samplingPercentage = AppConfigManager.getInstance().getSampleRate(userId, companyId); // Compare percentage to send event if (samplingPercentage >= randomPercentage) { maskedEvent.setWeight(moesifApi.getAPI().calculateWeight(samplingPercentage)); // Add the event to queue for batch-based transfer this.addEventToQueue(maskedEvent); } else { if(debug) { logger.info("Skipped Event due to SamplingPercentage " + samplingPercentage + " and randomPercentage " + randomPercentage); } } } catch(Throwable e) { if (debug) { logger.warning("add event to queue failed " + e); } } } else { logger.warning("The application Id should be set before using MoesifFilter"); } } static String getFullURL(HttpServletRequest request) { StringBuffer requestURL = request.getRequestURL(); String queryString = request.getQueryString(); if (requestURL == null) { return "/"; } else if (queryString == null) { return requestURL.toString(); } else { return requestURL.append('?').append(queryString).toString(); } } }
31.254601
151
0.664786
882eb7212056465e029385ffb81211b8765a34ff
10,010
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|pdfbox operator|. name|examples operator|. name|interactive operator|. name|form package|; end_package begin_import import|import name|java operator|. name|io operator|. name|File import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|pdfbox operator|. name|Loader import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|pdfbox operator|. name|pdmodel operator|. name|PDDocument import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|pdfbox operator|. name|pdmodel operator|. name|interactive operator|. name|action operator|. name|PDActionJavaScript import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|pdfbox operator|. name|pdmodel operator|. name|interactive operator|. name|action operator|. name|PDAnnotationAdditionalActions import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|pdfbox operator|. name|pdmodel operator|. name|interactive operator|. name|action operator|. name|PDFormFieldAdditionalActions import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|pdfbox operator|. name|pdmodel operator|. name|interactive operator|. name|annotation operator|. name|PDAnnotationWidget import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|pdfbox operator|. name|pdmodel operator|. name|interactive operator|. name|form operator|. name|PDAcroForm import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|pdfbox operator|. name|pdmodel operator|. name|interactive operator|. name|form operator|. name|PDField import|; end_import begin_comment comment|/** * Show usage of different field triggers. * * This sample adds a JavaScript to be executed on the different field triggers available. * * This sample builds on the form generated by @link CreateSimpleForm so you need to run that first. * */ end_comment begin_class specifier|public specifier|final class|class name|FieldTriggers block|{ specifier|private name|FieldTriggers parameter_list|() block|{ } specifier|public specifier|static name|void name|main parameter_list|( name|String index|[] name|args parameter_list|) throws|throws name|IOException block|{ comment|// Load the PDF document created by SimpleForm.java try|try init|( name|PDDocument name|document init|= name|Loader operator|. name|loadPDF argument_list|( operator|new name|File argument_list|( literal|"target/SimpleForm.pdf" argument_list|) argument_list|) init|) block|{ name|PDAcroForm name|acroForm init|= name|document operator|. name|getDocumentCatalog argument_list|() operator|. name|getAcroForm argument_list|() decl_stmt|; comment|// Get the field and the widget associated to it. comment|// Note: there might be multiple widgets name|PDField name|field init|= name|acroForm operator|. name|getField argument_list|( literal|"SampleField" argument_list|) decl_stmt|; name|PDAnnotationWidget name|widget init|= name|field operator|. name|getWidgets argument_list|() operator|. name|get argument_list|( literal|0 argument_list|) decl_stmt|; comment|// Some of the actions are available to the widget, some are available to the form field. comment|// See Table 8.44 and Table 8.46 in the PDF 1.7 specification comment|// Actions for the widget name|PDAnnotationAdditionalActions name|annotationActions init|= operator|new name|PDAnnotationAdditionalActions argument_list|() decl_stmt|; comment|// Create an action when entering the annotations active area name|PDActionJavaScript name|jsEnterAction init|= operator|new name|PDActionJavaScript argument_list|() decl_stmt|; name|jsEnterAction operator|. name|setAction argument_list|( literal|"app.alert(\"On 'enter' action\")" argument_list|) expr_stmt|; name|annotationActions operator|. name|setE argument_list|( name|jsEnterAction argument_list|) expr_stmt|; comment|// Create an action when exiting the annotations active area name|PDActionJavaScript name|jsExitAction init|= operator|new name|PDActionJavaScript argument_list|() decl_stmt|; name|jsExitAction operator|. name|setAction argument_list|( literal|"app.alert(\"On 'exit' action\")" argument_list|) expr_stmt|; name|annotationActions operator|. name|setX argument_list|( name|jsExitAction argument_list|) expr_stmt|; comment|// Create an action when the mouse button is pressed inside the annotations active area name|PDActionJavaScript name|jsMouseDownAction init|= operator|new name|PDActionJavaScript argument_list|() decl_stmt|; name|jsMouseDownAction operator|. name|setAction argument_list|( literal|"app.alert(\"On 'mouse down' action\")" argument_list|) expr_stmt|; name|annotationActions operator|. name|setD argument_list|( name|jsMouseDownAction argument_list|) expr_stmt|; comment|// Create an action when the mouse button is released inside the annotations active area name|PDActionJavaScript name|jsMouseUpAction init|= operator|new name|PDActionJavaScript argument_list|() decl_stmt|; name|jsMouseUpAction operator|. name|setAction argument_list|( literal|"app.alert(\"On 'mouse up' action\")" argument_list|) expr_stmt|; name|annotationActions operator|. name|setU argument_list|( name|jsMouseUpAction argument_list|) expr_stmt|; comment|// Create an action when the annotation gets the input focus name|PDActionJavaScript name|jsFocusAction init|= operator|new name|PDActionJavaScript argument_list|() decl_stmt|; name|jsFocusAction operator|. name|setAction argument_list|( literal|"app.alert(\"On 'focus' action\")" argument_list|) expr_stmt|; name|annotationActions operator|. name|setFo argument_list|( name|jsFocusAction argument_list|) expr_stmt|; comment|// Create an action when the annotation loses the input focus name|PDActionJavaScript name|jsBlurredAction init|= operator|new name|PDActionJavaScript argument_list|() decl_stmt|; name|jsBlurredAction operator|. name|setAction argument_list|( literal|"app.alert(\"On 'blurred' action\")" argument_list|) expr_stmt|; name|annotationActions operator|. name|setBl argument_list|( name|jsBlurredAction argument_list|) expr_stmt|; name|widget operator|. name|setActions argument_list|( name|annotationActions argument_list|) expr_stmt|; comment|// Actions for the field name|PDFormFieldAdditionalActions name|fieldActions init|= operator|new name|PDFormFieldAdditionalActions argument_list|() decl_stmt|; comment|// Create an action when the user types a keystroke in the field name|PDActionJavaScript name|jsKeystrokeAction init|= operator|new name|PDActionJavaScript argument_list|() decl_stmt|; name|jsKeystrokeAction operator|. name|setAction argument_list|( literal|"app.alert(\"On 'keystroke' action\")" argument_list|) expr_stmt|; name|fieldActions operator|. name|setK argument_list|( name|jsKeystrokeAction argument_list|) expr_stmt|; comment|// Create an action when the field is formatted to display the current value name|PDActionJavaScript name|jsFormattedAction init|= operator|new name|PDActionJavaScript argument_list|() decl_stmt|; name|jsFormattedAction operator|. name|setAction argument_list|( literal|"app.alert(\"On 'formatted' action\")" argument_list|) expr_stmt|; name|fieldActions operator|. name|setF argument_list|( name|jsFormattedAction argument_list|) expr_stmt|; comment|// Create an action when the field value changes name|PDActionJavaScript name|jsChangedAction init|= operator|new name|PDActionJavaScript argument_list|() decl_stmt|; name|jsChangedAction operator|. name|setAction argument_list|( literal|"app.alert(\"On 'change' action\")" argument_list|) expr_stmt|; comment|// fieldActions.setV(jsChangedAction); comment|// Create an action when the field value changes name|PDActionJavaScript name|jsRecalculateAction init|= operator|new name|PDActionJavaScript argument_list|() decl_stmt|; name|jsRecalculateAction operator|. name|setAction argument_list|( literal|"app.alert(\"On 'recalculate' action\")" argument_list|) expr_stmt|; name|fieldActions operator|. name|setC argument_list|( name|jsRecalculateAction argument_list|) expr_stmt|; comment|// Set the Additional Actions entry for the field comment|// Note: this is a workaround as if there is only one widget the widget comment|// and the form field may share the same dictionary. Now setting the comment|// fields Additional Actions entry directly will overwrite the settings done for comment|// the widget. comment|// https://issues.apache.org/jira/browse/PDFBOX-3036 name|field operator|. name|getActions argument_list|() operator|. name|getCOSObject argument_list|() operator|. name|addAll argument_list|( name|fieldActions operator|. name|getCOSObject argument_list|() argument_list|) expr_stmt|; name|document operator|. name|save argument_list|( literal|"target/FieldTriggers.pdf" argument_list|) expr_stmt|; block|} block|} block|} end_class end_unit
18.851224
810
0.802897
24f2caa8ce83987ef21600d174a199445defa26b
679
package br.com.curso.springboot.api.repositories; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import br.com.curso.springboot.api.entidades.Funcionario; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") public interface FuncionarioRepositoryTest extends JpaRepository<Funcionario, Long> { Funcionario findByCpf(String cpf); Funcionario findByEmail(String email); Funcionario findByCpfOrEmail(String cpf, String email); }
30.863636
85
0.835052
5eddab9ab63d1f2418c52ef04057f7759aeecadd
329
package com.rsamani.preflin.serializer; import java.util.List; /** * Created by rasool on 1/28/2019. * Email: [email protected] */ public interface Serializer { String toString(Object o); <T> T objectFromString(String s, Class<T> tClass); <T> List<T> listObjectFromString(String s, Class<T> tClass); }
18.277778
64
0.696049
39b28187a66d7c282286e5bec2a72e09fe5c9570
615
package com.cart.shoppingapp; import android.app.Activity; import com.cart.shoppingapp.di.component.ApplicationComponent; import com.cart.shoppingapp.di.component.DaggerApplicationComponent; import dagger.android.AndroidInjector; import dagger.android.support.DaggerApplication; public class ShoppingApplication extends DaggerApplication { @Override protected AndroidInjector<? extends DaggerApplication> applicationInjector() { ApplicationComponent component = DaggerApplicationComponent.builder().application(this).build(); component.inject(this); return component; } }
27.954545
104
0.79187
d0fdb9d462f78fdf1d0929867b6b5db6f7a69f53
1,440
/* * Copyright 2020 Vincent Galloy * * 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.vgalloy.gatlingjavaapi.api.dsl.http.wrapper; import com.vgalloy.gatlingjavaapi.api.dsl.core.wrapper.impl.ActionBuilderSupplier; import io.gatling.core.action.builder.ActionBuilder; import io.gatling.http.action.ws.WsCloseBuilder; import java.util.Objects; import java.util.function.Supplier; /** * Created by Vincent Galloy on 24/02/2017. * * @author Vincent Galloy. */ public final class WsCloseBuilderWrapper implements Supplier<WsCloseBuilder>, ActionBuilderSupplier { private final WsCloseBuilder wsCloseBuilder; public WsCloseBuilderWrapper(WsCloseBuilder wsCloseBuilder) { this.wsCloseBuilder = Objects.requireNonNull(wsCloseBuilder); } @Override public WsCloseBuilder get() { return wsCloseBuilder; } @Override public ActionBuilder toActionBuilder() { return wsCloseBuilder; } }
30
82
0.764583
8380896a37aed894b182304b4940a3dd65041da9
3,507
package com.belatrix.events.presentation.ui.fragments; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.belatrix.events.R; import com.belatrix.events.di.component.UIComponent; import com.belatrix.events.domain.model.Collaborator; import com.belatrix.events.presentation.presenters.AboutFragmentPresenter; import com.belatrix.events.presentation.ui.adapters.TeamListAdapter; import com.belatrix.events.presentation.ui.base.BelatrixBaseFragment; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import butterknife.BindView; public class AboutFragment extends BelatrixBaseFragment implements AboutFragmentPresenter.View { public static final String COLLABORATORS_KEY = "_collaborators_key"; @Inject AboutFragmentPresenter aboutPresenter; private TeamListAdapter collaboratorListAdapter; @BindView(R.id.collaborators) RecyclerView collaboratorsRecyclerView; public static AboutFragment newInstance() { AboutFragment aboutFragment = new AboutFragment(); return aboutFragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); return inflater.inflate(R.layout.fragment_about, container, false); } @Override protected void initDependencies(UIComponent uiComponent) { uiComponent.inject(this); aboutPresenter.setView(this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initViews(); if (savedInstanceState != null) { restoreState(savedInstanceState); } aboutPresenter.getContacts(); } @Override public void onSaveInstanceState(Bundle outState) { saveState(outState); super.onSaveInstanceState(outState); } private void restoreState(Bundle savedInstanceState) { List<Collaborator> collaborators = savedInstanceState.getParcelableArrayList(COLLABORATORS_KEY); aboutPresenter.loadPresenterState(collaborators); } private void saveState(Bundle outState) { List<Collaborator> collaborators = aboutPresenter.getCollaboratorsSync(); if (collaborators != null && collaborators instanceof ArrayList) { outState.putParcelableArrayList(COLLABORATORS_KEY, (ArrayList<Collaborator>) collaborators); } } @Override public void initViews() { GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2); collaboratorListAdapter = new TeamListAdapter(); collaboratorsRecyclerView.setAdapter(collaboratorListAdapter); collaboratorsRecyclerView.setNestedScrollingEnabled(false); collaboratorsRecyclerView.setLayoutManager(gridLayoutManager); } @Override public void onDestroyView() { super.onDestroyView(); } @Override public void addContacts(List<Collaborator> collaborators) { collaboratorListAdapter.add(collaborators); } @Override public void resetList() { collaboratorListAdapter.reset(); } }
32.472222
104
0.733961
8ed120a85149a96b7a2075c691001c0340c2e603
75
/** * Contains utility classes for tuples. */ package wulfric.util.tuple;
18.75
39
0.72
dba2b094774fcbc5279c564ab5b2bab50f52989e
436
package com.plaid.client.request; import com.plaid.client.request.common.BaseAccessTokenRequest; /** * Request for /processor/dwolla/processor_token/create endpoint. */ public class ItemDwollaProcessorTokenCreateRequest extends BaseAccessTokenRequest { private String accountId; public ItemDwollaProcessorTokenCreateRequest(String accessToken, String accountId) { super(accessToken); this.accountId = accountId; } }
27.25
86
0.800459
aff5699e5096a485ab8dba04f3931675d8555043
2,193
package com.ota.download; import java.net.InetSocketAddress; import java.net.Proxy; import org.apache.http.HttpHost; import org.apache.http.client.methods.HttpPost; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.text.TextUtils; public class CheckRequestState { public boolean isWapState=false; public static final String GWAP = "3gwap"; public static final String CMWAP = "cmwap"; public static final String CTWAP = "ctwap"; public static final String UNIWAP = "uniwap"; public static final String SCHEME = "http://"; public static final String X_ONLINE_HOST = "X-Online-Host"; public static final String X_OFFLINE_HOST = "http://10.0.0.172"; public static final String DEFAULT_PROXY_HOST="10.0.0.172"; public static boolean isWap(Context context) { ConnectivityManager connManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkinfo = connManager.getActiveNetworkInfo(); String extraInfo = null; if (networkinfo != null) { extraInfo = networkinfo.getExtraInfo(); } if (extraInfo != null && (extraInfo.equals(CMWAP) || extraInfo.equals(UNIWAP))) { return true; } return false; } public static HttpHost checkHttpHost(Context context){ if (isWap(context)) { String h = android.net.Proxy.getHost(context); int port = android.net.Proxy.getPort(context); if (h == null || TextUtils.isEmpty(h.trim())) { h = CheckRequestState.DEFAULT_PROXY_HOST; } if (port == -1) { port = 80; } return new HttpHost(h, port); } return null; } public static java.net.Proxy checkUrlConnectionProxy(Context context){ if (isWap(context)) { String h = android.net.Proxy.getHost(context); int port = android.net.Proxy.getPort(context); if (h == null || TextUtils.isEmpty(h.trim())) { h = CheckRequestState.DEFAULT_PROXY_HOST; } if (port == -1) { port = 80; } return new Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(h, port)); } return null; } }
25.5
72
0.677611
8394e46239267c15f3fe14e4261c86c6ba2ee6f6
5,695
package com.cosmos.cstnse.simpletreck; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SensorEventListener { // define the display assembly compass picture private ImageView image; // record the compass picture angle turned private float currentDegree = 0f; // device sensor manager private SensorManager mSensorManager; TextView tvHeading; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); image = (ImageView) findViewById(R.id.imageViewCompass); // TextView that will tell the user what degree is he heading tvHeading = (TextView) findViewById(R.id.tvHeading); // initialize your android device sensor capabilities mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override protected void onResume() { super.onResume(); // for the system's orientation sensor registered listeners mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME); } @Override protected void onPause() { super.onPause(); // to stop the listener and save battery mSensorManager.unregisterListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onSensorChanged(SensorEvent event) { // get the angle around the z-axis rotated float degree = Math.round(event.values[0]); tvHeading.setText("Heading: " + Float.toString(degree) + " degrees"); // create a rotation animation (reverse turn degree degrees) RotateAnimation ra = new RotateAnimation( currentDegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); // how long the animation will take place ra.setDuration(210); // set the animation after the end of the reservation status ra.setFillAfter(true); // Start the animation image.startAnimation(ra); currentDegree = -degree; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // not in use } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.compass) { Intent intent = new Intent(this, CompassActivity.class); int requestCode = 0; startActivityForResult(intent, requestCode); } else if (id == R.id.myWaypoints) { Intent intent = new Intent(this, emptyActivity.class); int requestCode = 0; startActivityForResult(intent, requestCode); } else if (id == R.id.map) { } else if (id == R.id.settings) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
35.154321
107
0.658472
c5e7870d200bd98dd6a28032dfec50b36e5975f8
953
package eventstore.j.examples; import akka.actor.ActorRef; import akka.actor.ActorSystem; import eventstore.Event; import eventstore.EventNumber; import eventstore.ReadEvent; import eventstore.j.EsConnection; import eventstore.j.EsConnectionFactory; import eventstore.j.ReadEventBuilder; import eventstore.tcp.ConnectionActor; import scala.concurrent.Future; public class APIsExample { final ActorSystem system = ActorSystem.create(); public void methodCall() { final EsConnection connection = EsConnectionFactory.create(system); final Future<Event> future = connection.readEvent("my-stream", new EventNumber.Exact(0), false, null); } public void messageSending() { final ActorRef connection = system.actorOf(ConnectionActor.getProps()); final ReadEvent readEvent = new ReadEventBuilder("my-stream") .first() .build(); connection.tell(readEvent, null); } }
31.766667
110
0.728227
5accd449c31d59c39dcb65219690c7d4475bf916
5,093
package com.example.androidproject.systermUI; import android.content.DialogInterface; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.os.Bundle; import android.util.Log; import android.webkit.JavascriptInterface; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import java.io.IOException; public class WebViewActivity extends AppCompatActivity { private String TAG = "WebViewActivity"; private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_web_view); AssetManager assetManager = getAssets(); try { String[] paths = assetManager.list(""); for (String path : paths) { Log.i(TAG, "路径:=" + path); } } catch (IOException e) { e.printStackTrace(); } webView = new WebView(this); //webView.loadUrl("https://www.baidu.com"); webView.loadUrl("file:///android_asset/webview.html"); // WebSettings。webView的设置 // 类似WKWebView的,WKWebViewConfig。 webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setSupportZoom(true); // 通过该方法实现,webView和js的互调。 webView.addJavascriptInterface(new MyObject(), "myObj"); // WebViewClient控制客户端,用于处理各种通知和请求事件。 // 类似iOS中,WKWebView的navigationDelegate webView.setWebViewClient(new WebViewClient(){ // Denied starting an intent without a user gesture // 需要重写该方法,返回false。主要原因是chrome内核问题。 // 控制对新加载的Url的处理,返回true,说明主程序处理WebView不做处理,返回false意味着WebView会对其进行处理 @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { Log.i(TAG, "shouldOverrideUrlLoading"); return false; } // 页面开始加载。 @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); Log.i(TAG, "onPageStarted"); } @Override public void onLoadResource(WebView view, String url) { super.onLoadResource(view, url); Log.i(TAG, "onLoadResource"); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); Log.i(TAG, "onPageFinished"); } }); // WebChromeClient。 浏览器客户端,用于处理网站图标、网站标题、网站弹窗等。 // 类似ios中,WKWebView的WKUIDelegate webView.setWebChromeClient(new WebChromeClient(){ // 获取网站的图标 @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); Log.i(TAG, "onReceivedTitle ||==" + title); } // 三种弹窗。 @Override public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { new AlertDialog.Builder(WebViewActivity.this) .setTitle("alter对话窗") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { result.confirm(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { result.cancel(); } }) .setCancelable(false) .show(); return true; } // 系统默认的样式 @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { return super.onJsConfirm(view, url, message, result); } @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { return super.onJsPrompt(view, url, message, defaultValue, result); } }); setContentView(webView); } } class MyObject extends Object { private String TAG = "MyObject"; @JavascriptInterface public void showDialog() { Log.i(TAG, "js 方法调用 showDialog"); } @JavascriptInterface public void showWithPara(String par) { Log.i(TAG, "js 方法调用 showWithPara" + par); } }
32.43949
125
0.579815
c24eca51d5c1ae699264a58eadb527fcc8344f2b
1,255
package com.accenture.pocproject.customers; import com.accenture.pocproject.api.PocApiClient; import com.accenture.pocproject.api.PocApiService; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by fjodors.pohodnevs on 8/29/2016. */ public class CustomersPresenter implements CustomerContract.Presenter { CustomerContract.View customerView; public CustomersPresenter(CustomerContract.View customerView) { this.customerView = customerView; } @Override public void fetchCostumers() { PocApiService apiService = PocApiClient.getGetClient().create(PocApiService.class); Call<List<Customer>> call = apiService.getCustomers(); call.enqueue(new Callback<List<Customer>>() { @Override public void onResponse(Call<List<Customer>> call, Response<List<Customer>> response) { customerView.showCustomers(response.body()); customerView.hideProgress(); } @Override public void onFailure(Call<List<Customer>> call, Throwable t) { customerView.hideProgress(); customerView.showError(t); } }); } }
29.186047
98
0.67012
7928d795233780af63e6eb90fe33ee57ba396356
208
package com.tw.marsrover; /** * * @author vji */ public class UninitialisedPlateauException extends RuntimeException { public UninitialisedPlateauException(String message) { super(message); } }
17.333333
69
0.735577
e1476898b5307401112600cb6042269b39d07131
24,077
package org.jboss.resteasy.client; import org.jboss.resteasy.client.core.BaseClientResponse; import org.jboss.resteasy.client.core.ClientInterceptorRepositoryImpl; import org.jboss.resteasy.core.interception.ClientExecutionContextImpl; import org.jboss.resteasy.core.interception.ClientWriterInterceptorContext; import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages; import org.jboss.resteasy.specimpl.MultivaluedMapImpl; import org.jboss.resteasy.specimpl.ResteasyUriBuilder; import org.jboss.resteasy.spi.Link; import org.jboss.resteasy.spi.LinkHeader; import org.jboss.resteasy.spi.ProviderFactoryDelegate; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.jboss.resteasy.spi.StringConverter; import org.jboss.resteasy.util.Encode; import org.jboss.resteasy.util.GenericType; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Providers; import javax.ws.rs.ext.RuntimeDelegate; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.jboss.resteasy.util.HttpHeaderNames.ACCEPT; /** * Create a hand coded request to send to the server. You call methods like accept(), body(), pathParameter() * etc. to create the state of the request. Then you call a get(), post(), etc. method to execute the request. * After an execution of a request, the internal state remains the same. You can invoke the request again. * You can clear the request with the clear() method. * * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module. * @author <a href="mailto:[email protected]">Solomon Duskis</a> * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ * * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339) * @see javax.ws.rs.client.Invocation */ @Deprecated @SuppressWarnings("unchecked") public class ClientRequest extends ClientInterceptorRepositoryImpl implements Cloneable { protected ResteasyProviderFactory providerFactory; protected ResteasyUriBuilder uri; protected ClientExecutor executor; protected MultivaluedMap<String, Object> headers; protected MultivaluedMap<String, String> queryParameters; protected MultivaluedMap<String, String> formParameters; protected MultivaluedMap<String, String> pathParameters; protected MultivaluedMap<String, String> matrixParameters; protected Object body; protected Class bodyType; protected Type bodyGenericType; protected Annotation[] bodyAnnotations; protected MediaType bodyContentType; protected boolean followRedirects; protected String httpMethod; protected String finalUri; protected List<String> pathParameterList; protected LinkHeader linkHeader; protected Map<String, Object> attributes = new HashMap<String, Object>(); private static String defaultExecutorClasss = "org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor"; /** * Set the default executor class name. * * @param classname */ public static void setDefaultExecutorClass(String classname) { defaultExecutorClasss = classname; } public static ClientExecutor getDefaultExecutor() { try { Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(defaultExecutorClasss); return (ClientExecutor) clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } public ClientRequest(String uriTemplate) { this(uriTemplate, getDefaultExecutor()); } public ClientRequest(String uriTemplate, ClientExecutor executor) { this(getBuilder(uriTemplate), executor); } public ClientRequest(UriBuilder uri, ClientExecutor executor) { this(uri, executor, ResteasyProviderFactory.getInstance()); } public ClientRequest(UriBuilder uri, ClientExecutor executor, ResteasyProviderFactory providerFactory) { this.uri = (ResteasyUriBuilder) uri; this.executor = executor; if (providerFactory instanceof ProviderFactoryDelegate) { this.providerFactory = ((ProviderFactoryDelegate) providerFactory) .getDelegate(); } else { this.providerFactory = providerFactory; } } /** * Clear this request's state so that it can be re-used */ public void clear() { headers = null; queryParameters = null; formParameters = null; pathParameters = null; matrixParameters = null; body = null; bodyType = null; bodyGenericType = null; bodyAnnotations = null; bodyContentType = null; httpMethod = null; finalUri = null; pathParameterList = null; linkHeader = null; } private static UriBuilder getBuilder(String uriTemplate) { return new ResteasyUriBuilder().uriTemplate(uriTemplate); } public boolean followRedirects() { return followRedirects; } public Map<String, Object> getAttributes() { return attributes; } public ClientRequest followRedirects(boolean followRedirects) { this.followRedirects = followRedirects; return this; } public ClientRequest accept(MediaType accepts) { return header(ACCEPT, accepts.toString()); } public ClientRequest accept(String accept) { String curr = (String) getHeadersAsObjects().getFirst(ACCEPT); if (curr != null) curr += "," + accept; else curr = accept; getHeadersAsObjects().putSingle(ACCEPT, curr); return this; } protected String toString(Object object) { if (object instanceof String) return (String) object; StringConverter converter = providerFactory.getStringConverter(object .getClass()); if (converter != null) return converter.toString(object); else return object.toString(); } protected String toHeaderString(Object object) { return providerFactory.toHeaderString(object); } public ClientRequest addLink(Link link) { if (linkHeader == null) { linkHeader = new LinkHeader(); } linkHeader.getLinks().add(link); return this; } public ClientRequest addLink(String title, String rel, String href, String type) { Link link = new Link(title, rel, href, type, null); return addLink(link); } public ClientRequest formParameter(String parameterName, Object value) { getFormParameters().add(parameterName, toString(value)); return this; } public ClientRequest queryParameter(String parameterName, Object value) { getQueryParameters().add(parameterName, toString(value)); return this; } public ClientRequest matrixParameter(String parameterName, Object value) { getMatrixParameters().add(parameterName, toString(value)); return this; } public ClientRequest header(String headerName, Object value) { getHeadersAsObjects().add(headerName, value); return this; } public ClientRequest cookie(String cookieName, Object value) { return cookie(new Cookie(cookieName, toString(value))); } public ClientRequest cookie(Cookie cookie) { return header(HttpHeaders.COOKIE, cookie); } public ClientRequest pathParameter(String parameterName, Object value) { getPathParameters().add(parameterName, toString(value)); return this; } public ClientRequest pathParameters(Object... values) { for (Object value : values) { getPathParameterList().add(toString(value)); } return this; } public ClientRequest body(String contentType, Object data) { return body(MediaType.valueOf(contentType), data, data.getClass(), null, null); } public ClientRequest body(MediaType contentType, Object data) { return body(contentType, data, data.getClass(), null, null); } public ClientRequest body(MediaType contentType, Object data, GenericType genericType) { return body(contentType, data, genericType.getType(), genericType .getGenericType(), null); } public ClientRequest body(MediaType contentType, Object data, Type genericType) { return body(contentType, data, data.getClass(), genericType, null); } public ClientRequest body(MediaType contentType, Object data, Class type, Type genericType, Annotation[] annotations) { this.body = data; this.bodyContentType = contentType; this.bodyGenericType = genericType; this.bodyType = type; this.bodyAnnotations = annotations; return this; } public ResteasyProviderFactory getProviderFactory() { return providerFactory; } public ClientExecutor getExecutor() { return executor; } /** * @return a copy of all header objects converted to a string */ public MultivaluedMap<String, String> getHeaders() { MultivaluedMap<String, String> rtn = new MultivaluedMapImpl<String, String>(); if (headers == null) return rtn; for (Map.Entry<String, List<Object>> entry : headers.entrySet()) { for (Object obj : entry.getValue()) { rtn.add(entry.getKey(), toHeaderString(obj)); } } return rtn; } public MultivaluedMap<String, Object> getHeadersAsObjects() { if (headers == null) headers = new MultivaluedMapImpl<String, Object>(); return headers; } public MultivaluedMap<String, String> getQueryParameters() { if (queryParameters == null) queryParameters = new MultivaluedMapImpl<String, String>(); return queryParameters; } public MultivaluedMap<String, String> getFormParameters() { if (formParameters == null) formParameters = new MultivaluedMapImpl<String, String>(); return formParameters; } public MultivaluedMap<String, String> getPathParameters() { if (pathParameters == null) pathParameters = new MultivaluedMapImpl<String, String>(); return pathParameters; } public List<String> getPathParameterList() { if (pathParameterList == null) pathParameterList = new ArrayList<String>(); return pathParameterList; } public MultivaluedMap<String, String> getMatrixParameters() { if (matrixParameters == null) matrixParameters = new MultivaluedMapImpl<String, String>(); return matrixParameters; } public Object getBody() { return body; } public Class getBodyType() { return bodyType; } public Type getBodyGenericType() { return bodyGenericType; } public Annotation[] getBodyAnnotations() { return bodyAnnotations; } public MediaType getBodyContentType() { return bodyContentType; } public String getHttpMethod() { return httpMethod; } public void setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; } public ClientResponse execute() throws Exception { Providers current = ResteasyProviderFactory.getContextData(Providers.class); ResteasyProviderFactory.pushContext(Providers.class, providerFactory); try { if (linkHeader != null) header("Link", linkHeader); if (getReaderInterceptorList().isEmpty()) { setReaderInterceptors(providerFactory.getClientReaderInterceptorRegistry().postMatch(null, null)); } if (getExecutionInterceptorList().isEmpty()) { setExecutionInterceptors(providerFactory .getClientExecutionInterceptorRegistry().bindForList(null, null)); } BaseClientResponse response = null; if (getExecutionInterceptorList().isEmpty()) { response = (BaseClientResponse) executor.execute(this); } else { ClientExecutionContextImpl ctx = new ClientExecutionContextImpl( getExecutionInterceptorList(), executor, this); response = (BaseClientResponse) ctx.proceed(); } response.setAttributes(attributes); response.setReaderInterceptors(getReaderInterceptors()); return response; } finally { ResteasyProviderFactory.popContextData(Providers.class); if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current); } } public void writeRequestBody(MultivaluedMap<String, Object> headers, OutputStream outputStream) throws IOException { if (body == null) { return; } if (getWriterInterceptorList().isEmpty()) { setWriterInterceptors(providerFactory.getClientWriterInterceptorRegistry().postMatch(null, null)); } new ClientWriterInterceptorContext(getWriterInterceptors(), providerFactory, body, bodyType, bodyGenericType, bodyAnnotations, bodyContentType, headers, outputStream, attributes).proceed(); } public ClientResponse get() throws Exception { return httpMethod("GET"); } /** * Tries to automatically unmarshal to target type. * * @param returnType * @param <T> * @return * @throws Exception */ public <T> T getTarget(Class<T> returnType) throws Exception { BaseClientResponse<T> response = (BaseClientResponse<T>) get(returnType); if (response.getStatus() == 204) return null; if (response.getStatus() != 200) throw new ClientResponseFailure(response); T obj = response.getEntity(); if (obj instanceof InputStream) { response.setWasReleased(true); } return obj; } /** * Templates the returned ClientResponse for easy access to returned entity * * @param returnType * @param <T> * @return * @throws Exception */ public <T> ClientResponse<T> get(Class<T> returnType) throws Exception { BaseClientResponse response = (BaseClientResponse) get(); response.setReturnType(returnType); return response; } public <T> ClientResponse<T> get(Class<T> returnType, Type genericType) throws Exception { BaseClientResponse response = (BaseClientResponse) get(); response.setReturnType(returnType); response.setGenericReturnType(genericType); return response; } public <T> ClientResponse<T> get(GenericType type) throws Exception { BaseClientResponse response = (BaseClientResponse) get(); response.setReturnType(type.getType()); response.setGenericReturnType(type.getGenericType()); return response; } public ClientResponse head() throws Exception { return httpMethod("HEAD"); } public ClientResponse put() throws Exception { return httpMethod("PUT"); } public <T> ClientResponse<T> put(Class<T> returnType) throws Exception { BaseClientResponse response = (BaseClientResponse) put(); response.setReturnType(returnType); return response; } public <T> ClientResponse<T> put(Class<T> returnType, Type genericType) throws Exception { BaseClientResponse response = (BaseClientResponse) put(); response.setReturnType(returnType); response.setGenericReturnType(genericType); return response; } public <T> ClientResponse<T> put(GenericType type) throws Exception { BaseClientResponse response = (BaseClientResponse) put(); response.setReturnType(type.getType()); response.setGenericReturnType(type.getGenericType()); return response; } public ClientResponse post() throws Exception { return httpMethod("POST"); } public <T> ClientResponse<T> post(Class<T> returnType) throws Exception { BaseClientResponse response = (BaseClientResponse) post(); response.setReturnType(returnType); return response; } public <T> T postTarget(Class<T> returnType) throws Exception { BaseClientResponse<T> response = (BaseClientResponse<T>) post(returnType); if (response.getStatus() == 204) return null; if (response.getStatus() != 200) throw new ClientResponseFailure(response); T obj = response.getEntity(); if (obj instanceof InputStream) { response.setWasReleased(true); } return obj; } public <T> ClientResponse<T> post(Class<T> returnType, Type genericType) throws Exception { BaseClientResponse response = (BaseClientResponse) post(); response.setReturnType(returnType); response.setGenericReturnType(genericType); return response; } public <T> ClientResponse<T> post(GenericType type) throws Exception { BaseClientResponse response = (BaseClientResponse) post(); response.setReturnType(type.getType()); response.setGenericReturnType(type.getGenericType()); return response; } /** * Automatically does POST/Create pattern. Will throw a ClientResponseFailure * if status is something other than 201 * * @return Link to created resource * @throws Exception, ClientResponseFailure */ public Link create() throws Exception, ClientResponseFailure { BaseClientResponse response = (BaseClientResponse) post(); if (response.getStatus() != 201) throw new ClientResponseFailure(response); return response.getLocationLink(); } public ClientResponse delete() throws Exception { return httpMethod("DELETE"); } public <T> ClientResponse<T> delete(Class<T> returnType) throws Exception { BaseClientResponse response = (BaseClientResponse) delete(); response.setReturnType(returnType); return response; } public <T> ClientResponse<T> delete(Class<T> returnType, Type genericType) throws Exception { BaseClientResponse response = (BaseClientResponse) delete(); response.setReturnType(returnType); response.setGenericReturnType(genericType); return response; } public <T> ClientResponse<T> delete(GenericType type) throws Exception { BaseClientResponse response = (BaseClientResponse) delete(); response.setReturnType(type.getType()); response.setGenericReturnType(type.getGenericType()); return response; } public ClientResponse options() throws Exception { return httpMethod("OPTIONS"); } public <T> ClientResponse<T> options(Class<T> returnType) throws Exception { BaseClientResponse response = (BaseClientResponse) options(); response.setReturnType(returnType); return response; } public <T> ClientResponse<T> options(Class<T> returnType, Type genericType) throws Exception { BaseClientResponse response = (BaseClientResponse) options(); response.setReturnType(returnType); response.setGenericReturnType(genericType); return response; } public <T> ClientResponse<T> options(GenericType type) throws Exception { BaseClientResponse response = (BaseClientResponse) options(); response.setReturnType(type.getType()); response.setGenericReturnType(type.getGenericType()); return response; } public ClientResponse httpMethod(String httpMethod) throws Exception { this.httpMethod = httpMethod; return execute(); } public <T> ClientResponse<T> httpMethod(String method, Class<T> returnType) throws Exception { BaseClientResponse response = (BaseClientResponse) httpMethod(method); response.setReturnType(returnType); return response; } public <T> ClientResponse<T> httpMethod(String method, Class<T> returnType, Type genericType) throws Exception { BaseClientResponse response = (BaseClientResponse) httpMethod(method); response.setReturnType(returnType); response.setGenericReturnType(genericType); return response; } public <T> ClientResponse<T> httpMethod(String method, GenericType type) throws Exception { BaseClientResponse response = (BaseClientResponse) httpMethod(method); response.setReturnType(type.getType()); response.setGenericReturnType(type.getGenericType()); return response; } public void overrideUri(URI uri) { this.uri.uri(uri); } /** * This method populates all path, matrix, and query parameters and saves it * internally. Once its called once it returns the cached value. * * @return * @throws Exception */ public String getUri() throws Exception { if (finalUri != null) return finalUri; ResteasyUriBuilder builder = (ResteasyUriBuilder) uri.clone(); if (matrixParameters != null) { for (Map.Entry<String, List<String>> entry : matrixParameters .entrySet()) { List<String> values = entry.getValue(); for (String value : values) builder.matrixParam(entry.getKey(), value); } } if (queryParameters != null) { for (Map.Entry<String, List<String>> entry : queryParameters .entrySet()) { List<String> values = entry.getValue(); for (String value : values) builder.clientQueryParam(entry.getKey(), value); } } if (pathParameterList != null && !pathParameterList.isEmpty()) { finalUri = builder.build(pathParameterList.toArray()).toString(); } else if (pathParameters != null && !pathParameters.isEmpty()) { for (Map.Entry<String, List<String>> entry : pathParameters.entrySet()) { List<String> values = entry.getValue(); for (String value : values) { value = Encode.encodePathAsIs(value); builder.substitutePathParam(entry.getKey(), value, true); } } } if (finalUri == null) finalUri = builder.build().toString(); return finalUri; } public ClientRequest createSubsequentRequest(URI uri) { try { ClientRequest clone = (ClientRequest) this.clone(); clone.clear(); clone.uri = new ResteasyUriBuilder(); clone.uri.uri(uri); return clone; } catch (CloneNotSupportedException e) { // this shouldn't happen throw new RuntimeException(Messages.MESSAGES.clientRequestDoesntSupportClonable()); } } }
30.400253
127
0.645014
aeee775b76eec39899a2c56b0bb4043134334f45
10,409
package com.kdgregory.pomutil.version; import java.io.File; import java.io.FileOutputStream; import java.util.HashSet; import java.util.List; import java.util.Set; import org.w3c.dom.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.kdgcommons.io.IOUtil; import net.sf.kdgcommons.lang.ObjectUtil; import net.sf.kdgcommons.lang.StringUtil; import net.sf.practicalxml.DomUtil; import net.sf.practicalxml.OutputUtil; import com.kdgregory.pomutil.util.GAV; import com.kdgregory.pomutil.util.PomPaths; import com.kdgregory.pomutil.util.PomWrapper; /** * Version updater: identifies POMs or dependencies that match a * specified version and updates them to a new version. */ public class VersionUpdater { Logger logger = LoggerFactory.getLogger(getClass()); private String groupId; private String artifactId; private String fromVersion; private String toVersion; private boolean autoVersion; private boolean updateParent; private boolean updateDependencies; /** * @param groupId If not-null, updates are restricted to POMs/dependencies that * have a matching group ID. * @param artifactId If not-null, updates are restricted to POMs/dependencies that * have a matching artifact ID. * @param fromVersion If not-null, updates are restricted to POMs/dependencies that * have a matching version ID. * @param toVersion The desired new version. * @param autoVersion Flag to indicate that versions should be automatically updated. * @param updateParent Flag to indicate that parent references should be updated. * @param updateDependencies Flag to indicate that dependency references should be updated. */ public VersionUpdater( String groupId, String artifactId, String fromVersion, String toVersion, boolean autoVersion, boolean updateParent, boolean updateDependencies) { // these checks simplify logic further down if (StringUtil.isEmpty(groupId)) throw new IllegalArgumentException("groupId must be specified"); if ((fromVersion == null) && ! autoVersion) throw new IllegalArgumentException("fromVersion must be specified if autoVersion not true"); if ((toVersion == null) && ! autoVersion) throw new IllegalArgumentException("fromVersion must be specified if autoVersion not true"); this.groupId = groupId; this.artifactId = artifactId; this.fromVersion = fromVersion; this.toVersion = toVersion; this.autoVersion = autoVersion; this.updateParent = updateParent; this.updateDependencies = updateDependencies; } public void run(List<File> files) throws Exception { for (File file : files) { logger.info("processing: " + file.getPath()); try { PomWrapper wrapped = new PomWrapper(file); boolean changed = possiblyUpdateProjectVersion(wrapped) | possiblyUpdateParentVersion(wrapped) | possiblyUpdateDependencies(wrapped); if (changed) { FileOutputStream out = new FileOutputStream(file); try { OutputUtil.compactStream(wrapped.getDom(), out); } finally { IOUtil.closeQuietly(out); } } } catch (Exception ex) { logger.warn("unable to parse file: " + file); } } } //---------------------------------------------------------------------------- // Internals //---------------------------------------------------------------------------- private boolean possiblyUpdateProjectVersion(PomWrapper wrapped) { Element projectElement = wrapped.selectElement(PomPaths.PROJECT); if (groupAndArtifactMatches(projectElement) && oldVersionMatches(projectElement)) { updateVersionElement("project", projectElement); return true; } else { return false; } } private boolean possiblyUpdateParentVersion(PomWrapper wrapped) { if (! updateParent) return false; Element parentElement = wrapped.selectElement(PomPaths.PARENT); if (groupAndArtifactMatches(parentElement) && oldVersionMatches(parentElement)) { updateVersionElement("parent", parentElement); return true; } else { return false; } } private boolean possiblyUpdateDependencies(PomWrapper wrapped) { if (! updateDependencies) return false; boolean result = false; Set<String> targetProperties = new HashSet<String>(); Set<Element> targetDependencies = new HashSet<Element>( wrapped.filterByGroupAndArtifact( wrapped.selectElements(PomPaths.PROJECT_DEPENDENCIES, PomPaths.MANAGED_DEPENDENCIES), groupId, artifactId)); for (Element dependencyElement : targetDependencies) { if (groupAndArtifactMatches(dependencyElement) && oldVersionMatches(dependencyElement)) { updateVersionElement("dependency", dependencyElement); result = true; } else { String dependencyVersion = wrapped.selectValue(dependencyElement, "mvn:version").trim(); if (dependencyVersion.startsWith("${")) { String propertyName = dependencyVersion.substring(2, dependencyVersion.length() - 1); targetProperties.add(propertyName); } } } return result || possiblyUpdateProperties(wrapped, targetDependencies, targetProperties); } private boolean possiblyUpdateProperties(PomWrapper wrapped, Set<Element> targetDependencies, Set<String> targetProperties) { boolean result = false; for (String property : targetProperties) { String existingVersion = wrapped.getProperty(property); if (! oldVersionMatches(existingVersion)) { continue; } Set<Element> elementsWithProperty = new HashSet<Element>(); elementsWithProperty.addAll(wrapped.selectElements(PomPaths.PROJECT_DEPENDENCIES + "[mvn:version='${" + property + "}']")); elementsWithProperty.addAll(wrapped.selectElements(PomPaths.MANAGED_DEPENDENCIES + "[mvn:version='${" + property + "}']")); if (! elementsWithProperty.equals(targetDependencies)) { logger.warn("unselected dependencies use property {}; not updating", property); continue; } String newVersion = determineNewVersion(existingVersion); logger.warn("updating property {} from {} to {}", property, existingVersion, newVersion); wrapped.setProperty(property, newVersion); result = true; } return result; } private boolean groupAndArtifactMatches(Element reference) { Element groupElement = DomUtil.getChild(reference, "groupId"); if (groupElement == null) return false; if (! groupId.equals(DomUtil.getText(groupElement))) return false; if (artifactId == null) return true; Element artifactElement = DomUtil.getChild(reference, "artifactId"); if (artifactElement == null) return false; if (! artifactId.equals(DomUtil.getText(artifactElement))) return false; return true; } private boolean oldVersionMatches(Element container) { // this is a bogus file if (container == null) return false; Element versionElement = DomUtil.getChild(container, "version"); if (versionElement == null) return false; return oldVersionMatches(DomUtil.getText(versionElement)); } private boolean oldVersionMatches(String existingVersion) { logger.debug("testing version {}; fromVersion = {}, autoVersion = {}", existingVersion, fromVersion, autoVersion); // this can't be used to check versions specified as properties if (existingVersion.startsWith("${")) return false; // auto-version doesn't need a from-version if (fromVersion == null) return autoVersion; return ObjectUtil.equals(fromVersion, existingVersion.trim()); } private void updateVersionElement(String containerType, Element container) { GAV gav = new GAV(container); String newVersion = determineNewVersion(gav.version); if (newVersion != null) { logger.info("new {} version: {}:{}:{}", containerType, gav.groupId, gav.artifactId, newVersion); Element versionElement = DomUtil.getChild(container, "version"); DomUtil.setText(versionElement, newVersion); } } private String determineNewVersion(String existingVersion) { if (toVersion != null) return toVersion; if (existingVersion.endsWith("-SNAPSHOT")) return StringUtil.extractLeft(existingVersion, "-SNAPSHOT"); String preservedPart = StringUtil.extractLeftOfLast(existingVersion, "."); String updatedPart = StringUtil.extractRightOfLast(existingVersion, "."); try { int oldValue = Integer.parseInt(updatedPart); return preservedPart + "." + (oldValue + 1) + "-SNAPSHOT"; } catch (NumberFormatException ex) { logger.error("unable to autoversion: " + existingVersion); return null; } } }
34.696667
135
0.589106
870ad239f104b550ac7d7056aa3638a8e0353756
3,235
package com.cqust.pojo; import java.util.Date; public class TStoreapplication { private Integer id; private Integer userid; private String ownname; private String phone; private String uid; private String uidimageurl; private String storename; private String storeaddr; private String detailaddr; private String storelicenseid; private String licenseimageurl; private Integer storetype; private Date sqdate; private Integer sqstatus; private String storelogoimg; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public String getOwnname() { return ownname; } public void setOwnname(String ownname) { this.ownname = ownname == null ? null : ownname.trim(); } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid == null ? null : uid.trim(); } public String getUidimageurl() { return uidimageurl; } public void setUidimageurl(String uidimageurl) { this.uidimageurl = uidimageurl == null ? null : uidimageurl.trim(); } public String getStorename() { return storename; } public void setStorename(String storename) { this.storename = storename == null ? null : storename.trim(); } public String getStoreaddr() { return storeaddr; } public void setStoreaddr(String storeaddr) { this.storeaddr = storeaddr == null ? null : storeaddr.trim(); } public String getDetailaddr() { return detailaddr; } public void setDetailaddr(String detailaddr) { this.detailaddr = detailaddr == null ? null : detailaddr.trim(); } public String getStorelicenseid() { return storelicenseid; } public void setStorelicenseid(String storelicenseid) { this.storelicenseid = storelicenseid == null ? null : storelicenseid.trim(); } public String getLicenseimageurl() { return licenseimageurl; } public void setLicenseimageurl(String licenseimageurl) { this.licenseimageurl = licenseimageurl == null ? null : licenseimageurl.trim(); } public Integer getStoretype() { return storetype; } public void setStoretype(Integer storetype) { this.storetype = storetype; } public Date getSqdate() { return sqdate; } public void setSqdate(Date sqdate) { this.sqdate = sqdate; } public Integer getSqstatus() { return sqstatus; } public void setSqstatus(Integer sqstatus) { this.sqstatus = sqstatus; } public String getStorelogoimg() { return storelogoimg; } public void setStorelogoimg(String storelogoimg) { this.storelogoimg = storelogoimg == null ? null : storelogoimg.trim(); } }
20.870968
87
0.625348
dcc670f9e2b10da5c73abb3349c8c3fe731a7433
238
package infobip.api.model.omni; /** * This is a generated class and is not intended for modification! */ public enum OmniChannel { SMS, EMAIL, VOICE, PARSECO, PUSH, VIBER, FACEBOOK, LINE, VKONTAKTE }
14.875
66
0.62605
dcde48c0f0e274685605f1d8b0ae3a32f6c74039
1,001
package com.jakewharton.u2020.ui; import com.jakewharton.u2020.IsInstrumentationTest; import com.jakewharton.u2020.ui.debug.DebugView; import com.jakewharton.u2020.ui.debug.DebugViewContainer; import com.jakewharton.u2020.ui.debug.SocketActivityHierarchyServer; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; @Module( injects = { DebugViewContainer.class, DebugView.class, }, complete = false, library = true, overrides = true ) public class DebugUiModule { @Provides @Singleton ViewContainer provideViewContainer(DebugViewContainer debugViewContainer, @IsInstrumentationTest boolean isInstrumentationTest) { // Do not add the debug controls for when we are running inside of an instrumentation test. return isInstrumentationTest ? ViewContainer.DEFAULT : debugViewContainer; } @Provides @Singleton ActivityHierarchyServer provideActivityHierarchyServer() { return new SocketActivityHierarchyServer(); } }
32.290323
96
0.78022
223532030470a4aaaa20c7fb16725ffa1656e114
17,402
/* * 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.hp.hpl.jena.vocabulary; import com.hp.hpl.jena.rdf.model.*; /** * Vocabulary definitions from vocabularies/dublin-core_terms.xml * @author Auto-generated by schemagen on 13 Feb 2010 15:46 */ public class DCTerms { /** <p>The RDF model that holds the vocabulary terms</p> */ private static Model m_model = ModelFactory.createDefaultModel(); /** <p>The namespace of the vocabulary as a string</p> */ public static final String NS = "http://purl.org/dc/terms/"; /** <p>The namespace of the vocabulary as a string</p> * @see #NS */ public static String getURI() {return NS;} /** <p>The namespace of the vocabulary as a resource</p> */ public static final Resource NAMESPACE = m_model.createResource( NS ); /** <p>A summary of the resource.</p> */ public static final Property abstract_ = m_model.createProperty( "http://purl.org/dc/terms/abstract" ); /** <p>Information about who can access the resource or an indication of its security * status.</p> */ public static final Property accessRights = m_model.createProperty( "http://purl.org/dc/terms/accessRights" ); /** <p>The method by which items are added to a collection.</p> */ public static final Property accrualMethod = m_model.createProperty( "http://purl.org/dc/terms/accrualMethod" ); /** <p>The frequency with which items are added to a collection.</p> */ public static final Property accrualPeriodicity = m_model.createProperty( "http://purl.org/dc/terms/accrualPeriodicity" ); /** <p>The policy governing the addition of items to a collection.</p> */ public static final Property accrualPolicy = m_model.createProperty( "http://purl.org/dc/terms/accrualPolicy" ); /** <p>An alternative name for the resource.</p> */ public static final Property alternative = m_model.createProperty( "http://purl.org/dc/terms/alternative" ); /** <p>A class of entity for whom the resource is intended or useful.</p> */ public static final Property audience = m_model.createProperty( "http://purl.org/dc/terms/audience" ); /** <p>Date (often a range) that the resource became or will become available.</p> */ public static final Property available = m_model.createProperty( "http://purl.org/dc/terms/available" ); /** <p>A bibliographic reference for the resource.</p> */ public static final Property bibliographicCitation = m_model.createProperty( "http://purl.org/dc/terms/bibliographicCitation" ); /** <p>An established standard to which the described resource conforms.</p> */ public static final Property conformsTo = m_model.createProperty( "http://purl.org/dc/terms/conformsTo" ); /** <p>An entity responsible for making contributions to the resource.</p> */ public static final Property contributor = m_model.createProperty( "http://purl.org/dc/terms/contributor" ); /** <p>The spatial or temporal topic of the resource, the spatial applicability of * the resource, or the jurisdiction under which the resource is relevant.</p> */ public static final Property coverage = m_model.createProperty( "http://purl.org/dc/terms/coverage" ); /** <p>Date of creation of the resource.</p> */ public static final Property created = m_model.createProperty( "http://purl.org/dc/terms/created" ); /** <p>An entity primarily responsible for making the resource.</p> */ public static final Property creator = m_model.createProperty( "http://purl.org/dc/terms/creator" ); /** <p>A point or period of time associated with an event in the lifecycle of the * resource.</p> */ public static final Property date = m_model.createProperty( "http://purl.org/dc/terms/date" ); /** <p>Date of acceptance of the resource.</p> */ public static final Property dateAccepted = m_model.createProperty( "http://purl.org/dc/terms/dateAccepted" ); /** <p>Date of copyright.</p> */ public static final Property dateCopyrighted = m_model.createProperty( "http://purl.org/dc/terms/dateCopyrighted" ); /** <p>Date of submission of the resource.</p> */ public static final Property dateSubmitted = m_model.createProperty( "http://purl.org/dc/terms/dateSubmitted" ); /** <p>An account of the resource.</p> */ public static final Property description = m_model.createProperty( "http://purl.org/dc/terms/description" ); /** <p>A class of entity, defined in terms of progression through an educational * or training context, for which the described resource is intended.</p> */ public static final Property educationLevel = m_model.createProperty( "http://purl.org/dc/terms/educationLevel" ); /** <p>The size or duration of the resource.</p> */ public static final Property extent = m_model.createProperty( "http://purl.org/dc/terms/extent" ); /** <p>The file format, physical medium, or dimensions of the resource.</p> */ public static final Property format = m_model.createProperty( "http://purl.org/dc/terms/format" ); /** <p>A related resource that is substantially the same as the pre-existing described * resource, but in another format.</p> */ public static final Property hasFormat = m_model.createProperty( "http://purl.org/dc/terms/hasFormat" ); /** <p>A related resource that is included either physically or logically in the * described resource.</p> */ public static final Property hasPart = m_model.createProperty( "http://purl.org/dc/terms/hasPart" ); /** <p>A related resource that is a version, edition, or adaptation of the described * resource.</p> */ public static final Property hasVersion = m_model.createProperty( "http://purl.org/dc/terms/hasVersion" ); /** <p>An unambiguous reference to the resource within a given context.</p> */ public static final Property identifier = m_model.createProperty( "http://purl.org/dc/terms/identifier" ); /** <p>A process, used to engender knowledge, attitudes and skills, that the described * resource is designed to support.</p> */ public static final Property instructionalMethod = m_model.createProperty( "http://purl.org/dc/terms/instructionalMethod" ); /** <p>A related resource that is substantially the same as the described resource, * but in another format.</p> */ public static final Property isFormatOf = m_model.createProperty( "http://purl.org/dc/terms/isFormatOf" ); /** <p>A related resource in which the described resource is physically or logically * included.</p> */ public static final Property isPartOf = m_model.createProperty( "http://purl.org/dc/terms/isPartOf" ); /** <p>A related resource that references, cites, or otherwise points to the described * resource.</p> */ public static final Property isReferencedBy = m_model.createProperty( "http://purl.org/dc/terms/isReferencedBy" ); /** <p>A related resource that supplants, displaces, or supersedes the described * resource.</p> */ public static final Property isReplacedBy = m_model.createProperty( "http://purl.org/dc/terms/isReplacedBy" ); /** <p>A related resource that requires the described resource to support its function, * delivery, or coherence.</p> */ public static final Property isRequiredBy = m_model.createProperty( "http://purl.org/dc/terms/isRequiredBy" ); /** <p>A related resource of which the described resource is a version, edition, * or adaptation.</p> */ public static final Property isVersionOf = m_model.createProperty( "http://purl.org/dc/terms/isVersionOf" ); /** <p>Date of formal issuance (e.g., publication) of the resource.</p> */ public static final Property issued = m_model.createProperty( "http://purl.org/dc/terms/issued" ); /** <p>A language of the resource.</p> */ public static final Property language = m_model.createProperty( "http://purl.org/dc/terms/language" ); /** <p>A legal document giving official permission to do something with the resource.</p> */ public static final Property license = m_model.createProperty( "http://purl.org/dc/terms/license" ); /** <p>An entity that mediates access to the resource and for whom the resource is * intended or useful.</p> */ public static final Property mediator = m_model.createProperty( "http://purl.org/dc/terms/mediator" ); /** <p>The material or physical carrier of the resource.</p> */ public static final Property medium = m_model.createProperty( "http://purl.org/dc/terms/medium" ); /** <p>Date on which the resource was changed.</p> */ public static final Property modified = m_model.createProperty( "http://purl.org/dc/terms/modified" ); /** <p>A statement of any changes in ownership and custody of the resource since * its creation that are significant for its authenticity, integrity, and interpretation.</p> */ public static final Property provenance = m_model.createProperty( "http://purl.org/dc/terms/provenance" ); /** <p>An entity responsible for making the resource available.</p> */ public static final Property publisher = m_model.createProperty( "http://purl.org/dc/terms/publisher" ); /** <p>A related resource that is referenced, cited, or otherwise pointed to by the * described resource.</p> */ public static final Property references = m_model.createProperty( "http://purl.org/dc/terms/references" ); /** <p>A related resource.</p> */ public static final Property relation = m_model.createProperty( "http://purl.org/dc/terms/relation" ); /** <p>A related resource that is supplanted, displaced, or superseded by the described * resource.</p> */ public static final Property replaces = m_model.createProperty( "http://purl.org/dc/terms/replaces" ); /** <p>A related resource that is required by the described resource to support its * function, delivery, or coherence.</p> */ public static final Property requires = m_model.createProperty( "http://purl.org/dc/terms/requires" ); /** <p>Information about rights held in and over the resource.</p> */ public static final Property rights = m_model.createProperty( "http://purl.org/dc/terms/rights" ); /** <p>A person or organization owning or managing rights over the resource.</p> */ public static final Property rightsHolder = m_model.createProperty( "http://purl.org/dc/terms/rightsHolder" ); /** <p>A related resource from which the described resource is derived.</p> */ public static final Property source = m_model.createProperty( "http://purl.org/dc/terms/source" ); /** <p>Spatial characteristics of the resource.</p> */ public static final Property spatial = m_model.createProperty( "http://purl.org/dc/terms/spatial" ); /** <p>The topic of the resource.</p> */ public static final Property subject = m_model.createProperty( "http://purl.org/dc/terms/subject" ); /** <p>A list of subunits of the resource.</p> */ public static final Property tableOfContents = m_model.createProperty( "http://purl.org/dc/terms/tableOfContents" ); /** <p>Temporal characteristics of the resource.</p> */ public static final Property temporal = m_model.createProperty( "http://purl.org/dc/terms/temporal" ); public static final Property title = m_model.createProperty( "http://purl.org/dc/terms/title" ); /** <p>The nature or genre of the resource.</p> */ public static final Property type = m_model.createProperty( "http://purl.org/dc/terms/type" ); /** <p>Date (often a range) of validity of a resource.</p> */ public static final Property valid = m_model.createProperty( "http://purl.org/dc/terms/valid" ); /** <p>A resource that acts or has the power to act.</p> */ public static final Resource Agent = m_model.createResource( "http://purl.org/dc/terms/Agent" ); /** <p>A group of agents.</p> */ public static final Resource AgentClass = m_model.createResource( "http://purl.org/dc/terms/AgentClass" ); /** <p>A book, article, or other documentary resource.</p> */ public static final Resource BibliographicResource = m_model.createResource( "http://purl.org/dc/terms/BibliographicResource" ); /** <p>A digital resource format.</p> */ public static final Resource FileFormat = m_model.createResource( "http://purl.org/dc/terms/FileFormat" ); /** <p>A rate at which something recurs.</p> */ public static final Resource Frequency = m_model.createResource( "http://purl.org/dc/terms/Frequency" ); /** <p>The extent or range of judicial, law enforcement, or other authority.</p> */ public static final Resource Jurisdiction = m_model.createResource( "http://purl.org/dc/terms/Jurisdiction" ); /** <p>A legal document giving official permission to do something with a Resource.</p> */ public static final Resource LicenseDocument = m_model.createResource( "http://purl.org/dc/terms/LicenseDocument" ); /** <p>A system of signs, symbols, sounds, gestures, or rules used in communication.</p> */ public static final Resource LinguisticSystem = m_model.createResource( "http://purl.org/dc/terms/LinguisticSystem" ); /** <p>A spatial region or named place.</p> */ public static final Resource Location = m_model.createResource( "http://purl.org/dc/terms/Location" ); /** <p>A location, period of time, or jurisdiction.</p> */ public static final Resource LocationPeriodOrJurisdiction = m_model.createResource( "http://purl.org/dc/terms/LocationPeriodOrJurisdiction" ); /** <p>A file format or physical medium.</p> */ public static final Resource MediaType = m_model.createResource( "http://purl.org/dc/terms/MediaType" ); /** <p>A media type or extent.</p> */ public static final Resource MediaTypeOrExtent = m_model.createResource( "http://purl.org/dc/terms/MediaTypeOrExtent" ); /** <p>A method by which resources are added to a collection.</p> */ public static final Resource MethodOfAccrual = m_model.createResource( "http://purl.org/dc/terms/MethodOfAccrual" ); /** <p>A process that is used to engender knowledge, attitudes, and skills.</p> */ public static final Resource MethodOfInstruction = m_model.createResource( "http://purl.org/dc/terms/MethodOfInstruction" ); /** <p>An interval of time that is named or defined by its start and end dates.</p> */ public static final Resource PeriodOfTime = m_model.createResource( "http://purl.org/dc/terms/PeriodOfTime" ); /** <p>A physical material or carrier.</p> */ public static final Resource PhysicalMedium = m_model.createResource( "http://purl.org/dc/terms/PhysicalMedium" ); /** <p>A material thing.</p> */ public static final Resource PhysicalResource = m_model.createResource( "http://purl.org/dc/terms/PhysicalResource" ); /** <p>A plan or course of action by an authority, intended to influence and determine * decisions, actions, and other matters.</p> */ public static final Resource Policy = m_model.createResource( "http://purl.org/dc/terms/Policy" ); /** <p>A statement of any changes in ownership and custody of a resource since its * creation that are significant for its authenticity, integrity, and interpretation.</p> */ public static final Resource ProvenanceStatement = m_model.createResource( "http://purl.org/dc/terms/ProvenanceStatement" ); /** <p>A statement about the intellectual property rights (IPR) held in or over a * Resource, a legal document giving official permission to do something with * a resource, or a statement about access rights.</p> */ public static final Resource RightsStatement = m_model.createResource( "http://purl.org/dc/terms/RightsStatement" ); /** <p>A dimension or extent, or a time taken to play or execute.</p> */ public static final Resource SizeOrDuration = m_model.createResource( "http://purl.org/dc/terms/SizeOrDuration" ); /** <p>A basis for comparison; a reference point against which other things can be * evaluated.</p> */ public static final Resource Standard = m_model.createResource( "http://purl.org/dc/terms/Standard" ); }
54.72327
146
0.688599
79fbe9bb37bf8538e656052ae9bebbba78569cd0
128
package gov.samhsa.c2s.ums.infrastructure.dto; import lombok.Data; @Data public class IdentifierDto { private String id; }
16
46
0.765625
11a12a0450f1ba89d20d888107264a7513b36155
1,640
package io.github.magicquartz.environmentalarmor.mixin; import io.github.apace100.origins.component.OriginComponent; import io.github.apace100.origins.power.DamageOverTimePower; import io.github.apace100.origins.power.PreventEntityRenderPower; import io.github.magicquartz.environmentalarmor.power.EnvironmentalArmorPowers; import io.github.magicquartz.environmentalarmor.registry.ModEffects; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List; @Mixin(PlayerEntity.class) public abstract class PlayerEntityMixin extends LivingEntity { @Shadow public abstract void tick(); protected PlayerEntityMixin(EntityType<? extends LivingEntity> entityType, World world) { super(entityType, world); } @Inject(at = @At("HEAD"), method = "tick") private void tick(CallbackInfo info) { if(OriginComponent.hasPower(this, DamageOverTimePower.class) && isTouchingWaterOrRain() && hasStatusEffect(ModEffects.WATER_RESISTANCE) && EnvironmentalArmorPowers.WATER_DAMAGE.isActive(this)) { // For enderians and blazeborns which are vulnerable to water. List<DamageOverTimePower> powers = OriginComponent.getPowers(this, DamageOverTimePower.class); powers.get(0).setValue(20); } } }
43.157895
202
0.785976
bd62901d2dbea453177da6f6f877c6aa3e444f70
6,357
package life.catalogue.common.date; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import de.undercouch.citeproc.csl.CSLDate; import de.undercouch.citeproc.csl.CSLDateBuilder; import life.catalogue.api.model.CslDate; import org.apache.commons.lang3.StringUtils; import java.time.*; import java.time.temporal.TemporalAccessor; import java.util.Objects; import static java.time.temporal.ChronoField.*; /** * A FuzzyDate encapsulates a {@link TemporalAccessor} instance which is guaranteed to have at least * its YEAR field set. Other fields may be unknown, in which case the date is said to be fuzzy. */ public final class FuzzyDate { private static final int DAY_PER_MONTH = 32; private static final int DAY_PER_YEAR = DAY_PER_MONTH * 13; // only Year, YearMonth or LocalDate allowed here!!! private final TemporalAccessor ta; @JsonCreator public static FuzzyDate of(int year) { return new FuzzyDate(Year.of(year)); } public static FuzzyDate of(int year, int month) { return new FuzzyDate(YearMonth.of(year, month)); } public static FuzzyDate of(int year, int month, int day) { return new FuzzyDate(LocalDate.of(year, month, day)); } public static FuzzyDate now() { return new FuzzyDate(LocalDate.now()); } /** * Reads a CSL date style int array. */ public static FuzzyDate of(int[] parts) { if (parts.length == 1) return of(parts[0]); if (parts.length == 2) return of(parts[0], parts[1]); if (parts.length == 3) return of(parts[0], parts[1], parts[2]); return null; } /** * Potentially incomplete iso date with year required * E.g. 1919, 1919-10, 1919-10-23 */ @JsonCreator public static FuzzyDate of(String isoDate) { if (StringUtils.isBlank(isoDate)) return null; int dashCnt = StringUtils.countMatches(isoDate, '-'); switch (dashCnt) { case 0: return new FuzzyDate(Year.parse(isoDate)); case 1: return new FuzzyDate(YearMonth.parse(isoDate)); case 2: return new FuzzyDate(LocalDate.parse(isoDate)); } throw new IllegalArgumentException("No fuzzy ISO date"); } public static FuzzyDate fromInt(int x) { if (x <= 0) return null; int y = x / DAY_PER_YEAR; x -= y*DAY_PER_YEAR; if (x > 0) { int m = x / DAY_PER_MONTH; x -= m*DAY_PER_MONTH; if (x > 0) { return FuzzyDate.of(y,m,x); } else { return FuzzyDate.of(y,m); } } return FuzzyDate.of(y); } public FuzzyDate(TemporalAccessor ta) { // Won't happen when obtaining a FuzzyDate from the FuzzyDateParser, but // since this is a public constructor ... Objects.requireNonNull(ta, "ta"); // make sure we deal with one of the 3 supported classes if (ta instanceof Year || ta instanceof YearMonth || ta instanceof LocalDate) { this.ta = ta; } else if (!ta.isSupported(YEAR)) { throw new IllegalArgumentException("Cannot create FuzzyDate without a year"); } else { // copy fuzzy date this.ta = bestMatch(ta); } } /** * Returns a {@link LocalDate} if year, month and day are known; a {@link YearMonth} if year and * month are known; or a {@link Year} if only the year is known. * * @return */ private static TemporalAccessor bestMatch(TemporalAccessor ta) { if (ta.isSupported(MONTH_OF_YEAR)) { if (ta.isSupported(DAY_OF_MONTH)) { return LocalDate.of(ta.get(YEAR), ta.get(MONTH_OF_YEAR), ta.get(DAY_OF_MONTH)); } return YearMonth.of(ta.get(YEAR), ta.get(MONTH_OF_YEAR)); } return Year.of(ta.get(YEAR)); } /** * Returns a {@link LocalDate}, setting month and/or day to 1 if unknown. * * @return */ public LocalDate toLocalDate() { if (ta.getClass() == LocalDate.class) { return (LocalDate) ta; } if (ta.getClass() == OffsetDateTime.class) { return ((OffsetDateTime) ta).toLocalDate(); } if (ta.getClass() == LocalDateTime.class) { return ((LocalDateTime) ta).toLocalDate(); } if (ta.isSupported(MONTH_OF_YEAR)) { if (ta.isSupported(DAY_OF_MONTH)) { return LocalDate.of(ta.get(YEAR), ta.get(MONTH_OF_YEAR), ta.get(DAY_OF_MONTH)); } return LocalDate.of(ta.get(YEAR), ta.get(MONTH_OF_YEAR), 1); } return LocalDate.of(ta.get(YEAR), 1, 1); } /** * @return Year, YearMonth or LocalDate instance represeting this fuzzy date */ public TemporalAccessor getDate() { return ta; } public int getYear() { return ta.get(YEAR); } /** * Returns false if year, month and day are known, true otherwise. * * @return */ public boolean isFuzzyDate() { return !ta.isSupported(MONTH_OF_YEAR) || !ta.isSupported(DAY_OF_MONTH); } public CSLDate toCSLDate() { if (ta.isSupported(MONTH_OF_YEAR)) { if (ta.isSupported(DAY_OF_MONTH)) { return new CSLDateBuilder().dateParts(ta.get(YEAR), ta.get(MONTH_OF_YEAR), ta.get(DAY_OF_MONTH)).build(); } return new CSLDateBuilder().dateParts(ta.get(YEAR), ta.get(MONTH_OF_YEAR)).build(); } return new CSLDateBuilder().dateParts(ta.get(YEAR)).build(); } public CslDate toCslDate() { if (ta.isSupported(MONTH_OF_YEAR)) { if (ta.isSupported(DAY_OF_MONTH)) { return new CslDate(ta.get(YEAR), ta.get(MONTH_OF_YEAR), ta.get(DAY_OF_MONTH)); } return new CslDate(ta.get(YEAR), ta.get(MONTH_OF_YEAR)); } return new CslDate(ta.get(YEAR)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FuzzyDate fuzzyDate = (FuzzyDate) o; return Objects.equals(ta, fuzzyDate.ta); } @Override public int hashCode() { return Objects.hash(ta); } @Override @JsonValue public String toString() { return ta.toString(); } /** * Int representation of the fuzzy date. Can be reconstructed via the fromInt factory method. * @return a single int representing the fuzzy date */ public int toInt() { int x = ta.get(YEAR) * DAY_PER_YEAR; if (ta.isSupported(MONTH_OF_YEAR)) { x += ta.get(MONTH_OF_YEAR) * DAY_PER_MONTH; if (ta.isSupported(DAY_OF_MONTH)) { x += ta.get(DAY_OF_MONTH); } } return x; } }
28.635135
113
0.652037
9054a74a876419f346dd8d1844f3475803290c7e
5,632
package com.example.fym.coolweather.activity; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.example.fym.coolweather.R; import com.example.fym.coolweather.service.UpdateWeatheService; import com.example.fym.coolweather.util.HttpCallBackListener; import com.example.fym.coolweather.util.HttpUtil; import com.example.fym.coolweather.util.Utility; /** * Created by Administrator on 2016/5/17 0017. */ public class WeatherActivity extends Activity implements View.OnClickListener{ private TextView cityName; private TextView pubTime; private TextView currentDate; private TextView weatherDesc; private TextView temp1; private TextView temp2; private LinearLayout weatherInfoLayout; private Button home; private Button refresh; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.weather_layout); cityName=(TextView)findViewById(R.id.city_name); pubTime=(TextView)findViewById(R.id.pubTime); currentDate=(TextView)findViewById(R.id.current_date); weatherDesc=(TextView)findViewById(R.id.desc); temp1=(TextView)findViewById(R.id.lowTemp); temp2=(TextView)findViewById(R.id.highTemp); home=(Button)findViewById(R.id.home_button); refresh=(Button)findViewById(R.id.rfresh_button); weatherInfoLayout=(LinearLayout)findViewById(R.id.weather_info_layout); home.setOnClickListener(this); refresh.setOnClickListener(this); String countyCode=getIntent().getStringExtra("countyCode"); if (!TextUtils.isEmpty(countyCode)){ weatherInfoLayout.setVisibility(View.INVISIBLE); queryWeatherCode(countyCode); }else{ showWeatherInfo(); } } @Override public void onClick(View v) { switch (v.getId()){ case R.id.home_button: Intent intent=new Intent(this,ChooseAreaActivity.class); startActivity(intent); finish(); break; case R.id.rfresh_button: SharedPreferences sdf=PreferenceManager.getDefaultSharedPreferences(this); String weather_code=sdf.getString("cityCode","."); cityName.setText("同步中。。。"); if (!TextUtils.isEmpty(weather_code)){ queryWeatherInfo(weather_code); } break; } } public void queryWeatherCode(String countyCode){ String address="http://www.weather.com.cn/data/list3/city"+countyCode+".xml"; queryFromServer(address,"countyCode"); } public void queryWeatherInfo(String weatherCode){ String address="http://www.weather.com.cn/data/cityinfo/"+weatherCode+".html"; queryFromServer(address, "weatherCode"); } public void queryFromServer(final String address,final String type){ HttpUtil.setHttpRequest(address, new HttpCallBackListener() { @Override public void onFinish(String response) { boolean result = false; if (type.equals("countyCode")) { if (!TextUtils.isEmpty(response)) { String[] arrays = response.split("\\|"); if (arrays != null && arrays.length == 2) { String weatherCode = arrays[1]; queryWeatherInfo(weatherCode); } } } else if (type.equals("weatherCode")) { result = Utility.handleWeatherResponse(WeatherActivity.this, response); } if (result) { runOnUiThread(new Runnable() { @Override public void run() { showWeatherInfo(); } }); } } @Override public void onError(Exception e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(WeatherActivity.this, "加载失败", Toast.LENGTH_SHORT); } }); } }); } public void showWeatherInfo(){ SharedPreferences spf= PreferenceManager.getDefaultSharedPreferences(this); String city_Name=spf.getString("cityName", "."); String highTemp=spf.getString("temp1","."); String lowTemp=spf.getString("temp2","."); String weather_Desc=spf.getString("weatherDesc","."); String pTime=spf.getString("pTime","."); String data=spf.getString("data","."); cityName.setText(city_Name); pubTime.setText("今天" + pTime + "发布"); temp1.setText(lowTemp); temp2.setText(highTemp); weatherDesc.setText(weather_Desc); currentDate.setText(data); weatherInfoLayout.setVisibility(View.VISIBLE); Intent intent=new Intent(this, UpdateWeatheService.class); startService(intent); } }
34.341463
91
0.607955
814e3522172b607405cb19d04a94eea73e4ff7bf
5,731
/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package xmlcursor.detailed; import org.apache.xmlbeans.XmlCursor.TokenType; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.junit.Ignore; import org.junit.Test; import xmlcursor.common.BasicCursorTestCase; import xmlcursor.common.Common; import static org.junit.Assert.*; public class InsertNamespaceTest extends BasicCursorTestCase { @Test public void testInsertNamespaceAfterSTART() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); m_xc.insertNamespace("prefix", "value"); m_xc.toStartDoc(); XmlOptions map = new XmlOptions(); map.put(XmlOptions.SAVE_NAMESPACES_FIRST, ""); assertEquals("<foo xmlns:prefix=\"value\" attr0=\"val0\" attr1=\"val1\">text</foo>", m_xc.xmlText(map)); } @Test public void testInsertNamespaceAfterATTR() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.ATTR); toNextTokenOfType(m_xc, TokenType.ATTR); m_xc.insertNamespace("prefix", "value"); m_xc.toStartDoc(); XmlOptions map = new XmlOptions(); map.put(XmlOptions.SAVE_NAMESPACES_FIRST, ""); assertEquals("<foo xmlns:prefix=\"value\" attr0=\"val0\" attr1=\"val1\">text</foo>", m_xc.xmlText(map)); } @Test(expected = IllegalArgumentException.class) public void testInsertNamespaceInsideTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); m_xc.toNextChar(2); assertEquals("xt", m_xc.getChars()); m_xc.insertNamespace("prefix", "value"); } @Test(expected = IllegalArgumentException.class) public void testInsertNamespaceFromSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); m_xc.insertNamespace("prefix", "value"); } @Test(expected = IllegalArgumentException.class) public void testInsertNamespaceAfterPROCINST() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.PROCINST); m_xc.toNextToken(); m_xc.insertNamespace("prefix", "value"); } @Test public void testInsertNamespaceAfterNAMESPACE() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_NS); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.NAMESPACE); m_xc.toNextToken(); m_xc.insertNamespace("prefix", "value"); m_xc.toStartDoc(); assertEquals("<foo xmlns=\"http://www.foo.org\" xmlns:prefix=\"value\"/>", m_xc.xmlText()); } @Test public void testInsertDuplicateNamespace() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); m_xc.insertNamespace("prefix", "http://www.foo.org"); m_xc.insertNamespace("prefix", "http://www.foo.org"); m_xc.toStartDoc(); assertEquals("<foo xmlns:prefix=\"http://www.foo.org\">text</foo>", m_xc.xmlText()); } @Test @Ignore public void testInsertNamespaceWithNullPrefix() throws Exception { // According to Eric V... This test is not valid // Eric's comments: // is erroneous. <foo> must be in no namespace. // By setting the default namespace to "http://www.foo.org" // and having it saved out as such, <foo> would be in that // namespace. So, the saver does not save out that namespace // (note that mapping a prefix to no namespace "" is illegal). // Below is the original code. // m_xo = XmlObject.Factory.parse(Common.XML_FOO, // XmlOptions.AUTOTYPE_DOCUMENT_LAX); // m_xc = m_xo.newCursor(); // toNextTokenOfType(m_xc, TokenType.END); // m_xc.insertNamespace(null, "http://www.foo.org"); // m_xc.toStartDoc(); // assertEquals("<foo xmlns=\"http://www.foo.org\"/>", m_xc.xmlText()); } @Test public void testInsertNamespaceWithNullValue() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.END); //EricV: this should be OK, but make sure the saver // doesn't serialize it since it's not legal XML m_xc.insertNamespace("prefix", null); m_xc.toStartDoc(); assertEquals("<foo/>", m_xc.xmlText()); } @Test(expected = IllegalArgumentException.class) public void testInsertEmptyNamespace() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.END); m_xc.insertNamespace("", ""); } }
38.463087
112
0.664282
fa8fca809dd1c87a5a56f59b9e0d7ea211ec5994
2,342
package com.monst.bankingplugin.config.values; import com.monst.bankingplugin.BankingPlugin; import com.monst.bankingplugin.exceptions.parse.PathParseException; import com.monst.bankingplugin.lang.Message; import com.monst.bankingplugin.lang.Placeholder; import com.monst.bankingplugin.utils.Callback; import com.monst.bankingplugin.utils.Parser; import org.bukkit.command.CommandSender; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class DatabaseFile extends ConfigValue<String, Path> implements NonNativeString<Path> { public DatabaseFile(BankingPlugin plugin) { super(plugin, "database-file", Paths.get("banking.db")); } @Override public Path parse(String input) throws PathParseException { return Parser.parsePath(input, ".db"); } @Override public void afterSet(CommandSender executor) { plugin.reloadEntities(Callback.onResult(banksAndAccounts -> { int numberOfBanks = banksAndAccounts.size(); int numberOfAccounts = banksAndAccounts.values().size(); executor.sendMessage(Message.RELOADED_PLUGIN .with(Placeholder.NUMBER_OF_BANKS).as(numberOfBanks) .and(Placeholder.NUMBER_OF_ACCOUNTS).as(numberOfAccounts) .translate()); })); } @Override public List<String> getTabCompletions(CommandSender sender, String[] args) { if (args.length > 2) return Collections.emptyList(); Stream.Builder<String> tabCompletions = Stream.builder(); tabCompletions.accept(getFormatted()); tabCompletions.accept("banking.db"); Path databaseFolder = plugin.getDataFolder().toPath().resolve("database"); try { Files.walk(databaseFolder) .filter(Files::isRegularFile) .map(databaseFolder::relativize) .map(Path::toString) .filter(fileName -> fileName.endsWith(".db")) .forEach(tabCompletions); } catch (IOException ignored) {} return tabCompletions.build().distinct().collect(Collectors.toList()); } }
37.174603
94
0.677199
f7adf4a1c1bcbcf6bd4db493d7a42740bed0278f
208
package pw.cdmi.open.repositories.jpa; import pw.cdmi.open.repositories.EmployeeAndDeptGroupRepository; public interface JpaEmployeeAndDeptGroupRepository extends EmployeeAndDeptGroupRepository { }
26
92
0.841346
58e66f123ec86ce44d33aa307106923e07b5df72
2,000
package io.muun.apollo.data.os; import io.muun.common.Optional; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import rx.Observable; import java.util.concurrent.TimeUnit; import javax.inject.Inject; public class ClipboardProvider { private final ClipboardManager clipboard; @Inject public ClipboardProvider(Context context) { clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); } /** * Copy some text to the clipboard. * * @param label User-visible label for the pasted data. * @param text The actual text to copy. */ public void copy(String label, String text) { final ClipData clip = ClipData.newPlainText(label, text); clipboard.setPrimaryClip(clip); } /** * Grab some text from the clipboard. */ public Optional<String> paste() { if (!clipboard.hasPrimaryClip()) { return Optional.empty(); } final ClipData primaryClip = clipboard.getPrimaryClip(); if (primaryClip == null || primaryClip.getItemCount() == 0) { return Optional.empty(); } final ClipData.Item item = primaryClip.getItemAt(0); if (item == null) { return Optional.empty(); } final CharSequence text = item.getText(); if (text == null) { return Optional.empty(); } return Optional.of(text.toString()); } /** * Create an Observable that reports changes on the system clipboard (fires on subscribe). */ public Observable<String> watchPrimaryClip() { return Observable .interval(250, TimeUnit.MILLISECONDS) // emits sequential numbers 0+ on each tick .startWith(-1L) // emits -1 immediately (since interval waits for the first delay) .map(i -> paste().orElse("")) .distinctUntilChanged(); } }
27.39726
98
0.625
5a1bf0c05816483d9b93d7c25154b5c468e94272
1,546
package com.clpstudio.tvshowtimespent.datalayer.repository; import com.clpstudio.tvshowtimespent.datalayer.network.listener.OnSuccess; import com.clpstudio.tvshowtimespent.datalayer.network.model.ApiModel; import com.clpstudio.tvshowtimespent.datalayer.network.model.TvShow; import com.clpstudio.tvshowtimespent.datalayer.repository.abstraction.ITvRepository; import com.clpstudio.tvshowtimespent.datalayer.repository.datasource.TvCachedDataSource; import com.clpstudio.tvshowtimespent.datalayer.repository.datasource.TvOnlineDataSource; import java.util.List; import javax.inject.Inject; import rx.Observable; public class TvRepository implements ITvRepository { private TvOnlineDataSource onlineDataSource; private TvCachedDataSource cachedDataSource; @Inject public TvRepository(TvOnlineDataSource onlineDataSource, TvCachedDataSource cachedDataSource) { this.onlineDataSource = onlineDataSource; this.cachedDataSource = cachedDataSource; } @Override public Observable<TvShow> getTvShowById(String id) { return onlineDataSource.getTvShowById(id); } @Override public Observable<ApiModel> getTvShowByName(String name) { return onlineDataSource.getTvShowByName(name); } @Override public Observable<List<String>> getSuggestions() { return cachedDataSource.getSuggestions(); } @Override public void addSuggestion(String suggestion, OnSuccess<Object> listener) { cachedDataSource.addSuggestion(suggestion, listener); } }
31.55102
99
0.785899
f3780be0d5b29895b101346c3bc8a8a7fe4b0818
605
package dp.abstractFactory; import dp.abstractFactory.banking.BankingProjectTeamFactory; public class BankSystem { public static void main(String[] args) { ProjectTeamFactory projectTeamFactory = new BankingProjectTeamFactory(); Developer teamLead = projectTeamFactory.getFirstDeveloper(); Developer developer = projectTeamFactory.getSecondDeveloper(); QA qa = projectTeamFactory.getQA(); PM pm = projectTeamFactory.getPM(); System.out.println("Creating banking project"); teamLead.writeCode(); developer.writeCode(); qa.testCode(); pm.manageProject(); } }
28.809524
76
0.747107
e9db67ae4159d79af450097bc1ab390e61db46a6
1,198
package com.hwadee.spring_mybatis.service.impl; import com.hwadee.spring_mybatis.model.Account; import com.hwadee.spring_mybatis.service.AccountService; import org.junit.Test; import org.junit.Before; import org.junit.After; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Assert; /** * AccountServiceImpl Tester. * * @author <Authors name> * @since <pre>���� 13, 2018</pre> * @version 1.0 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring-context.xml"}) public class AccountServiceImplTest { @Autowired private AccountService accountService; @Before public void before() throws Exception { } @After public void after() throws Exception { } /** * * Method: login(String email, String password) * */ @Test public void testLogin() throws Exception { Account account = accountService.login("[email protected]","123456"); Assert.notNull(account, "success"); System.out.println( account ); } }
23.490196
74
0.75793
0f1e7c20d246e8677f35d22e029fa54a6e4198c7
386
package com.wagner.hackerrank.practice.algorithms.warmup; import java.util.stream.IntStream; public class SimpleArraySum { public static void main(String[] args) { int[] intArray = new int[]{1, 2, 3, 4, 10, 11}; int sum = simpleArraySum(intArray); System.out.println(sum); } private static int simpleArraySum(int[] arr) { return IntStream.of(arr).sum(); } }
22.705882
57
0.686528
b3bc466781c77a36f04832c40e501949c50e09c0
1,662
import org.junit.*; import static org.junit.Assert.*; public class MemberTest { @Before public void tearDown() { Member.clear(); } @Test public void member_instantiatesCorrectly_true() { Member testMember = new Member("Chulo", "Chulo's house", "Being a dog", "Portland"); assertTrue(testMember instanceof Member); } @Test public void member_memberInstatiatesWithVariables_mVariables() { Member testMember = new Member("Chulo", "Chulo's house", "Being a dog", "Portland"); assertEquals("Chulo", testMember.getName()); assertEquals("Chulo's house", testMember.getWork()); assertEquals("Being a dog", testMember.getSpecialty()); assertEquals("Portland", testMember.getHome()); assertEquals(1 , testMember.getId()); } @Test public void all_returnsAllInstancesOfMember_true() { Member firstMember = new Member("Chulo", "Chulo's house", "Being a dog", "Portland"); Member secondMember = new Member("Valentina", "Valentina's house", "Being a cat", "Portland"); assertTrue(Member.all().contains(firstMember)); assertTrue(Member.all().contains(secondMember)); } @Test public void clear_emptiesList_0() { Member testMember = new Member("Chulo", "Chulo's house", "Being a dog", "Portland"); Member.clear(); assertEquals(0, Member.all().size()); } @Test public void find_returnsMemberById_secondMember() { Member firstMember = new Member("Chulo", "Chulo's house", "Being a dog", "Portland"); Member secondMember = new Member("Valentina", "Valentina's house", "Being a cat", "Portland"); assertEquals(secondMember, Member.find(secondMember.getId())); } }
33.24
98
0.690734
50e39f1d75a163a02b8982cb504c73cc8e24370e
2,753
package net.minecraft.server.management; import com.google.common.base.Predicate; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.mojang.authlib.Agent; import com.mojang.authlib.GameProfile; import com.mojang.authlib.ProfileLookupCallback; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; import net.atO; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; import net.minecraft.util.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public final class PreYggdrasilConverter { private static final Logger LOGGER = LogManager.getLogger(); public static final File OLD_IPBAN_FILE = new File("banned-ips.txt"); public static final File OLD_PLAYERBAN_FILE = new File("banned-players.txt"); public static final File OLD_OPS_FILE = new File("ops.txt"); public static final File OLD_WHITELIST_FILE = new File("white-list.txt"); private static void lookupNames(MinecraftServer var0, Collection var1, ProfileLookupCallback var2) { String[] var3 = (String[])Iterators.toArray(Iterators.filter(var1.iterator(), PreYggdrasilConverter::lambda$lookupNames$0), String.class); if(var0.isServerInOnlineMode()) { var0.getGameProfileRepository().findProfilesByNames(var3, Agent.MINECRAFT, var2); } else { for(String var7 : var3) { UUID var8 = EntityPlayer.getUUID(new GameProfile((UUID)null, var7)); GameProfile var9 = new GameProfile(var8, var7); var2.onProfileLookupSucceeded(var9); } } } public static String getStringUUIDFromName(String var0) { if(!StringUtils.isNullOrEmpty(var0) && var0.length() <= 16) { MinecraftServer var1 = MinecraftServer.getServer(); GameProfile var2 = var1.getPlayerProfileCache().getGameProfileForUsername(var0); if(var2.getId() != null) { return var2.getId().toString(); } else if(!var1.isSinglePlayer() && var1.isServerInOnlineMode()) { ArrayList var3 = Lists.newArrayList(); atO var4 = new atO(var1, var3); lookupNames(var1, Lists.newArrayList(new String[]{var0}), var4); return !var3.isEmpty() && ((GameProfile)var3.get(0)).getId() != null?((GameProfile)var3.get(0)).getId().toString():""; } else { return EntityPlayer.getUUID(new GameProfile((UUID)null, var0)).toString(); } } else { return var0; } } private static boolean lambda$lookupNames$0(String var0) { return !StringUtils.isNullOrEmpty(var0); } static Logger access$000() { return LOGGER; } }
40.485294
144
0.695968
028e3fd3e39747e63fc4d4148a2bbf6c93584377
25,695
/* * Copyright 2004-2010 Information & Software Engineering Group (188/1) * Institute of Software Technology and Interactive Systems * Vienna University of Technology, Austria * * 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.ifs.tuwien.ac.at/dm/somtoolbox/license.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package at.tuwien.ifs.somtoolbox.models; import java.io.IOException; import java.util.Properties; import java.util.logging.Logger; import org.apache.commons.lang.NotImplementedException; import com.martiansoftware.jsap.JSAPResult; import com.martiansoftware.jsap.Parameter; import at.tuwien.ifs.somtoolbox.SOMToolboxException; import at.tuwien.ifs.somtoolbox.apps.SOMToolboxApp; import at.tuwien.ifs.somtoolbox.apps.config.AbstractOptionFactory; import at.tuwien.ifs.somtoolbox.apps.config.OptionFactory; import at.tuwien.ifs.somtoolbox.data.InputData; import at.tuwien.ifs.somtoolbox.data.SOMVisualisationData; import at.tuwien.ifs.somtoolbox.data.SharedSOMVisualisationData; import at.tuwien.ifs.somtoolbox.input.SOMInputReader; import at.tuwien.ifs.somtoolbox.input.SOMLibDataWinnerMapping; import at.tuwien.ifs.somtoolbox.input.SOMLibFormatInputReader; import at.tuwien.ifs.somtoolbox.layers.GrowingLayer; import at.tuwien.ifs.somtoolbox.layers.LayerAccessException; import at.tuwien.ifs.somtoolbox.layers.ToroidLayer; import at.tuwien.ifs.somtoolbox.layers.TrainingInterruptionListener; import at.tuwien.ifs.somtoolbox.layers.Unit; import at.tuwien.ifs.somtoolbox.layers.Layer.GridTopology; import at.tuwien.ifs.somtoolbox.layers.quality.QualityMeasure; import at.tuwien.ifs.somtoolbox.output.HTMLOutputter; import at.tuwien.ifs.somtoolbox.output.SOMLibMapOutputter; import at.tuwien.ifs.somtoolbox.output.labeling.AbstractLabeler; import at.tuwien.ifs.somtoolbox.output.labeling.Labeler; import at.tuwien.ifs.somtoolbox.properties.FileProperties; import at.tuwien.ifs.somtoolbox.properties.GHSOMProperties; import at.tuwien.ifs.somtoolbox.properties.PropertiesException; import at.tuwien.ifs.somtoolbox.properties.SOMProperties; import at.tuwien.ifs.somtoolbox.util.StdErrProgressWriter; /** * This class implements the Growing Self-Organizing Map. It is basically a wrapper for the * {@link at.tuwien.ifs.somtoolbox.layers.GrowingLayer} and mainly handles command line execution and parameters. It * implements the {@link at.tuwien.ifs.somtoolbox.models.NetworkModel} interface wich is currently not used, but may be * used in the future. * * @author Michael Dittenbach * @version $Id: GrowingSOM.java 4015 2011-01-26 16:07:49Z mayer $ */ public class GrowingSOM extends AbstractNetworkModel implements SOMToolboxApp { public static final Parameter[] OPTIONS = new Parameter[] { OptionFactory.getSwitchHtmlOutput(false), OptionFactory.getOptLabeling(false), OptionFactory.getOptNumberLabels(false), OptionFactory.getOptWeightVectorFileInit(false), OptionFactory.getOptMapDescriptionFile(false), OptionFactory.getSwitchSkipDataWinnerMapping(), OptionFactory.getOptNumberWinners(false), OptionFactory.getOptProperties(true), OptionFactory.getOptUseMultiCPU(false) }; public static final Type APPLICATION_TYPE = Type.Training; public static String DESCRIPTION = "Provides a Growing Grid and a static SOM (with the growth parameters disabled)"; // TODO: Long_Description public static String LONG_DESCRIPTION = "Provides a Growing Grid (Bernd Fritzke, 1995), i.e. a Self-Organising Map that can dynamically grow by inserting whole rows or cells. When setting the growth-controlling parameters to disable growth, it can also be used to train a standard SOM."; /** * Method for stand-alone execution of map training. Options are:<br/> * <ul> * <li>-h toggles HTML output</li> * <li>-l name of class implementing the labeling algorithm</li> * <li>-n number of labels to generate</li> * <li>-w name of weight vector file in case of training an already trained map</li> * <li>-m name of map description file in case of training an already trained map</li> * <li>--noDWM switch to not write the data winner mapping file</li> * <li>properties name of properties file, mandatory</li> * </ul> * * @param args the execution arguments as stated above. */ public static void main(String[] args) { InputData data = null; FileProperties fileProps = null; GrowingSOM som = null; SOMProperties somProps = null; String networkModelName = "GrowingSOM"; // register and parse all options JSAPResult config = OptionFactory.parseResults(args, OPTIONS); Logger.getLogger("at.tuwien.ifs.somtoolbox").info("starting" + networkModelName); int cpus = config.getInt("cpus", 1); int systemCPUs = Runtime.getRuntime().availableProcessors(); // We do not use more CPUs than available! if (cpus > systemCPUs) { String msg = "Number of CPUs required exceeds number of CPUs available."; if (cpus > 2 * systemCPUs) { msg += "Limiting to twice the number of available processors: " + 2 * systemCPUs; cpus = 2 * systemCPUs; } Logger.getLogger("at.tuwien.ifs.somtoolbox").warning(msg); } GrowingLayer.setNO_CPUS(cpus); String propFileName = AbstractOptionFactory.getFilePath(config, "properties"); String weightFileName = AbstractOptionFactory.getFilePath(config, "weightVectorFile"); String mapDescFileName = AbstractOptionFactory.getFilePath(config, "mapDescriptionFile"); String labelerName = config.getString("labeling", null); int numLabels = config.getInt("numberLabels", DEFAULT_LABEL_COUNT); boolean skipDataWinnerMapping = config.getBoolean("skipDataWinnerMapping", false); Labeler labeler = null; // TODO: use parameter for max int numWinners = config.getInt("numberWinners", SOMLibDataWinnerMapping.MAX_DATA_WINNERS); if (labelerName != null) { // if labeling then label try { labeler = AbstractLabeler.instantiate(labelerName); Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Instantiated labeler " + labelerName); } catch (Exception e) { Logger.getLogger("at.tuwien.ifs.somtoolbox").severe( "Could not instantiate labeler \"" + labelerName + "\"."); System.exit(-1); } } if (weightFileName == null) { Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Training a new SOM."); } else { Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Further training of an already trained SOM."); } try { fileProps = new FileProperties(propFileName); somProps = new SOMProperties(propFileName); } catch (PropertiesException e) { Logger.getLogger("at.tuwien.ifs.somtoolbox").severe(e.getMessage() + " Aborting."); System.exit(-1); } data = getInputData(fileProps); if (weightFileName == null) { som = new GrowingSOM(data.isNormalizedToUnitLength(), somProps, data); } else { try { som = new GrowingSOM(new SOMLibFormatInputReader(weightFileName, null, mapDescFileName)); } catch (Exception e) { Logger.getLogger("at.tuwien.ifs.somtoolbox").severe(e.getMessage() + " Aborting."); System.exit(-1); } } if (somProps.getDumpEvery() > 0) { IntermediateSOMDumper dumper = som.new IntermediateSOMDumper(fileProps); som.layer.setTrainingInterruptionListener(dumper, somProps.getDumpEvery()); } // setting input data so it is accessible by map output som.setSharedInputObjects(new SharedSOMVisualisationData(null, null, null, null, fileProps.vectorFileName(true), fileProps.templateFileName(true), null)); som.getSharedInputObjects().setData(SOMVisualisationData.INPUT_VECTOR, data); som.train(data, somProps); if (labelerName != null) { // if labeling then label labeler.label(som, data, numLabels); } try { SOMLibMapOutputter.write(som, fileProps.outputDirectory(), fileProps.namePrefix(false), true, somProps, fileProps); } catch (IOException e) { // TODO: create new exception type Logger.getLogger("at.tuwien.ifs.somtoolbox").severe( "Could not open or write to output file " + fileProps.namePrefix(false) + ": " + e.getMessage()); System.exit(-1); } if (!skipDataWinnerMapping) { numWinners = Math.min(numWinners, som.getLayer().getXSize() * som.getLayer().getYSize()); try { SOMLibMapOutputter.writeDataWinnerMappingFile(som, data, numWinners, fileProps.outputDirectory(), fileProps.namePrefix(false), true); } catch (IOException e) { Logger.getLogger("at.tuwien.ifs.somtoolbox").severe( "Could not open or write to output file " + fileProps.namePrefix(false) + ": " + e.getMessage()); System.exit(-1); } } else { Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Skipping writing data winner mapping file"); } if (config.getBoolean("htmlOutput") == true) { try { new HTMLOutputter().write(som, fileProps.outputDirectory(), fileProps.namePrefix(false)); } catch (IOException e) { // TODO: create new exception type Logger.getLogger("at.tuwien.ifs.somtoolbox").severe( "Could not open or write to output file " + fileProps.namePrefix(false) + ": " + e.getMessage()); System.exit(-1); } } Logger.getLogger("at.tuwien.ifs.somtoolbox").info( "finished" + networkModelName + "(" + som.getLayer().getGridLayout() + ", " + som.getLayer().getGridTopology() + ")"); } protected GrowingLayer layer = null; public GrowingSOM(Properties properties) throws PropertiesException { FileProperties fileProps = new FileProperties(properties); SOMProperties somProps = new SOMProperties(properties); InputData data = getInputData(fileProps); // setting input data so it is accessible by map output setSharedInputObjects(new SharedSOMVisualisationData(null, null, null, null, fileProps.vectorFileName(true), fileProps.templateFileName(true), null)); getSharedInputObjects().setData(SOMVisualisationData.INPUT_VECTOR, data); initLayer(data.isNormalizedToUnitLength(), somProps, data); train(data, somProps); if (somProps.getDumpEvery() > 0) { IntermediateSOMDumper dumper = new IntermediateSOMDumper(fileProps); layer.setTrainingInterruptionListener(dumper, somProps.getDumpEvery()); } } /** * Constructs a new <code>GrowingSOM</code> with <code>dim</code>-dimensional weight vectors. Argument * <code>norm</code> determines whether the randomly initialised weight vectors should be normalised to unit length * or not. * * @param norm specifies if the weight vectors are to be normalised to unit length. * @param props the network properties. */ public GrowingSOM(boolean norm, SOMProperties props, InputData data) { initLayer(norm, props, data); } private void initLayer(boolean norm, SOMProperties props, InputData data) { if (props.getGridTopology() == GridTopology.planar) { layer = new GrowingLayer(props.xSize(), props.ySize(), props.zSize(), props.metricName(), data.dim(), norm, props.pca(), props.randomSeed(), data); } else if (props.getGridTopology() == GridTopology.toroid) { layer = new ToroidLayer(props.xSize(), props.ySize(), props.zSize(), props.metricName(), data.dim(), norm, props.pca(), props.randomSeed(), data); } else { throw new NotImplementedException("Supported for grid topology " + props.getGridTopology() + " not yet implemented."); } } /** * Constructs and trains a new <code>GrowingSOM</code>. All the non-specified parameters will be automatically set * to <i>"default"</i> values. */ public GrowingSOM(int xSize, int ySize, int numIterations, InputData data) throws PropertiesException { SOMProperties props = new SOMProperties(xSize, ySize, numIterations, SOMProperties.defaultLearnRate); initLayer(false, props, data); train(data, props); } /** Constructs and trains a new <code>GrowingSOM</code>. */ public GrowingSOM(int xSize, int ySize, int zSize, String metricName, int numIterations, boolean normalised, boolean usePCAInit, int randomSeed, InputData data) throws PropertiesException { SOMProperties props = new SOMProperties(xSize, ySize, zSize, randomSeed, 0, numIterations, SOMProperties.defaultLearnRate, -1, -1, null, usePCAInit); initLayer(false, props, data); train(data, props); } /** * Constructs a new <code>GrowingSOM</code> with <code>dim</code>-dimensional weight vectors. Argument * <code>norm</code> determines whether the randlomy initialized weight vectors should be normalized to unit length * or not. In hierarchical network models consisting of multiple maps such as the {@link GHSOM}, a unique identifier * is assigned by argument <code>id</code> and the superordinate unit is provided by argument <code>su</code>. * * @param id a unique identifier used in hierarchies of maps (e.g. the <code>GHSOM</code>). * @param su the superordinate unit of the map. * @param dim the dimensionality of the weight vectors. * @param norm specifies if the weight vectors are to be normalized to unit length. * @param props the network properties. */ public GrowingSOM(int id, Unit su, int dim, boolean norm, SOMProperties props, InputData data) { layer = new GrowingLayer(id, su, props.xSize(), props.ySize(), props.zSize(), props.metricName(), dim, norm, props.pca(), props.randomSeed(), data); } /** * Private constructor used recursively in hierarchical network models consisting of multiple maps. A unique * identifier is assigned by argument <code>id</code> and the superordinate unit is provided by argument * <code>su</code>. * * @param id a unique identifier used in hierarchies of maps (e.g. the <code>GHSOM</code>). * @param su the superordinate unit of the map. * @param ir an object implementing the <code>SOMinputReader</code> interface to load an already trained model. */ protected GrowingSOM(int id, Unit su, SOMInputReader ir) { Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Starting layer restoration."); // FIXME: the initialisation of the layer should actually be done in the layer class itself try { // TODO: think about rand seed (7), use map description file when provided layer = new GrowingLayer(id, su, ir.getXSize(), ir.getYSize(), ir.getZSize(), ir.getMetricName(), ir.getDim(), ir.getVectors(), 7); } catch (SOMToolboxException e) { Logger.getLogger("at.tuwien.ifs.somtoolbox").severe(e.getMessage()); System.exit(-1); } labelled = ir.isLabelled(); restoreLayer(id, ir, layer); } protected GrowingSOM(int id, Unit su, SOMInputReader ir, GrowingLayer layer) { this.layer = layer; labelled = ir.isLabelled(); restoreLayer(id, ir, layer); } private void restoreLayer(int id, SOMInputReader ir, GrowingLayer layer) { layer.setGridLayout(ir.getGridLayout()); layer.setGridTopology(ir.getGridTopology()); contentType = ir.getContentType(); int numUnits = layer.getXSize() * layer.getYSize(); int currentUnitNum = 0; Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Restoring state of " + numUnits + " units: "); StdErrProgressWriter progressWriter = new StdErrProgressWriter(numUnits, "Restoring state of unit ", 10); try { for (int j = 0; j < layer.getYSize(); j++) { for (int i = 0; i < layer.getXSize(); i++) { // adapted to mnemonic (sparse) SOMs if (layer.getUnit(i, j, 0) == null) { // if this unit is empty, i.e. not part of the mnemonic map // --> we skip it progressWriter.progress("Skipping empty unit " + i + "/" + j + ", ", (currentUnitNum + 1)); } else { // otherwise we read this unit progressWriter.progress("Restoring state of unit " + i + "/" + j + ", ", (currentUnitNum + 1)); layer.getUnit(i, j, 0).restoreMappings(ir.getNrVecMapped(i, j), ir.getMappedVecs(i, j), ir.getMappedVecsDist(i, j)); layer.getUnit(i, j, 0).restoreLabels(ir.getNrUnitLabels(i, j), ir.getUnitLabels(i, j), ir.getUnitLabelsQe(i, j), ir.getUnitLabelsWgt(i, j)); layer.getUnit(i, j, 0).restoreKaskiLabels(ir.getNrKaskiLabels(i, j), ir.getKaskiUnitLabels(i, j), ir.getKaskiUnitLabelsWgt(i, j)); layer.getUnit(i, j, 0).restoreKaskiGateLabels(ir.getNrKaskiGateLabels(i, j), ir.getKaskiGateUnitLabels(i, j, 0)); if (ir.getNrSomsMapped(i, j) > 0) { // if expanded then create new growingsom String subWeightFileName = null; if (ir.getWeightVectorFileName() != null) { subWeightFileName = ir.getFilePath() + ir.getUrlMappedSoms(i, j)[0] + SOMLibFormatInputReader.weightFileNameSuffix; } String subUnitFileName = null; if (ir.getUnitDescriptionFileName() != null) { subUnitFileName = ir.getFilePath() + ir.getUrlMappedSoms(i, j)[0] + SOMLibFormatInputReader.unitFileNameSuffix; } String subMapFileName = null; if (ir.getMapDescriptionFileName() != null) { subMapFileName = ir.getFilePath() + ir.getUrlMappedSoms(i, j)[0] + SOMLibFormatInputReader.mapFileNameSuffix; } try { layer.getUnit(i, j, 0).setMappedSOM( new GrowingSOM(++id, layer.getUnit(i, j, 0), new SOMLibFormatInputReader( subWeightFileName, subUnitFileName, subMapFileName))); } catch (Exception e) { Logger.getLogger("at.tuwien.ifs.somtoolbox").severe(e.getMessage() + " Aborting."); System.exit(-1); } } } currentUnitNum++; } } // TODO FIXME : pass the quality measure as parameter! String qualityMeasureName = "at.tuwien.ifs.somtoolbox.layers.quality.QuantizationError.mqe"; layer.setQualityMeasure(qualityMeasureName); layer.setCommonVectorLabelPrefix(ir.getCommonVectorLabelPrefix()); } catch (LayerAccessException e) { Logger.getLogger("at.tuwien.ifs.somtoolbox").severe(e.getMessage()); System.exit(-1); } Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Finished layer restoration."); // layer.calculateQuantizationErrorAfterTraining(); is done by the unit. } /** * Constructs an already trained <code>GrowingSOM</code> with a <code>SOMInputReader</code> provided by argument * <code>ir</code>. * * @param ir an object implementing the <code>SOMinputReader</code> interface to load an already trained model. */ public GrowingSOM(SOMInputReader ir) { this(1, null, ir); } /** only used for subclassing */ protected GrowingSOM() { } /** * Returns the actual map layer. * * @return the actual map layer */ public GrowingLayer getLayer() { return layer; } /** * Trains the map with the input data and training parameters specified in the properties provided by argument * <code>props</code>. If the value of property <code>tau</code> is 1, a fix-sized layer is trained, otherwise the * layer grows until a certain quality criterion determined by <code>tau</code> and the mean quantization error * specified by argument <code>mqe0</code> of the data (which is automatically calculated) is reached. This method * is usually used for GHSOM training. * * @param data input data to train the map with. * @param props the training properties. * @param targetQualityValue the desired granularity of data representation. Used for maps in GHSOMs. */ public QualityMeasure train(InputData data, GHSOMProperties props, double targetQualityValue, String qualityMeasureName) { // call training function depending on the properties (iterations || cycles) int iterationsToTrain = 0; if (props.numIterations() > 0) { iterationsToTrain = props.numIterations(); } else { iterationsToTrain = props.numCycles() * data.numVectors(); } return layer.train(data, props.learnrate(), props.sigma(), iterationsToTrain, 0, props.tau(), targetQualityValue, qualityMeasureName, props); } /** * Trains the map with the input data and training parameters specified in the properties provided by argument * <code>props</code>. If the value of property <code>tau</code> is 1, a fix-sized layer is trained, otherwise the * layer grows until a certain quality criterion determined by <code>tau</code> and the mean quantization error of * the data (which is automatically calculated) is reached. * * @param data input data to train the map with. * @param props the training properties */ public void train(InputData data, SOMProperties props) { // call training function depending on the properties (iterations || cycles) int iterationsToTrain = 0; if (props.numIterations() > 0) { iterationsToTrain = props.numIterations(); } else { iterationsToTrain = props.numCycles() * data.numVectors(); } layer.train(data, props.learnrate(), props.sigma(), iterationsToTrain, 0, props.tau(), props.growthQualityMeasureName(), props); } @Override public boolean equals(Object o) { if (o instanceof GrowingSOM) { // compare the layers for equality return getLayer().equalWeights(((GrowingSOM) o).getLayer()); } // false in all other cases... return false; } private class IntermediateSOMDumper implements TrainingInterruptionListener { private final FileProperties fileProperties; public IntermediateSOMDumper(FileProperties fileProperties) { this.fileProperties = fileProperties; } @Override public void interruptionOccurred(int currentIteration, int numIterations) { // FIXME: maybe skip writing the SOM at 0 iterations (0 mod x == 0 ...) String filename = fileProperties.namePrefix(false) + "_" + currentIteration; try { SOMLibMapOutputter.writeWeightVectorFile(GrowingSOM.this, fileProperties.outputDirectory(), filename, true, "$CURRENT_ITERATION=" + currentIteration, "$NUM_ITERATIONS=" + numIterations); } catch (IOException e) { Logger.getLogger("at.tuwien.ifs.somtoolbox").severe( "Could not open or write to output file " + filename + ": " + e.getMessage()); } } } /* (non-Javadoc) * @see java.lang.Object#clone() */ @Override public Object clone() throws CloneNotSupportedException { GrowingSOM newGSOM = new GrowingSOM(); newGSOM.labelled = this.labelled; newGSOM.layer = (GrowingLayer) this.layer.clone(); newGSOM.sharedInputObjects = this.sharedInputObjects; newGSOM.trainingStart = this.trainingStart; return newGSOM; } }
49.224138
291
0.637128
39c5e223028a53ae4f20fb8c66238778e2dd17c9
626
package resonant.core.content; import net.minecraft.item.Item; import net.minecraft.util.Icon; import resonant.core.ResonantEngine; import resonant.lib.References; /** An Base Item Class for Basic Components. Do not use this! Make your own! * * @author Calclavia */ public class ItemBase extends Item { protected final Icon[] icons = new Icon[256]; public ItemBase(String name, int id) { super(References.CONFIGURATION.getItem(name, id).getInt(id)); this.setUnlocalizedName(References.PREFIX + name); this.setTextureName(References.PREFIX + name); this.setNoRepair(); } }
27.217391
76
0.709265
d73bc42a54359dda8166283107924cc761b52d4c
912
package com.roncoo.education.user.service.dao; import com.roncoo.education.user.service.common.resq.UserExtViewRESQ; import com.roncoo.education.user.service.dao.impl.mapper.entity.UserLogInvite; import com.roncoo.education.user.service.dao.impl.mapper.entity.UserLogInviteExample; import com.roncoo.education.util.base.Page; import com.roncoo.education.util.base.Result; import java.util.List; /** * 用户邀请记录表 服务类 * * @author husend * @since 2020-05-19 */ public interface UserLogInviteDao { int save(UserLogInvite record); int deleteById(Long id); int updateById(UserLogInvite record); UserLogInvite getById(Long id); Page<UserLogInvite> listForPage(int pageCurrent, int pageSize, UserLogInviteExample example); UserLogInvite getByInvitedUserNo(Long userNo); List<UserLogInvite> getByInviteUserNo(Long userNo); }
27.636364
105
0.730263
d0fcd8e9371ce4dfc47e0e00c8307566a41ffe64
199
package com.tencent.tmsecure.module.optimize; public class ProcessEntity { public String mPackageName; public int mPriority; public int mPriorityGroup; public String mProcessName; }
22.111111
45
0.763819
541dcc3844fe157b8a3c77621dc3c0f35fad3488
1,218
package br.odb.moonshot; import java.util.ArrayList; import java.util.List; import br.odb.gameapp.ConsoleApplication; import br.odb.gameapp.command.UserCommandLineAction; import br.odb.gameapp.command.CommandParameterDefinition; import br.odb.libscene.GroupSector; import br.odb.libscene.MeshNode; import br.odb.libscene.SceneNode; public class ClearMeshCommand extends UserCommandLineAction { @Override public String getDescription() { return ""; } @Override public void run(ConsoleApplication app, String arg1) throws Exception { LevelEditor editor = (LevelEditor) app; clearMeshesOn( editor.world.masterSector ); } private void clearMeshesOn(GroupSector sector ) { List< MeshNode > nodes = new ArrayList<MeshNode>(); for ( SceneNode sn : sector.getSons() ) { if ( sn instanceof MeshNode ) { nodes.add( (MeshNode) sn ); } else if ( sn instanceof GroupSector ) { clearMeshesOn( (GroupSector) sn ); } } for ( MeshNode node : nodes ) { sector.removeChild( node ); } } @Override public String toString() { return "clear-meshes"; } @Override public CommandParameterDefinition[] requiredOperands() { return new CommandParameterDefinition[0]; } }
22.145455
72
0.727422
ef8ab6e0ea9990fa708885108769da9b3de5da0b
419
package com.tangzhangss.commonutils.utils; import cn.hutool.json.JSONObject; import org.apache.commons.lang.StringUtils; public class RequestUtil { public static void checkNullParam(JSONObject object,String ...keys){ for (int i = 0; i < keys.length; i++) { if(StringUtils.isBlank(object.getStr(keys[i]))) ExceptionUtil.throwException("参数:"+keys[i]+",不能为空!"); } } }
29.928571
72
0.656325
c856a81cef7115a5efba4043e9845a859af3685c
1,753
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.protocol.oidc.utils; import java.io.IOException; import java.security.PublicKey; import org.keycloak.broker.provider.util.SimpleHttp; import org.keycloak.jose.jwk.JSONWebKeySet; import org.keycloak.jose.jwk.JWK; import org.keycloak.jose.jwk.JWKParser; import org.keycloak.util.JsonSerialization; /** * @author <a href="mailto:[email protected]">Marek Posolda</a> */ public class JWKSUtils { public static JSONWebKeySet sendJwksRequest(String jwksURI) throws IOException { String keySetString = SimpleHttp.doGet(jwksURI).asString(); return JsonSerialization.readValue(keySetString, JSONWebKeySet.class); } public static PublicKey getKeyForUse(JSONWebKeySet keySet, JWK.Use requestedUse) { for (JWK jwk : keySet.getKeys()) { JWKParser parser = JWKParser.create(jwk); if (parser.getJwk().getPublicKeyUse().equals(requestedUse.asString()) && parser.isAlgorithmSupported(jwk.getKeyType())) { return parser.toPublicKey(); } } return null; } }
34.372549
133
0.722191
3db8c154625ab78c1630d325dc25d1eb6ddb0935
3,257
/* * Copyright 2012-2014 Dan Cioca * * 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.dci.intellij.dbn.connection; import com.dci.intellij.dbn.common.Icons; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.Icon; import java.util.ArrayList; import java.util.List; public class ProjectConnectionBundle extends ConnectionBundle implements ProjectComponent { private List<ConnectionHandler> virtualConnections = new ArrayList<ConnectionHandler>(); private ProjectConnectionBundle(Project project) { super(project); virtualConnections.add(new VirtualConnectionHandler( "virtual-oracle-connection", "Virtual - Oracle 10.1", DatabaseType.ORACLE, project)); virtualConnections.add(new VirtualConnectionHandler( "virtual-mysql-connection", "Virtual - MySQL 5.0", DatabaseType.MYSQL, project)); virtualConnections.add(new VirtualConnectionHandler( "virtual-iso92-sql-connection", "Virtual - ISO-92 SQL", DatabaseType.UNKNOWN, project)); } @Override public String getDisplayName() { return "DB Connections"; } @NotNull @Override public String getId() { return "DBNavigator.Project.ConnectionBundle"; } public static ProjectConnectionBundle getInstance(Project project) { return project.getComponent(ProjectConnectionBundle.class); } public List<ConnectionHandler> getVirtualConnections() { return virtualConnections; } public ConnectionHandler getVirtualConnection(String id) { for (ConnectionHandler virtualConnection : virtualConnections) { if (virtualConnection.getId().equals(id)) { return virtualConnection; } } return null; } public Icon getIcon(int flags) { return Icons.PROJECT; } /*************************************** * ProjectComponent * ****************************************/ @NotNull @NonNls public String getComponentName() { return "DBNavigator.Project.ConnectionManager"; } public void projectOpened() {} public void projectClosed() {} public void initComponent() {} public void disposeComponent() { dispose(); } @Override public String toString() { return "ProjectConnectionBundle"; } public int compareTo(Object o) { return -1; } }
29.880734
92
0.641695
428170756e319e08e41533ee5a8796c04f0a667f
4,868
package com.example.hoangdang.diemdanh.studentQuiz; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.example.hoangdang.diemdanh.R; import com.example.hoangdang.diemdanh.SupportClass.AppVariable; import com.example.hoangdang.diemdanh.SupportClass.SecurePreferences; import com.example.hoangdang.diemdanh.currentSessionImage.ApiAdapter; import com.example.hoangdang.diemdanh.currentSessionImage.GPSTracker; import com.example.hoangdang.diemdanh.currentSessionImage.VolleyCallBack; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import butterknife.BindView; import butterknife.ButterKnife; import static com.example.hoangdang.diemdanh.currentSessionImage.MyFaceDetect.GET_GPS; import static com.example.hoangdang.diemdanh.currentSessionImage.MyFaceDetect.removeAccent; public class ResultActivity extends AppCompatActivity { @BindView(R.id.correct_question) TextView _correct_question; @BindView(R.id.message) TextView _message; @BindView(R.id.view_detail) Button _viewDetail; @BindView(R.id.close) Button _close; @BindView(R.id.toolbar_quiz_result) Toolbar toolbar; JSONObject quizConfig; int countCorrect; int total; boolean noAnswer; int quiz_type; public ArrayList<String> selecteds; public ArrayList<String> corrects; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); selecteds = (ArrayList<String>)this.getIntent().getSerializableExtra("selecteds"); corrects = (ArrayList<String>)this.getIntent().getSerializableExtra("corrects"); ButterKnife.bind(this); toolbar.setTitle("QUIZ RESULT"); quizConfig = null; SharedPreferences pref = new SecurePreferences(this); int temp = pref.getInt(AppVariable.QUIZ_BLANK, 0); noAnswer = temp == 0; countCorrect = pref.getInt(AppVariable.QUIZ_CORRECT, 0); total = pref.getInt(AppVariable.QUIZ_TOTAL, 0); quiz_type = pref.getInt(AppVariable.QUIZ_TYPE, 0); setButtonListener(); } private void setButtonListener() { _close.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); _viewDetail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDetail(); } }); _correct_question.setText("Correct: " + String.valueOf(countCorrect) + " out of " + String.valueOf(total)); String text; if (noAnswer){ text = "Your Attendance is not checked. You didn't answer any question."; } else { if (quiz_type == 0 || countCorrect == total){ text = "Your Attendance is checked"; // Get GPS SharedPreferences pref = new SecurePreferences(this); Intent intent = new Intent(this, GPSTracker.class); startActivityForResult(intent, GET_GPS); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String mylat = sharedPref.getString("Lat","Error"); String mylong = sharedPref.getString("Long","Error"); Date currentTime = Calendar.getInstance().getTime(); String log = "Toa do: (" + mylat + "," + mylong +") " + " - Method: Quiz" + " - Time: " + currentTime +"$"; Log.wtf("HiepQuiz",log ); //Update Log final ApiAdapter apiAdapter = new ApiAdapter(ResultActivity.this); apiAdapter.UpdateLog(this,log, removeAccent( pref.getString(AppVariable.USER_NAME, "EMPTY")), new VolleyCallBack() { @Override public void onSuccess(String result) { } }); } else { text = "Your Attendance is not checked. Miscellaneous quiz requires you to be 100% correct to be checked"; } } _message.setText(text); } private void showDetail(){ Intent intent = new Intent(this, DetailActivity.class); intent.putExtra("selecteds", selecteds); intent.putExtra("corrects", corrects); startActivity(intent); } }
33.342466
132
0.652424
b6c3f223027e0c26606cd51a4805608eaf86cd36
2,119
/* * Copyright © 2014 Cask Data, 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 co.cask.cdap.examples.purchase; import co.cask.cdap.api.annotation.ProcessInput; import co.cask.cdap.api.common.Bytes; import co.cask.cdap.api.flow.flowlet.AbstractFlowlet; import co.cask.cdap.api.flow.flowlet.OutputEmitter; import co.cask.cdap.api.flow.flowlet.StreamEvent; /** * This Flowlet reads events from a Stream and parses them as sentences of the form * <pre><name> bought <n> <items> for $<price></pre>. The event is then converted into * a Purchase object and emitted. If the event does not have this form, it is dropped. */ public class PurchaseStreamReader extends AbstractFlowlet { private OutputEmitter<Purchase> out; @ProcessInput public void process(StreamEvent event) { String body = Bytes.toString(event.getBody()); // <name> bought <n> <items> for $<price> String[] tokens = body.split(" "); if (tokens.length != 6) { return; } String customer = tokens[0]; if (!"bought".equals(tokens[1])) { return; } int quantity = Integer.parseInt(tokens[2]); String item = tokens[3]; if (quantity != 1 && item.length() > 1 && item.endsWith("s")) { item = item.substring(0, item.length() - 1); } if (!"for".equals(tokens[4])) { return; } String price = tokens[5]; if (!price.startsWith("$")) { return; } int amount = Integer.parseInt(tokens[5].substring(1)); Purchase purchase = new Purchase(customer, item, quantity, amount, System.currentTimeMillis()); out.emit(purchase); } }
33.634921
99
0.684285
e100394baf60d9301dc158b25bb45f03acbd28b4
1,140
package com.fsoft.team.entity; import java.io.Serializable; import java.time.LocalDateTime; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "tbl_enrollements") public class Enrollement implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long enrollID; @Column(name = "enrollDate") private LocalDateTime enrollDate; @Column(name = "isComplete") private boolean isComplete; @ManyToOne() @JoinColumn(name = "username") private User user; @ManyToOne() @JoinColumn(name = "courseID") private Course course; }
24.782609
56
0.740351
e6712da50438e7c00cc4031eeaa612ee7403b97f
5,747
package tmpgnmanntest; import java.io.File; import java.util.LinkedHashMap; import java.util.Map; import us.kbase.auth.AuthToken; import us.kbase.common.service.JsonServerMethod; import us.kbase.common.service.JsonServerServlet; import us.kbase.common.service.JsonServerSyslog; import us.kbase.common.service.RpcContext; //BEGIN_HEADER import genomeannotationfileutil.GenbankToGenomeAnnotationParams; import genomeannotationfileutil.GenomeAnnotationDetails; import genomeannotationfileutil.GenomeAnnotationFileUtilClient; import java.net.URL; import java.nio.file.Files; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FileUtils; import us.kbase.common.service.Tuple4; import us.kbase.genbank.GenometoGbk; import us.kbase.kbasegenomes.Feature; import us.kbase.kbasegenomes.Genome; //END_HEADER /** * <p>Original spec-file module name: TmpGnmAnnTest</p> * <pre> * A KBase module: TmpGnmAnnTest * </pre> */ public class TmpGnmAnnTestServer extends JsonServerServlet { private static final long serialVersionUID = 1L; private static final String version = "0.0.1"; private static final String gitUrl = ""; private static final String gitCommitHash = ""; //BEGIN_CLASS_HEADER private File scratchDir = null; //END_CLASS_HEADER public TmpGnmAnnTestServer() throws Exception { super("TmpGnmAnnTest"); //BEGIN_CONSTRUCTOR scratchDir = new File(config.get("scratch")); //END_CONSTRUCTOR } /** * <p>Original spec-file function name: prepare_test_genome_annotation_from_proteins</p> * <pre> * </pre> * @param params instance of type {@link tmpgnmanntest.PrepareTestGenomeAnnotationFromProteinsParams PrepareTestGenomeAnnotationFromProteinsParams} * @return parameter "ga_ref" of String */ @JsonServerMethod(rpc = "TmpGnmAnnTest.prepare_test_genome_annotation_from_proteins", async=true) public String prepareTestGenomeAnnotationFromProteins(PrepareTestGenomeAnnotationFromProteinsParams params, AuthToken authPart, RpcContext jsonRpcContext) throws Exception { String returnVal = null; //BEGIN prepare_test_genome_annotation_from_proteins File tempDir = Files.createTempDirectory(scratchDir.toPath(), "gbk_").toFile(); try { File gbkFile = new File(tempDir, "genome.gbk"); List<Feature> features = new ArrayList<>(); List<String> proteinIds = new ArrayList<>(params.getProteinIdToSequence().keySet()); String contigId = "contig1"; long featureStart = 1; for (int genePos = 0; genePos < proteinIds.size(); genePos++) { String proteinId = proteinIds.get(genePos); String proteinSeq = params.getProteinIdToSequence().get(proteinId); long featureLength = proteinSeq.length() * 3; features.add(new Feature().withId(proteinId) .withProteinTranslation(proteinSeq) .withType("CDS").withLocation(Arrays.asList( new Tuple4<String, Long, String, Long>().withE1(contigId) .withE2(featureStart).withE3("+").withE4(featureLength)))); featureStart += featureLength; } char[] contigSeqChars = new char[(int)featureStart + 5]; Arrays.fill(contigSeqChars, 'a'); Genome genome = new Genome().withScientificName(params.getGenomeName()) .withFeatures(features).withTaxonomy("Bacteria; Proteobacteria; Gammaproteobacteria; " + "Alteromonadales; Shewanellaceae; Shewanella."); GenometoGbk.writeGenbankFile(genome, contigId, contigId, new String(contigSeqChars), gbkFile); GenomeAnnotationFileUtilClient gafu = new GenomeAnnotationFileUtilClient( new URL(System.getenv("SDK_CALLBACK_URL")), authPart); gafu.setIsInsecureHttpConnectionAllowed(true); GenomeAnnotationDetails ret = gafu.genbankToGenomeAnnotation( new GenbankToGenomeAnnotationParams().withFilePath( gbkFile.getCanonicalPath()).withGenomeName(params.getOutputObjectName()) .withWorkspaceName(params.getOutputWorkspaceName())); returnVal = ret.getGenomeAnnotationRef(); } finally { FileUtils.deleteQuietly(tempDir); } //END prepare_test_genome_annotation_from_proteins return returnVal; } @JsonServerMethod(rpc = "TmpGnmAnnTest.status") public Map<String, Object> status() { Map<String, Object> returnVal = null; //BEGIN_STATUS returnVal = new LinkedHashMap<String, Object>(); returnVal.put("state", "OK"); returnVal.put("message", ""); returnVal.put("version", version); returnVal.put("git_url", gitUrl); returnVal.put("git_commit_hash", gitCommitHash); //END_STATUS return returnVal; } public static void main(String[] args) throws Exception { if (args.length == 1) { new TmpGnmAnnTestServer().startupServer(Integer.parseInt(args[0])); } else if (args.length == 3) { JsonServerSyslog.setStaticUseSyslog(false); JsonServerSyslog.setStaticMlogFile(args[1] + ".log"); new TmpGnmAnnTestServer().processRpcCall(new File(args[0]), new File(args[1]), args[2]); } else { System.out.println("Usage: <program> <server_port>"); System.out.println(" or: <program> <context_json_file> <output_json_file> <token>"); return; } } }
43.537879
177
0.665913
529634d016699a846b7a23ea364f9b0a2faf89ae
1,290
package com.packt.microprofile.book.ch6.metrics; import org.eclipse.microprofile.metrics.Meter; import org.eclipse.microprofile.metrics.MetricID; import org.eclipse.microprofile.metrics.MetricRegistry; import org.eclipse.microprofile.metrics.Tag; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; @ApplicationScoped @Path("/meterResource") public class MeterResource { @Inject MetricRegistry metricRegistry; private final String METER_METRIC_NAME = "meterMetric"; private final Tag METER_TAG = new Tag("metricType", "meter"); @GET @Path("/meter") public String getMeter() throws Exception { Meter meter = metricRegistry.meter(METER_METRIC_NAME, METER_TAG); meter.mark(); return "Meter created/retrieved and marked by 1"; } @GET @Path("/meter2") public String getMeter2(@QueryParam("value") @DefaultValue("1") int value) throws Exception { MetricID meterMetricID = new MetricID(METER_METRIC_NAME, METER_TAG); Meter meter = metricRegistry.meter(meterMetricID); meter.mark(value); return "Meter created/retrieved and marked by " + value; } }
32.25
97
0.731008
eab89b4a8527d9c006d10cfb5f118096050ab27a
2,801
package com.example.geopay; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import androidx.appcompat.app.AppCompatActivity; import org.json.JSONException; public class Area extends AppCompatActivity { public static final String AREA = ""; Spinner spiner; String selectedArea; impMerchantList merchantList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_area); //connect to API JSONMerchantTask task = new JSONMerchantTask(); task.execute(new String[]{""}); //get username from main activity and set up the spinner Intent intent = getIntent(); String message = intent.getStringExtra(UserHome.USERNAME); if(message != "") { spiner = findViewById(R.id.spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.geo_mock_areas, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spiner.setAdapter(adapter); spiner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { selectedArea = parent.getSelectedItem().toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { // show some msg } }); } } // Control events public void goToMerchants(View view) { Intent intent = new Intent(this, Merchants.class); intent.putExtra("merchantList", merchantList); startActivity(intent); } private class JSONMerchantTask extends AsyncTask<String, Void, impMerchantList> { //retrieve currency exchange rate @Override protected impMerchantList doInBackground(String... params) { Log.d("data", params[0]); merchantList = new impMerchantList(); String data = ((new HttpClient()).getMerchantData()); if (data != null) { try { merchantList = JsonApiParser.getMerchants(data); } catch (JSONException e) { e.printStackTrace(); } return merchantList; } else { return null; } } } }
31.47191
101
0.611567
08b6e19172727b6fdb0a80839d6c6434dc5db5cd
653
package org.jeroen.ddd.specification; public class AndSpecification<T> extends ComposableSpecification<T> { private final Specification<T> lhs; private final Specification<T> rhs; public AndSpecification(Specification<T> lhs, Specification<T> rhs) { super(); this.lhs = lhs; this.rhs = rhs; } /** * {@inheritDoc} */ @Override public boolean isSatisfiedBy(T candidate) { return lhs.isSatisfiedBy(candidate) && rhs.isSatisfiedBy(candidate); } public Specification<T> getLhs() { return lhs; } public Specification<T> getRhs() { return rhs; } }
21.766667
76
0.627871
6abd25264a3c5ed822f697879877d5c09aab4cd1
3,335
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.app.catalog; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.text.Html; import android.view.View; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import org.wso2.app.catalog.beans.Application; public class ReadMoreInfoActivity extends Activity { private TextView txtAppName; private TextView txtDescription; private TextView txtNewFeatures; private TextView txtVersion; private TextView txtUpdatedOn; private LinearLayout layoutWhatsNew; private Context context; private Application application; private ImageButton btnBack; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_read_more_info); Bundle extras = getIntent().getExtras(); context = ReadMoreInfoActivity.this.getApplicationContext(); if (extras != null) { if (getIntent().getSerializableExtra(context.getResources(). getString(R.string.intent_extra_application)) != null) { application = (Application) getIntent().getSerializableExtra(context.getResources(). getString(R.string.intent_extra_application)); } } txtAppName = (TextView)findViewById(R.id.txtAppName); txtDescription = (TextView)findViewById(R.id.txtDescription); txtNewFeatures = (TextView)findViewById(R.id.txtNewFeatures); txtVersion = (TextView)findViewById(R.id.txtVersion); txtUpdatedOn = (TextView)findViewById(R.id.txtUpdatedOn); layoutWhatsNew = (LinearLayout)findViewById(R.id.layoutWhatsNew); btnBack = (ImageButton)findViewById(R.id.btnBack); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); if (application != null) { txtAppName.setText(application.getName()); txtDescription.setText(Html.fromHtml(application.getDescription())); txtVersion.setText(application.getVersion()); txtUpdatedOn.setText(application.getCreatedtime()); if (application.getRecentChanges() != null) { txtNewFeatures.setText(Html.fromHtml(application.getRecentChanges())); } else { layoutWhatsNew.setVisibility(View.GONE); } } } @Override public void onBackPressed() { super.onBackPressed(); finish(); } }
36.25
100
0.67976
fad4793182650ae4ee2b58263c1f0af93e101bec
511
package net.yozo.services.front.template.dto; /** * 推荐模板查询DTO * Created by t on 2018/1/5. */ public class RelatedTemplateQuery { private Integer tempalteId; //模板ID private int start; //limit start public Integer getTempalteId() { return tempalteId; } public void setTempalteId(Integer tempalteId) { this.tempalteId = tempalteId; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } }
18.25
51
0.632094
54b68951cbd2c91480d841d25421446ae90c0636
3,097
package model.db; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashSet; import java.util.Set; import model.exceptions.InvalidEmailException; import model.exceptions.InvalidUserNameException; import model.inTheLab.DentalLaboratory; import model.inTheLab.LaboratoryManager; import model.mainObjects.Dentist; import model.tools.SendMail; public class DentistDAO { private static DentistDAO instance; private DentistDAO(){} public synchronized static DentistDAO getInstance(){ if(instance == null){ instance = new DentistDAO(); } return instance; } public Set<Dentist> getAllDentists() throws InvalidEmailException, InvalidUserNameException{ Set<Dentist> users = new HashSet<Dentist>(); try { Statement st = DBManager.getInstance().getConnection().createStatement(); System.out.println("statement created"); ResultSet resultSet = st.executeQuery("SELECT password, email, address, first_name, last_name, egn, phone, user_id, lab_id FROM users WHERE fk_user_type_id LIKE (2);"); System.out.println("result set created"); while(resultSet.next()){ DentalLaboratory dl = LaboratoryManager.getInstatnce().getLab(resultSet.getInt("lab_id")); Dentist d = new Dentist(resultSet.getString("email"),resultSet.getString("password"),resultSet.getInt("user_id"),dl); if(resultSet.getString("address") != null){ d.setAddress(resultSet.getString("address")); } d.setFirstName(resultSet.getString("first_name")); d.setLastName(resultSet.getString("last_name")); d.setEgn(resultSet.getString("egn")); if(resultSet.getString("phone") != null){ d.setPhone(resultSet.getString("phone")); } users.add(d); } } catch (SQLException e) { System.out.println("Oops, cannot make statement."); return users; } System.out.println("Dentists loaded successfully"); DBManager.getInstance().closeConnection(); return users; } public void saveDentist(Dentist dentist){ try { PreparedStatement st = DBManager.getInstance().getConnection().prepareStatement("INSERT INTO users (password, email, fk_user_type_id) VALUES (?, ?, ?);"); st.setString(1, dentist.getPassword()); st.setString(2, dentist.getEmail()); st.setInt(3, 2); st.executeUpdate(); System.out.println("inserted dentist in db"); System.out.println(dentist.getEmail()); ResultSet rs = st.getGeneratedKeys(); if(rs.next()) { int last_inserted_id = rs.getInt(1); dentist.setUserId(last_inserted_id); } String sub = "New account!!!"; String msg = "<h1>You have an dentist account</h1><a href=\"http://dent-info.net\"><h1>www.dent-info.net</h1></a><h1>password: " + dentist.getPassword() + "</h1>"; SendMail.sendMail(dentist.getEmail(), sub, msg); DBManager.getInstance().closeConnection(); System.out.println("Dentist added successfully"); } catch (SQLException e) { System.out.println("Oops .. did not save the dentist"); e.printStackTrace(); } } }
34.797753
171
0.707136
e8382b197a51bdbd056392c88c27618ae61cd9a7
1,823
package dk.kb.yggdrasil.utils; import static org.junit.Assert.*; import java.io.File; import java.util.LinkedHashMap; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.yaml.snakeyaml.scanner.ScannerException; import dk.kb.yggdrasil.config.RunningMode; import dk.kb.yggdrasil.exceptions.YggdrasilException; import dk.kb.yggdrasil.utils.YamlTools; /** * Tests for the methods in the YamlTools class. * */ @RunWith(JUnit4.class) public class YamlToolsTest { public static String YAML_TEST_FILE = "src/test/resources/config/rabbitmq.yml"; public static String NOT_YAML_TEST_FILE = "src/test/resources/config/rabbitmq.yaml"; public static String NOT_YAML_TEST_FILE2 = "src/test/resources/config/file_with_no_yaml_content.xml"; @Test public void testReadYamlFailed() throws Exception { File f = new File(NOT_YAML_TEST_FILE); try { YamlTools.loadYamlSettings(f); fail("Should throw YggdrasilException on non existing file"); } catch (YggdrasilException e) { // expected } } @Test public void testReadNonYamlFile() throws Exception { File f = new File(NOT_YAML_TEST_FILE2); try { YamlTools.loadYamlSettings(f); fail("Should throw YAML ScannerException on reading non YAML file"); } catch (ScannerException e) { // expected } } @SuppressWarnings("rawtypes") @Test public void testReadYamlFile() throws Exception { File f = new File(YAML_TEST_FILE); LinkedHashMap m = YamlTools.loadYamlSettings(f); Assert.assertNotNull(m); String mode = RunningMode.getMode().toString(); Assert.assertTrue(m.containsKey(mode)); } }
28.936508
105
0.68678
97100760ccce1f280895e95118c1b416550679b0
12,115
package com.shynieke.geore.config; import com.shynieke.geore.GeOre; import net.minecraftforge.common.ForgeConfigSpec; import net.minecraftforge.common.ForgeConfigSpec.BooleanValue; import net.minecraftforge.common.ForgeConfigSpec.IntValue; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.event.config.ModConfigEvent; import org.apache.commons.lang3.tuple.Pair; public class GeOreConfig { public static class Common { public final BooleanValue generateCoalGeore; public final BooleanValue generateCopperGeore; public final BooleanValue generateDiamondGeore; public final BooleanValue generateEmeraldGeore; public final BooleanValue generateGoldGeore; public final BooleanValue generateIronGeore; public final BooleanValue generateLapisGeore; public final BooleanValue generateQuartzGeore; public final BooleanValue generateQuartzInNetherGeore; public final BooleanValue generateRedstoneGeore; //Mod support public final BooleanValue generateRubyGeore; public final BooleanValue generateSapphireGeore; public final BooleanValue generateTopazGeore; public final IntValue coalGeoreRarity; public final IntValue copperGeoreRarity; public final IntValue diamondGeoreRarity; public final IntValue emeraldGeoreRarity; public final IntValue goldGeoreRarity; public final IntValue ironGeoreRarity; public final IntValue lapisGeoreRarity; public final IntValue quartzGeoreRarity; public final IntValue redstoneGeoreRarity; //Mod support public final IntValue rubyGeoreRarity; public final IntValue sapphireGeoreRarity; public final IntValue topazGeoreRarity; public final IntValue coalGeoreMinY; public final IntValue coalGeoreMaxY; public final IntValue copperGeoreMinY; public final IntValue copperGeoreMaxY; public final IntValue diamondGeoreMinY; public final IntValue diamondGeoreMaxY; public final IntValue emeraldGeoreMinY; public final IntValue emeraldGeoreMaxY; public final IntValue goldGeoreMinY; public final IntValue goldGeoreMaxY; public final IntValue ironGeoreMinY; public final IntValue ironGeoreMaxY; public final IntValue lapisGeoreMinY; public final IntValue lapisGeoreMaxY; public final IntValue quartzGeoreMinY; public final IntValue quartzGeoreMaxY; public final IntValue redstoneGeoreMinY; public final IntValue redstoneGeoreMaxY; //Mod support public final IntValue rubyGeoreMinY; public final IntValue rubyGeoreMaxY; public final IntValue sapphireGeoreMinY; public final IntValue sapphireGeoreMaxY; public final IntValue topazGeoreMinY; public final IntValue topazGeoreMaxY; Common(ForgeConfigSpec.Builder builder) { builder.comment("Generation settings") .push("Generation"); generateCoalGeore = builder .comment("Generate Coal GeOre [Default: true]") .define("generateCoalGeore", true); coalGeoreMinY = builder .comment("The Min Y level that Coal GeOre will generate at (above minimum world height) [Default: 6]") .defineInRange("coalGeoreMinY", 6, 0, Integer.MAX_VALUE); coalGeoreMaxY = builder .comment("The max Y level that Coal GeOre will generate at [Default: 30]") .defineInRange("coalGeoreMaxY", 30, 0, Integer.MAX_VALUE); generateCopperGeore = builder .comment("Generate Copper GeOre [Default: true]") .define("generateCopperGeore", true); copperGeoreMinY = builder .comment("The Min Y level that Copper GeOre will generate at (above minimum world height) [Default: 6]") .defineInRange("copperGeoreMinY", 6, 0, Integer.MAX_VALUE); copperGeoreMaxY = builder .comment("The max Y level that Copper GeOre will generate at [Default: 30]") .defineInRange("copperGeoreMaxY", 30, 0, Integer.MAX_VALUE); generateDiamondGeore = builder .comment("Generate Diamond GeOre [Default: true]") .define("generateDiamondGeore", true); diamondGeoreMinY = builder .comment("The Min Y level that Diamond GeOre will generate at (above minimum world height) [Default: 6]") .defineInRange("diamondGeoreMinY", 6, 0, Integer.MAX_VALUE); diamondGeoreMaxY = builder .comment("The max Y level that Diamond GeOre will generate at [Default: 30]") .defineInRange("diamondGeoreMaxY", 30, 0, Integer.MAX_VALUE); generateEmeraldGeore = builder .comment("Generate Emerald GeOre [Default: true]") .define("generateEmeraldGeore", true); emeraldGeoreMinY = builder .comment("The Min Y level that Emerald GeOre will generate at (above minimum world height) [Default: 6]") .defineInRange("emeraldGeoreMinY", 6, 0, Integer.MAX_VALUE); emeraldGeoreMaxY = builder .comment("The max Y level that Emerald GeOre will generate at [Default: 30]") .defineInRange("emeraldGeoreMaxY", 30, 0, Integer.MAX_VALUE); generateGoldGeore = builder .comment("Generate Gold GeOre [Default: true]") .define("generateGoldGeore", true); goldGeoreMinY = builder .comment("The Min Y level that Gold GeOre will generate at (above minimum world height) [Default: 6]") .defineInRange("goldGeoreMinY", 6, 0, Integer.MAX_VALUE); goldGeoreMaxY = builder .comment("The max Y level that Gold GeOre will generate at [Default: 30]") .defineInRange("goldGeoreMaxY", 30, 0, Integer.MAX_VALUE); generateIronGeore = builder .comment("Generate Iron GeOre [Default: true]") .define("generateIronGeore", true); ironGeoreMinY = builder .comment("The Min Y level that Iron GeOre will generate at (above minimum world height) [Default: 6]") .defineInRange("ironGeoreMinY", 6, 0, Integer.MAX_VALUE); ironGeoreMaxY = builder .comment("The max Y level that Iron GeOre will generate at [Default: 30]") .defineInRange("ironGeoreMaxY", 30, 0, Integer.MAX_VALUE); generateLapisGeore = builder .comment("Generate Lapis GeOre [Default: true]") .define("generateLapisGeore", true); lapisGeoreMinY = builder .comment("The Min Y level that Lapis GeOre will generate at (above minimum world height) [Default: 6]") .defineInRange("lapisGeoreMinY", 6, 0, Integer.MAX_VALUE); lapisGeoreMaxY = builder .comment("The max Y level that Lapis GeOre will generate at [Default: 30]") .defineInRange("lapisGeoreMaxY", 30, 0, Integer.MAX_VALUE); generateQuartzGeore = builder .comment("Generate Quartz GeOre [Default: true]") .define("generateQuartzGeore", true); quartzGeoreMinY = builder .comment("The Min Y level that Quartz GeOre will generate at (above minimum world height) [Default: 6]") .defineInRange("quartzGeoreMinY", 6, 0, Integer.MAX_VALUE); quartzGeoreMaxY = builder .comment("The max Y level that Quartz GeOre will generate at [Default: 30]") .defineInRange("quartzGeoreMaxY", 30, 0, Integer.MAX_VALUE); generateQuartzInNetherGeore = builder .comment("Generate Quartz GeOre in the Nether [Default: true]") .define("generateQuartzInNetherGeore", true); generateRedstoneGeore = builder .comment("Generate Redstone GeOre [Default: true]") .define("generateRedstoneGeore", true); redstoneGeoreMinY = builder .comment("The Min Y level that Redstone GeOre will generate at (above minimum world height) [Default: 6]") .defineInRange("redstoneGeoreMinY", 6, 0, Integer.MAX_VALUE); redstoneGeoreMaxY = builder .comment("The max Y level that Redstone GeOre will generate at [Default: 30]") .defineInRange("redstoneGeoreMaxY", 30, 0, Integer.MAX_VALUE); builder.pop(); builder.comment("Modded Generation settings") .push("ModdedGeneration"); generateRubyGeore = builder .comment("Generate Ruby GeOre [Default: false]") .define("generateRubyGeore", false); rubyGeoreMinY = builder .comment("The Min Y level that Ruby GeOre will generate at (above minimum world height) [Default: 6]") .defineInRange("rubyGeoreMinY", 6, 0, Integer.MAX_VALUE); rubyGeoreMaxY = builder .comment("The max Y level that Ruby GeOre will generate at [Default: 30]") .defineInRange("rubyGeoreMaxY", 30, 0, Integer.MAX_VALUE); generateSapphireGeore = builder .comment("Generate Sapphire GeOre [Default: false]") .define("generateSapphireGeore", false); sapphireGeoreMinY = builder .comment("The Min Y level that Sapphire GeOre will generate at (above minimum world height) [Default: 6]") .defineInRange("sapphireGeoreMinY", 6, 0, Integer.MAX_VALUE); sapphireGeoreMaxY = builder .comment("The max Y level that Sapphire GeOre will generate at [Default: 30]") .defineInRange("sapphireGeoreMaxY", 30, 0, Integer.MAX_VALUE); generateTopazGeore = builder .comment("Generate Topaz GeOre [Default: false]") .define("generateTopazGeore", false); topazGeoreMinY = builder .comment("The Min Y level that Topaz GeOre will generate at (above minimum world height) [Default: 6]") .defineInRange("topazGeoreMinY", 6, 0, Integer.MAX_VALUE); topazGeoreMaxY = builder .comment("The max Y level that Topaz GeOre will generate at [Default: 30]") .defineInRange("topazGeoreMaxY", 30, 0, Integer.MAX_VALUE); builder.pop(); builder.comment("Rarity settings") .push("Rarity"); coalGeoreRarity = builder .comment("Coal GeOre Rarity [Default: 60] (The higher the value the rarer)") .defineInRange("coalGeoreRarity", 60, 0, Integer.MAX_VALUE); copperGeoreRarity = builder .comment("Copper GeOre Rarity [Default: 90] (The higher the value the rarer)") .defineInRange("copperGeoreRarity", 90, 0, Integer.MAX_VALUE); diamondGeoreRarity = builder .comment("Diamond GeOre Rarity [Default: 270] (The higher the value the rarer)") .defineInRange("diamondGeoreRarity", 330, 0, Integer.MAX_VALUE); emeraldGeoreRarity = builder .comment("Emerald GeOre Rarity [Default: 300] (The higher the value the rarer)") .defineInRange("emeraldGeoreRarity", 420, 0, Integer.MAX_VALUE); goldGeoreRarity = builder .comment("Gold GeOre Rarity [Default: 180] (The higher the value the rarer)") .defineInRange("goldGeoreRarity", 180, 0, Integer.MAX_VALUE); ironGeoreRarity = builder .comment("Iron GeOre Rarity [Default: 120] (The higher the value the rarer)") .defineInRange("ironGeoreRarity", 120, 0, Integer.MAX_VALUE); lapisGeoreRarity = builder .comment("Lapis GeOre Rarity [Default: 210] (The higher the value the rarer)") .defineInRange("lapisGeoreRarity", 210, 0, Integer.MAX_VALUE); quartzGeoreRarity = builder .comment("Quartz GeOre Rarity [Default: 150] (The higher the value the rarer)") .defineInRange("quartzGeoreRarity", 150, 0, Integer.MAX_VALUE); redstoneGeoreRarity = builder .comment("Redstone GeOre Rarity [Default: 240] (The higher the value the rarer)") .defineInRange("redstoneGeoreRarity", 240, 0, Integer.MAX_VALUE); rubyGeoreRarity = builder .comment("Ruby GeOre Rarity [Default: 240] (The higher the value the rarer)") .defineInRange("rubyGeoreRarity", 240, 0, Integer.MAX_VALUE); sapphireGeoreRarity = builder .comment("Sapphire GeOre Rarity [Default: 240] (The higher the value the rarer)") .defineInRange("sapphireGeoreRarity", 240, 0, Integer.MAX_VALUE); topazGeoreRarity = builder .comment("Topaz GeOre Rarity [Default: 240] (The higher the value the rarer)") .defineInRange("topazGeoreRarity", 240, 0, Integer.MAX_VALUE); builder.pop(); } } public static final ForgeConfigSpec commonSpec; public static final Common COMMON; static { final Pair<Common, ForgeConfigSpec> specPair = new ForgeConfigSpec.Builder().configure(Common::new); commonSpec = specPair.getRight(); COMMON = specPair.getLeft(); } @SubscribeEvent public static void onLoad(final ModConfigEvent.Loading configEvent) { GeOre.LOGGER.debug("Loaded GeOre's config file {}", configEvent.getConfig().getFileName()); } @SubscribeEvent public static void onFileChange(final ModConfigEvent.Reloading configEvent) { GeOre.LOGGER.debug("GeOre's config just got changed on the file system!"); } }
40.791246
111
0.738341
efe3e0a2031ff6e456454b4a7425e0f3a50f74d6
11,634
package net.csibio.propro.service.impl; import lombok.extern.slf4j.Slf4j; import net.csibio.propro.algorithm.decoy.generator.NicoGenerator; import net.csibio.propro.algorithm.decoy.generator.ReplaceGenerator; import net.csibio.propro.algorithm.decoy.generator.ShuffleGenerator; import net.csibio.propro.algorithm.parser.*; import net.csibio.propro.algorithm.stat.LibraryStat; import net.csibio.propro.algorithm.stat.StatConst; import net.csibio.propro.constants.enums.ResultCode; import net.csibio.propro.constants.enums.TaskStatus; import net.csibio.propro.dao.BaseDAO; import net.csibio.propro.dao.LibraryDAO; import net.csibio.propro.dao.PeptideDAO; import net.csibio.propro.domain.Result; import net.csibio.propro.domain.bean.common.IdName; import net.csibio.propro.domain.bean.peptide.FragmentGroup; import net.csibio.propro.domain.db.LibraryDO; import net.csibio.propro.domain.db.PeptideDO; import net.csibio.propro.domain.db.TaskDO; import net.csibio.propro.domain.query.LibraryQuery; import net.csibio.propro.domain.query.PeptideQuery; import net.csibio.propro.exceptions.XException; import net.csibio.propro.service.LibraryService; import net.csibio.propro.service.PeptideService; import net.csibio.propro.service.TaskService; import net.csibio.propro.utils.FileUtil; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.InputStream; import java.util.*; @Slf4j @Service("libraryService") public class LibraryServiceImpl implements LibraryService { int errorListNumberLimit = 10; @Autowired LibraryDAO libraryDAO; @Autowired LibraryStat libraryStat; @Autowired PeptideService peptideService; @Autowired PeptideDAO peptideDAO; @Autowired LibraryTsvParser tsvParser; @Autowired OpenCsvParser openCsvParser; @Autowired TraMLParser traMLParser; @Autowired FastTraMLParser fastTraMLParser; @Autowired MsmsParser msmsParser; @Autowired TaskService taskService; @Autowired FastaParser fastaParser; @Autowired NicoGenerator nicoGenerator; @Autowired ShuffleGenerator shuffleGenerator; @Autowired ReplaceGenerator replaceGenerator; @Override public BaseDAO<LibraryDO, LibraryQuery> getBaseDAO() { return libraryDAO; } @Override public void beforeInsert(LibraryDO libraryDO) throws XException { if (libraryDO.getName() == null) { throw new XException(ResultCode.LIBRARY_NAME_CANNOT_BE_EMPTY); } libraryDO.setCreateDate(new Date()); libraryDO.setLastModifiedDate(new Date()); } @Override public void beforeUpdate(LibraryDO libraryDO) throws XException { if (libraryDO.getId() == null) { throw new XException(ResultCode.ID_CANNOT_BE_NULL_OR_ZERO); } if (libraryDO.getName() == null) { throw new XException(ResultCode.LIBRARY_NAME_CANNOT_BE_EMPTY); } libraryDO.setLastModifiedDate(new Date()); } @Override public void beforeRemove(String id) throws XException { try { peptideService.removeAllByLibraryId(id); } catch (Exception e) { throw e; } } @Override public Result<LibraryDO> clone(LibraryDO oriLib, String newLibName, Boolean includeDecoy) { //TODO 李然 根据一个旧库,一个新库名和是否克隆伪肽段 克隆一个新库,包含库内所有的肽段信息 List<PeptideDO> allByLibraryId = peptideService.getAllByLibraryId(oriLib.getId()); LibraryDO libraryDO = new LibraryDO(); libraryDO.setDescription(oriLib.getDescription()); libraryDO.setGenerator(oriLib.getGenerator()); libraryDO.setName(newLibName); libraryDO.setFilePath(oriLib.getFilePath()); libraryDO.setOrganism(oriLib.getOrganism()); libraryDO.setType(oriLib.getType()); libraryDO.setStatistic(oriLib.getStatistic()); insert(libraryDO); List<PeptideDO> peptideDOList = new ArrayList<>(); if (includeDecoy) { for (PeptideDO peptideDO : allByLibraryId) { PeptideDO newPeptide = new PeptideDO(); BeanUtils.copyProperties(peptideDO, newPeptide); peptideDOList.add(newPeptide); } } else { for (PeptideDO peptideDO : allByLibraryId) { PeptideDO newPeptide = new PeptideDO(); BeanUtils.copyProperties(peptideDO, newPeptide); newPeptide.clearDecoy(); peptideDOList.add(newPeptide); } } peptideService.insert(peptideDOList); log.info("库克隆完毕"); return Result.OK(); } @Override public void uploadFile(LibraryDO library, InputStream libFileStream, TaskDO taskDO) { //先Parse文件,再作数据库的操作 Result result = parseAndInsert(library, libFileStream, taskDO); if (result.getErrorList() != null) { if (result.getErrorList().size() > errorListNumberLimit) { taskDO.addLog("解析错误,错误的条数过多,这边只显示" + errorListNumberLimit + "条错误信息"); taskDO.addLog(result.getErrorList().subList(0, errorListNumberLimit)); } else { taskDO.addLog(result.getErrorList()); } } if (result.isFailed()) { taskDO.addLog(result.getErrorMessage()); taskDO.finish(TaskStatus.FAILED.getName()); } //如果全部存储成功,开始统计蛋白质数目,肽段数目和Transition数目 taskDO.addLog("开始统计蛋白质数目,肽段数目和Transition数目"); taskService.update(taskDO); statistic(library); taskDO.finish(TaskStatus.SUCCESS.getName(), "统计完毕"); taskService.update(taskDO); } @Override public Result parseAndInsert(LibraryDO library, InputStream libFileStream, TaskDO taskDO) { Result result = null; String filePath = library.getFilePath(); if (filePath.toLowerCase().endsWith("tsv")) { library.setFileFormat("tsv"); result = openCsvParser.parseAndInsert(libFileStream, library, taskDO); } else if (filePath.toLowerCase().endsWith("csv")) { library.setFileFormat("csv"); result = openCsvParser.parseAndInsert(libFileStream, library, taskDO); } else if (filePath.toLowerCase().endsWith("traml")) { library.setFileFormat("traml"); result = traMLParser.parseAndInsert(libFileStream, library, taskDO); } else if (filePath.toLowerCase().endsWith("txt")) { library.setFileFormat("txt"); result = msmsParser.parseAndInsert(libFileStream, library, taskDO); } else { return Result.Error(ResultCode.INPUT_FILE_TYPE_MUST_BE_TSV_OR_TRAML); } FileUtil.close(libFileStream); library.setGenerator(ShuffleGenerator.NAME); return result; } @Override public void statistic(LibraryDO library) { Map<String, Object> statistic = new HashMap<>(); List<FragmentGroup> peptideList = peptideService.getAll(new PeptideQuery(library.getId()), FragmentGroup.class); statistic.put(StatConst.Protein_Count, libraryStat.proteinCount(library)); statistic.put(StatConst.Peptide_Count, libraryStat.peptideCount(library)); statistic.put(StatConst.Fragment_Count, libraryStat.fragmentCount(peptideList)); statistic.put(StatConst.Peptide_Dist_On_Mz_5, libraryStat.mzDistList(peptideList, 20)); statistic.put(StatConst.Peptide_Dist_On_RT_5, libraryStat.rtDistList(peptideList, 20)); library.setStatistic(statistic); libraryDAO.update(library); log.info("统计完成"); } @Override public Result clearDecoys(LibraryDO library) { List<PeptideDO> allByLibraryId = peptideService.getAllByLibraryId(library.getId()); for (PeptideDO peptideDO : allByLibraryId) { peptideDO.clearDecoy(); peptideService.update(peptideDO); } log.info("伪肽段清除完毕"); return Result.OK("成功清除"); } @Override public Result generateDecoys(LibraryDO library, String generator) { List<PeptideDO> peptideList = peptideService.getAllByLibraryId(library.getId()); switch (generator) { case NicoGenerator.NAME: nicoGenerator.generate(peptideList); break; case ShuffleGenerator.NAME: shuffleGenerator.generate(peptideList); break; case ReplaceGenerator.NAME: replaceGenerator.generate(peptideList); break; default: generator = ShuffleGenerator.NAME; shuffleGenerator.generate(peptideList); } peptideService.updateDecoyInfos(peptideList); library.setGenerator(generator); update(library); return Result.OK(); } // @Cacheable(cacheNames = "libraryGetId", key = "#id") @Override public LibraryDO getById(String id) { try { return getBaseDAO().getById(id); } catch (Exception e) { return null; } } // @CacheEvict(cacheNames = "libraryGetId", key = "#libraryDO.id") @Override public Result<LibraryDO> update(LibraryDO libraryDO) { try { beforeUpdate(libraryDO); getBaseDAO().update(libraryDO); return Result.OK(libraryDO); } catch (XException xe) { return Result.Error(xe.getResultCode()); } catch (Exception e) { return Result.Error(ResultCode.UPDATE_ERROR); } } // @CacheEvict(allEntries = true) @Override public Result<List<LibraryDO>> update(List<LibraryDO> libraryDOS) { try { for (LibraryDO t : libraryDOS) { beforeUpdate(t); } getBaseDAO().update(libraryDOS); return Result.OK(libraryDOS); } catch (XException xe) { return Result.Error(xe.getResultCode()); } catch (Exception e) { return Result.Error(ResultCode.UPDATE_ERROR); } } // @Cacheable(cacheNames = "LibraryGetAll", key = "#libraryQuery.getName()") @Override public List<LibraryDO> getAll(LibraryQuery libraryQuery) { return getBaseDAO().getAll(libraryQuery); } // @CacheEvict(cacheNames = "libraryGetId", key = "#id") @Override public Result removeById(String id) { if (id == null || id.isEmpty()) { return Result.Error(ResultCode.ID_CANNOT_BE_NULL_OR_ZERO); } try { beforeRemove(id); getBaseDAO().removeById(id); return Result.OK(); } catch (Exception e) { return Result.Error(ResultCode.DELETE_ERROR); } } private void simulateSlowService() { try { long time = 3000L; Thread.sleep(time); } catch (InterruptedException e) { throw new IllegalStateException(e); } } @Override public Result remove(LibraryQuery query) { List<IdName> idNameList = getAll(query, IdName.class); List<String> errorList = new ArrayList<>(); idNameList.forEach(idName -> { Result res = removeById(idName.id()); if (res.isFailed()) { errorList.add("Remove Library Failed:" + res.getErrorMessage()); } }); if (errorList.size() > 0) { return Result.Error(ResultCode.DELETE_ERROR, errorList); } return Result.OK(); } }
35.361702
120
0.647069
11a3b05a4c0e02a91197d9af5ed58375b4f3602e
15,546
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =======================================================================*/ package org.tensorflow.ndarray.impl.sparse; import org.tensorflow.ndarray.FloatNdArray; import org.tensorflow.ndarray.LongNdArray; import org.tensorflow.ndarray.NdArray; import org.tensorflow.ndarray.NdArrays; import org.tensorflow.ndarray.Shape; import org.tensorflow.ndarray.StdArrays; import org.tensorflow.ndarray.buffer.DataBuffer; import org.tensorflow.ndarray.buffer.DataBuffers; import org.tensorflow.ndarray.buffer.FloatDataBuffer; import org.tensorflow.ndarray.impl.dimension.DimensionalSpace; import org.tensorflow.ndarray.impl.sparse.slice.FloatSparseSlice; import org.tensorflow.ndarray.index.Index; import java.nio.ReadOnlyBufferException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * sparse array for the float data type * * <p>A sparse array as two separate dense arrays: indices, values, and a shape that represents the * dense shape. * * <p><em>NOTE:</em> all Sparse Arrays are readonly for the {@link #set(NdArray, long...)} and * {@link #setObject(Float, long...)} methods * * <pre>{@code * FloatSparseNdArray st = new FloatSparseNdArray( * StdArrays.of(new long[][] {{0, 0}, {1, 2}}), * NdArrays.vectorOf(1f, 3.14f}), * Shape.of(3, 4)); * * }</pre> * * <p>represents the dense array: * * <pre>{@code * [[1, 0, 0, 0] * [0, 0, 3.14, 0] * [0, 0, 0, 0]] * * }</pre> */ public class FloatSparseNdArray extends AbstractSparseNdArray<Float, FloatNdArray> implements FloatNdArray { /** * Creates a FloatSparseNdArray with a default value of zero. * * @param indices A 2-D LongNdArray of shape {@code [N, ndims]}, that specifies the indices of the * elements in the sparse array that contain non-default values (elements are zero-indexed). * For example, {@code indices=[[1,3], [2,4]]} specifies that the elements with indexes of * {@code [1,3]} and {@code [2,4]} have non-default values. * @param values A 1-D FloatNdArray of shape {@code [N]}, which supplies the values for each * element in indices. For example, given {@code indices=[[1,3], [2,4]]}, the parameter {@code * values=[18, 3.6]} specifies that element {@code [1,3]} of the sparse NdArray has a value of * {@code 18}, and element {@code [2,4]} of the NdArray has a value of {@code 3.6}. * @param dimensions the dimensional space for the dense object represented by this sparse array, */ FloatSparseNdArray(LongNdArray indices, FloatNdArray values, DimensionalSpace dimensions) { this(indices, values, 0f, dimensions); } /** * Creates a FloatSparseNdArray * * @param indices A 2-D LongNdArray of shape {@code [N, ndims]}, that specifies the indices of the * elements in the sparse array that contain non-default values (elements are zero-indexed). * For example, {@code indices=[[1,3], [2,4]]} specifies that the elements with indexes of * {@code [1,3]} and {@code [2,4]} have non-default values. * @param values A 1-D FloatNdArray of shape {@code [N]}, which supplies the values for each * element in indices. For example, given {@code indices=[[1,3], [2,4]]}, the parameter {@code * values=[18, 3.6]} specifies that element {@code [1,3]} of the sparse NdArray has a value of * {@code 18}, and element {@code [2,4]} of the NdArray has a value of {@code 3.6}. * @param defaultValue Scalar value to set for indices not specified in {@link #getIndices()} * @param dimensions the dimensional space for the dense object represented by this sparse array, */ FloatSparseNdArray( LongNdArray indices, FloatNdArray values, float defaultValue, DimensionalSpace dimensions) { super(indices, values, defaultValue, dimensions); } /** * Creates a FloatSparseNdArray * * @param dataBuffer a dense dataBuffer used to create the spars array * @param dimensions the dimensional space for the dense object represented by this sparse array, */ FloatSparseNdArray(FloatDataBuffer dataBuffer, DimensionalSpace dimensions) { this(dataBuffer, 0f, dimensions); } /** * Creates a FloatSparseNdArray * * @param dataBuffer a dense dataBuffer used to create the spars array * @param defaultValue Scalar value to set for indices not specified in {@link #getIndices()} * @param dimensions the dimensional space for the dense object represented by this sparse array, */ FloatSparseNdArray(FloatDataBuffer dataBuffer, float defaultValue, DimensionalSpace dimensions) { super(defaultValue, dimensions); // use write to set up the indices and values write(dataBuffer); } /** * Creates a zero-filled FloatSparseNdArray * * @param dimensions the dimensional space for the dense object represented by this sparse array, */ FloatSparseNdArray(DimensionalSpace dimensions) { this(0f, dimensions); } /** * Creates a zero-filled FloatSparseNdArray * * @param defaultValue Scalar value to set for indices not specified in {@link #getIndices()} * @param dimensions the dimensional space for the dense object represented by this sparse array, */ FloatSparseNdArray(float defaultValue, DimensionalSpace dimensions) { super(defaultValue, dimensions); } /** * Creates a new FloatSparseNdArray * * @param indices A 2-D LongNdArray of shape {@code [N, ndims]}, that specifies the indices of the * elements in the sparse array that contain non-default values (elements are zero-indexed). * For example, {@code indices=[[1,3], [2,4]]} specifies that the elements with indexes of * {@code [1,3]} and {@code [2,4]} have non-default values. * @param values A 1-D NdArray of any type and shape {@code [N]}, which supplies the values for * each element in indices. For example, given {@code indices=[[1,3], [2,4]]}, the parameter * {@code values=[18, 3.6]} specifies that element {@code [1,3]} of the sparse NdArray has a * value of {@code 18}, and element {@code [2,4]} of the NdArray has a value of {@code 3.6}. * @param dimensions the dimensional space for the dense object represented by this sparse array. * @return the new Sparse Array */ public static FloatSparseNdArray create( LongNdArray indices, FloatNdArray values, DimensionalSpace dimensions) { return new FloatSparseNdArray(indices, values, dimensions); } /** * Creates a new FloatSparseNdArray * * @param indices A 2-D LongNdArray of shape {@code [N, ndims]}, that specifies the indices of the * elements in the sparse array that contain non-default values (elements are zero-indexed). * For example, {@code indices=[[1,3], [2,4]]} specifies that the elements with indexes of * {@code [1,3]} and {@code [2,4]} have non-default values. * @param values A 1-D NdArray of any type and shape {@code [N]}, which supplies the values for * each element in indices. For example, given {@code indices=[[1,3], [2,4]]}, the parameter * {@code values=[18, 3.6]} specifies that element {@code [1,3]} of the sparse NdArray has a * value of {@code 18}, and element {@code [2,4]} of the NdArray has a value of {@code 3.6}. * @param defaultValue Scalar value to set for indices not specified in {@link #getIndices()} * @param dimensions the dimensional space for the dense object represented by this sparse array. * @return the new Sparse Array */ public static FloatSparseNdArray create( LongNdArray indices, FloatNdArray values, float defaultValue, DimensionalSpace dimensions) { return new FloatSparseNdArray(indices, values, defaultValue, dimensions); } /** * Creates a new FloatSparseNdArray from a data buffer * * @param dataBuffer the databuffer containing the dense array * @param dimensions the dimensional space for the sparse array * @return the new Sparse Array */ public static FloatSparseNdArray create(FloatDataBuffer dataBuffer, DimensionalSpace dimensions) { return new FloatSparseNdArray(dataBuffer, dimensions); } /** * Creates a new FloatSparseNdArray from a data buffer * * @param dataBuffer the databuffer containing the dense array * @param defaultValue Scalar value to set for indices not specified in {@link #getIndices()} * @param dimensions the dimensional space for the sparse array * @return the new Sparse Array */ public static FloatSparseNdArray create( FloatDataBuffer dataBuffer, float defaultValue, DimensionalSpace dimensions) { return new FloatSparseNdArray(dataBuffer, defaultValue, dimensions); } /** * Creates a new empty FloatSparseNdArray from a data buffer * * @param dimensions the dimensions array * @return the new Sparse Array */ public static FloatSparseNdArray create(DimensionalSpace dimensions) { return new FloatSparseNdArray(dimensions); } /** * Creates a new empty FloatSparseNdArray from a data buffer * * @param defaultValue Scalar value to set for indices not specified in {@link #getIndices()} * @param dimensions the dimensions array * @return the new Sparse Array */ public static FloatSparseNdArray create(float defaultValue, DimensionalSpace dimensions) { return new FloatSparseNdArray(defaultValue, dimensions); } /** * Creates a new empty FloatSparseNdArray from a float data buffer * * @param buffer the data buffer * @param shape the shape of the sparse array. * @return the new Sparse Array */ public static FloatSparseNdArray create(FloatDataBuffer buffer, Shape shape) { return new FloatSparseNdArray(buffer, DimensionalSpace.create(shape)); } /** * Creates a new empty FloatSparseNdArray from a float data buffer * * @param buffer the data buffer * @param defaultValue Scalar value to set for indices not specified in {@link #getIndices()} * @param shape the shape of the sparse array. * @return the new Sparse Array */ public static FloatSparseNdArray create(FloatDataBuffer buffer, float defaultValue, Shape shape) { return new FloatSparseNdArray(buffer, defaultValue, DimensionalSpace.create(shape)); } /** * Creates a new FloatSparseNdArray from a FloatNdArray * * @param src the FloatNdArray * @return the new Sparse Array */ public static FloatSparseNdArray create(FloatNdArray src) { FloatDataBuffer buffer = DataBuffers.ofFloats(src.size()); src.read(buffer); return new FloatSparseNdArray(buffer, DimensionalSpace.create(src.shape())); } /** * Creates a new FloatSparseNdArray from a FloatNdArray * * @param src the FloatNdArray * @param defaultValue Scalar value to set for indices not specified in {@link #getIndices()} * @return the new Sparse Array */ public static FloatSparseNdArray create(FloatNdArray src, float defaultValue) { FloatDataBuffer buffer = DataBuffers.ofFloats(src.size()); src.read(buffer); return new FloatSparseNdArray(buffer, defaultValue, DimensionalSpace.create(src.shape())); } /** * Creates a FloatNdArray of the specified shape * * @param shape the shape of the dense array. * @return a FloatNdArray of the specified shape */ public FloatNdArray createValues(Shape shape) { return NdArrays.ofFloats(shape); } /** {@inheritDoc} */ @Override public FloatNdArray slice(long position, DimensionalSpace sliceDimensions) { return new FloatSparseSlice(this, position, sliceDimensions); } /** {@inheritDoc} */ @Override public float getFloat(long... coordinates) { return getObject(coordinates); } /** {@inheritDoc} */ @Override public FloatNdArray setFloat(float value, long... coordinates) { throw new ReadOnlyBufferException(); } /** {@inheritDoc} */ @Override public FloatNdArray read(DataBuffer<Float> dst) { return read((FloatDataBuffer) dst); } /** {@inheritDoc} */ @Override public FloatNdArray read(FloatDataBuffer dst) { // set the values in buf to the default, then overwrite with indices/values Float[] defaults = new Float[(int) shape().size()]; Arrays.fill(defaults, getDefaultValue()); dst.write(defaults); AtomicInteger i = new AtomicInteger(); getIndices() .elements(0) .forEachIndexed( (idx, l) -> { long[] coordinates = getIndicesCoordinates(l); float value = getValues().getFloat(i.getAndIncrement()); dst.setObject(value, dimensions.positionOf(coordinates)); }); return this; } /** {@inheritDoc} */ @Override public FloatNdArray write(FloatDataBuffer src) { List<long[]> indices = new ArrayList<>(); List<Float> values = new ArrayList<>(); for (long i = 0; i < src.size(); i++) { if (!src.getObject(i).equals(getDefaultValue())) { indices.add(toCoordinates(dimensions, i)); values.add(src.getObject(i)); } } long[][] indicesArray = new long[indices.size()][]; float[] valuesArray = new float[values.size()]; for (int i = 0; i < indices.size(); i++) { indicesArray[i] = indices.get(i); valuesArray[i] = values.get(i); } setIndices(StdArrays.ndCopyOf(indicesArray)); setValues(NdArrays.vectorOf(valuesArray)); return this; } /** {@inheritDoc} */ @Override public FloatNdArray write(DataBuffer<Float> src) { return write((FloatDataBuffer) src); } /** * Converts the sparse array to a dense array * * @return the dense array */ public FloatNdArray toDense() { FloatDataBuffer dataBuffer = DataBuffers.ofFloats(shape().size()); read(dataBuffer); return NdArrays.wrap(shape(), dataBuffer); } /** * Populates this sparse array from a dense array * * @param src the dense array * @return this sparse array */ public FloatNdArray fromDense(FloatNdArray src) { FloatDataBuffer buffer = DataBuffers.ofFloats(src.size()); src.read(buffer); write(buffer); return this; } /** {@inheritDoc} */ @Override public FloatNdArray slice(Index... indices) { return (FloatNdArray) super.slice(indices); } /** {@inheritDoc} */ @Override public FloatNdArray get(long... coordinates) { return (FloatNdArray) super.get(coordinates); } /** {@inheritDoc} */ @Override public FloatNdArray setObject(Float value, long... coordinates) { throw new ReadOnlyBufferException(); } /** {@inheritDoc} */ @Override public FloatNdArray set(NdArray<Float> src, long... coordinates) { throw new ReadOnlyBufferException(); } /** {@inheritDoc} */ @Override public FloatNdArray copyTo(NdArray<Float> dst) { return (FloatNdArray) super.copyTo(dst); } /** {@inheritDoc} */ @Override public FloatNdArray createDefaultArray() { return NdArrays.scalarOf(getDefaultValue()); } }
37.191388
100
0.692911
1e7721df5e5e321f10cd3d38676ea6c5efd72d55
3,186
/* * Copyright (C) 2012-2014 DuyHai DOAN * * 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 info.archinnov.achilles.test.integration.entity; import info.archinnov.achilles.annotations.EmbeddedId; import info.archinnov.achilles.annotations.Entity; import info.archinnov.achilles.annotations.Order; import info.archinnov.achilles.annotations.PartitionKey; import info.archinnov.achilles.internal.metadata.holder.PropertyType; import java.nio.ByteBuffer; import java.util.Objects; import static info.archinnov.achilles.test.integration.entity.ClusteredEntityForTranscoding.TABLE_NAME; @Entity(table = TABLE_NAME) public class ClusteredEntityForTranscoding { public static final String TABLE_NAME = "clustered_for_transcoding"; @EmbeddedId private EmbeddedKey id; public ClusteredEntityForTranscoding() { } public ClusteredEntityForTranscoding(Long id, PropertyType type, Integer year, ByteBuffer bytes) { this.id = new EmbeddedKey(id, type, year, bytes); } public EmbeddedKey getId() { return id; } public void setId(EmbeddedKey id) { this.id = id; } public static class EmbeddedKey { @PartitionKey @Order(1) private long id; @PartitionKey @Order(2) private PropertyType type; @Order(3) private Integer year; @Order(4) private ByteBuffer bytes; public EmbeddedKey() { } public EmbeddedKey(long id, PropertyType type, Integer year, ByteBuffer bytes) { this.id = id; this.type = type; this.year = year; this.bytes = bytes; } public long getId() { return id; } public void setId(long id) { this.id = id; } public PropertyType getType() { return type; } public void setType(PropertyType type) { this.type = type; } public Integer getYear() { return year; } public void setYear(Integer year) { this.year = year; } public ByteBuffer getBytes() { return bytes; } public void setBytes(ByteBuffer bytes) { this.bytes = bytes; } @Override public int hashCode() { return Objects.hash(this.id, this.type, this.year, this.bytes); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EmbeddedKey other = (EmbeddedKey) obj; return Objects.equals(this.id, other.id) && Objects.equals(this.type, other.type) && Objects.equals(this.year, other.year) && Objects.equals(this.bytes, other.bytes); } } }
23.954887
103
0.672316
532264af07fc435258da46712b18eefec907c9db
570
package cn.closeli.rtc.net.converter; import com.alibaba.fastjson.JSON; import okhttp3.MediaType; import okhttp3.RequestBody; import retrofit2.Converter; /** * * 将传过来的数据转换成requestBody */ final class FastJsonRequestBodyConverter<T> implements Converter<T, RequestBody> { /** 传json字符串的media type */ private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=UTF-8"); @Override public RequestBody convert(T value) { byte[] bodyBytes = JSON.toJSONBytes(value); return RequestBody.create(MEDIA_TYPE_JSON, bodyBytes); } }
20.357143
101
0.768421
f45a15e889df03a17fba1e5285b7fe6c280db2c9
999
package ai.elimu.logic.converters; import org.apache.commons.lang.StringUtils; import ai.elimu.dao.LetterToAllophoneMappingDao; import ai.elimu.model.content.LetterToAllophoneMapping; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.converter.Converter; public class StringToLetterToAllophoneMappingConverter implements Converter<String, LetterToAllophoneMapping> { @Autowired private LetterToAllophoneMappingDao letterToAllophoneMappingDao; /** * Convert LetterToAllophoneMapping id to LetterToAllophoneMapping entity */ public LetterToAllophoneMapping convert(String id) { if (StringUtils.isBlank(id)) { return null; } else { Long letterToAllophoneMappingId = Long.parseLong(id); LetterToAllophoneMapping letterToAllophoneMapping = letterToAllophoneMappingDao.read(letterToAllophoneMappingId); return letterToAllophoneMapping; } } }
37
125
0.763764
2055ca9f31f1b828e42ee31116d1ac9b87bbd628
1,773
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2019, Chris Fraire <[email protected]>. */ package org.opengrok.indexer.analysis.verilog; import org.opengrok.indexer.analysis.AbstractAnalyzer.Genre; import org.opengrok.indexer.analysis.FileAnalyzer; import org.opengrok.indexer.analysis.FileAnalyzerFactory; /** * Represents a factory to create {@link VerilogAnalyzer} instances. */ public class VerilogAnalyzerFactory extends FileAnalyzerFactory { private static final String NAME = "Verilog"; private static final String[] SUFFIXES = {"SV", "SVH", "V", "VH"}; /** * Initializes a factory instance to associate a file extensions ".sv", * ".svh", ".v", and ".vh" with {@link VerilogAnalyzer}. */ public VerilogAnalyzerFactory() { super(null, null, SUFFIXES, null, null, "text/plain", Genre.PLAIN, NAME); } /** * Creates a new {@link VerilogAnalyzer} instance. * @return a defined instance */ @Override protected FileAnalyzer newAnalyzer() { return new VerilogAnalyzer(this); } }
31.105263
75
0.702764
1a7bfd6240f492a05203b25c1dfb22e25e207beb
185
package com.atguigu.gmall.cart.vo; import lombok.Data; /** * Created by FJC on 2019-11-18. */ @Data public class CartItemVO { private Long skuId; private Integer count; }
12.333333
34
0.681081
04d2a301485f4e6aa007779cd2a149bf344f0e31
1,962
package jnapi.subtitles; import jnapi.mediainfo.MediaInfo; import java.io.File; import java.util.List; /** * Subtitles converter. Handles reading and writing of several subtitles formats * <p/> * Resource: http://leksykot.top.hell.pl/lx3/B/subtitle_formats#c1 * * @author Maciej Dragan */ public class Converter { List<Line> lines = null; private File videoFile; private float fps; public Converter(File videoFile) throws SubtitlesException { this.videoFile = videoFile; try { // Read subtitles framerate. This is needed for conversion MediaInfo mediaInfo = new MediaInfo(); mediaInfo.open(videoFile); fps = Float.parseFloat(mediaInfo.get(MediaInfo.StreamKind.Video, 0, "FrameRate")); } catch (NumberFormatException e) { throw new SubtitlesException("Could not detect video file FPS"); } } /** * Load and parse subtitles file * * @param fileName * @return Recognized format or null is none is found */ public Format loadSubtitles(String fileName) { return loadSubtitles(new File(fileName)); } public Format loadSubtitles(File subtitlesFile) { lines = null; for (Format format : Format.values()) { try { FormatHandler formatHandler = format.getFormatHandler(); lines = formatHandler.parse(subtitlesFile, fps); if (lines != null && lines.size() > 0) { return format; } } catch (Exception e) { } } return null; } /** * Save subtitles to specified format * * @param subtitlesFiles * @param format * @throws SubtitlesException */ public void saveSubtitles(File subtitlesFiles, Format format) throws SubtitlesException { format.getFormatHandler().save(subtitlesFiles, lines, fps); } }
27.633803
94
0.611111
6a276a640a3e374118fca00735c5c7fb67cc4c02
7,160
/** * Copyright (c) 2009-2013, Lukas Eder, [email protected] * All rights reserved. * * This software is licensed to you under the Apache License, Version 2.0 * (the "License"); You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * . Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * . Neither the name "jOOQ" nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.jooq.test._.testcases; import static java.util.Arrays.asList; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.jooq.SQLDialect.SQLITE; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import org.jooq.ExecuteContext; import org.jooq.Record1; import org.jooq.Record2; import org.jooq.Record3; import org.jooq.Record6; import org.jooq.TableRecord; import org.jooq.UpdatableRecord; import org.jooq.exception.DataAccessException; import org.jooq.impl.DefaultExecuteListener; import org.jooq.test.BaseTest; import org.jooq.test.jOOQAbstractTest; import org.junit.Test; public class ResultSetTests< A extends UpdatableRecord<A> & Record6<Integer, String, String, Date, Integer, ?>, AP, B extends UpdatableRecord<B>, S extends UpdatableRecord<S> & Record1<String>, B2S extends UpdatableRecord<B2S> & Record3<String, Integer, Integer>, BS extends UpdatableRecord<BS>, L extends TableRecord<L> & Record2<String, String>, X extends TableRecord<X>, DATE extends UpdatableRecord<DATE>, BOOL extends UpdatableRecord<BOOL>, D extends UpdatableRecord<D>, T extends UpdatableRecord<T>, U extends TableRecord<U>, UU extends UpdatableRecord<UU>, I extends TableRecord<I>, IPK extends UpdatableRecord<IPK>, T725 extends UpdatableRecord<T725>, T639 extends UpdatableRecord<T639>, T785 extends TableRecord<T785>> extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T725, T639, T785> { public ResultSetTests(jOOQAbstractTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T725, T639, T785> delegate) { super(delegate); } @Test public void testResultSetType() throws Exception { if (asList(SQLITE).contains(dialect())) { log.info("SKIPPING", "ResultSet type tests"); return; } ResultSet rs = create().select(TBook_ID()) .from(TBook()) .where(TBook_ID().in(1, 2)) .orderBy(TBook_ID()) .resultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE) .fetchResultSet(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertTrue(rs.previous()); assertEquals(1, rs.getInt(1)); assertTrue(rs.last()); assertEquals(2, rs.getInt(1)); rs.close(); } @SuppressWarnings("serial") @Test public void testResultSetTypeWithListener() throws Exception { if (asList(SQLITE).contains(dialect())) { log.info("SKIPPING", "ResultSet type tests"); return; } assertEquals( asList(1, 1, 1, 2), create(new DefaultExecuteListener() { int repeat; @Override public void recordEnd(ExecuteContext ctx) { try { // Rewind the first record three times if (++repeat < 3) ctx.resultSet().previous(); } catch (SQLException e) { throw new DataAccessException("Exception", e); } } }) .select(TBook_ID()) .from(TBook()) .where(TBook_ID().in(1, 2)) .orderBy(TBook_ID()) .resultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE) .fetch(TBook_ID())); } @SuppressWarnings("serial") @Test public void testResultSetConcurrency() throws Exception { switch (dialect()) { case MARIADB: case SQLITE: case SYBASE: log.info("SKIPPING", "ResultSet concurrency tests"); return; } jOOQAbstractTest.reset = false; assertEquals( asList("Title 1", "Title 2", "Title 3", "Title 4"), create(new DefaultExecuteListener() { int repeat; @Override public void recordStart(ExecuteContext ctx) { try { // Change values before reading a record ctx.resultSet().updateString(TBook_TITLE().getName(), "Title " + (++repeat)); ctx.resultSet().updateRow(); } catch (SQLException e) { throw new DataAccessException("Exception", e); } } }) .select(TBook_ID(), TBook_TITLE()) .from(TBook()) // Derby doesn't support ORDER BY when using CONCUR_UPDATABLE // https://issues.apache.org/jira/browse/DERBY-4138 // .orderBy(TBook_ID()) // SQL Server doesn't support SCROLL INSENSITIVE and UPDATABLE // .resultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE) .resultSetConcurrency(ResultSet.CONCUR_UPDATABLE) .fetch(TBook_TITLE())); } }
37.098446
134
0.600978
ca87db61f009e51bc51395562e242a6e64fbcd61
3,797
package se.plilja.imcollect.internal.fingertrees; import com.pholser.junit.quickcheck.Property; import com.pholser.junit.quickcheck.generator.InRange; import se.plilja.imcollect.internal.CollectionsBaseTest; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.stream.IntStream; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.junit.Assert.*; public class FingerTreeTest extends CollectionsBaseTest { public FingerTreeTest() { super(FingerTreeList.empty()); } @Property public void toMutableCollectionShouldReturnObjectEqualToArrayList(ArrayList<Integer> values) { var target = FingerTreeList.<Integer>empty(); target = target.addAll(values); // when var result = target.toMutableCollection(); // then assertEquals(values, result); } @Property public void setFollowedByGetShouldYieldSetValue(@InRange(minInt = 0, maxInt = 10) int idx, int value) { var target = FingerTreeList.<Integer>empty(); for (int i = 0; i < 11; i++) { target = target.add(i); } // when target = target.set(idx, value); int result = target.get(idx); // then assertEquals(value, result); } @Property public void accessingObjectWithIllegalIndexShouldYieldIndexOutOfBounds(List<Integer> values) { var target = FingerTreeList.<Integer>empty() .addAll(values); // when, then for (int j = -100; j < 0; j++) { verifyCausesOutOfBounds(j, i -> target.get(i)); verifyCausesOutOfBounds(j, i -> target.set(i, 4711)); } for (int j = values.size(); j < 100; j++) { verifyCausesOutOfBounds(j, i -> target.get(i)); verifyCausesOutOfBounds(j, i -> target.set(i, 4711)); } } private void verifyCausesOutOfBounds(int idx, Consumer<Integer> actionThatShouldCauseOutOfBoundsException) { try { actionThatShouldCauseOutOfBoundsException.accept(idx); fail("Should have triggered IndexOutOfBoundsException before reaching here"); } catch (IndexOutOfBoundsException ex) { // expected } } @Property public void getIndexOfShouldReturnValue(List<Integer> values) { var target = FingerTreeList.<Integer>empty() .addAll(values); for (int value : values) { assertEquals(value, (int) target.get(target.indexOf(value))); assertEquals(value, (int) target.get(target.lastIndexOf(value))); } } @Property public void getLastIndexOfVsIndexOf(List<Integer> values) { var target = FingerTreeList.<Integer>empty() .addAll(values); for (int value : values) { assert target.indexOf(value) != -1; assert target.lastIndexOf(value) != -1; assertEquals(0, IntStream.range(0, target.indexOf(value)) .filter(i -> target.get(i).equals(value)) .count()); assertEquals(0, IntStream.range(target.lastIndexOf(value) + 1, target.size()) .filter(i -> target.get(i).equals(value)) .count()); assertThat(target.indexOf(value), lessThanOrEqualTo(target.lastIndexOf(value))); } } @Property public void indexOfShouldReturnMinusOneForNonExistingValue(List<@InRange(minInt = -1000, maxInt = -1) Integer> values, @InRange(minInt = 0, maxInt = 1000) Integer query) { var target = FingerTreeList.<Integer>empty() .addAll(values); assertEquals(-1, target.indexOf(query)); assertEquals(-1, target.lastIndexOf(query)); } }
34.207207
175
0.624704
bce35f11b5c53ba2cb2c9604d4339b27721b2c4d
3,110
package db.migration; import org.flywaydb.core.api.migration.jdbc.JdbcMigration; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; public class V227__Migrate_TeachingCallReceipts_Comments_To_TeachingCallComments implements JdbcMigration { @Override public void migrate(Connection connection) throws Exception { // Create TeachingCallComments table String createTeachingCallComments = "CREATE TABLE IF NOT EXISTS `TeachingCallComments` (" + "`Id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY," + "`Comment` TEXT NOT NULL," + "`TeachingCallReceiptId` INT(11)," + "`UpdatedAt` TIMESTAMP NULL," + "`CreatedAt` TIMESTAMP NULL," + "`ModifiedBy` VARCHAR(16) NULL," + "FOREIGN KEY (`TeachingCallReceiptId`)" + " REFERENCES `TeachingCallReceipts`(`id`));"; PreparedStatement createTableStatement = connection.prepareStatement(createTeachingCallComments); // Get TeachingCallReceipts comments PreparedStatement commentsQuery = connection.prepareStatement( "SELECT" + " TeachingCallReceipts.`Id` AS TeachingCallReceiptId, " + " `Comment` " + " FROM `TeachingCallReceipts` " + " JOIN `Instructors` " + " ON Instructors.`id` = TeachingCallReceipts.`InstructorId` " + " WHERE `Comment` IS NOT NULL AND Comment<>''; "); ResultSet rsComments = commentsQuery.executeQuery(); try { createTableStatement.execute(); // Loop over combined comments and insert them into Receipts while(rsComments.next()) { long teachingCallReceiptId = rsComments.getLong("teachingCallReceiptId"); String comment = rsComments.getString("comment"); // Save combine comments in TeachingCallReceipts String insertTeachingCallCommentsQuery = "INSERT INTO `TeachingCallComments`" + " (Comment, TeachingCallReceiptId) " + " VALUES (?, ?)"; PreparedStatement insertTeachingCallCommentsStatement = connection.prepareStatement(insertTeachingCallCommentsQuery); insertTeachingCallCommentsStatement.setString(1, comment); insertTeachingCallCommentsStatement.setLong(2, teachingCallReceiptId); insertTeachingCallCommentsStatement.execute(); insertTeachingCallCommentsStatement.close(); } // Drop the Comment column from TeachingCallResponses String dropColumnQuery = "ALTER TABLE `TeachingCallReceipts` DROP COLUMN `Comment`;"; PreparedStatement dropColumnStatement = connection.prepareStatement(dropColumnQuery); dropColumnStatement.execute(); dropColumnStatement.close(); } finally { createTableStatement.close(); rsComments.close(); } } }
44.428571
133
0.627653
ab920b8773e8efe16530e796e34d8a18e6dae1cc
2,314
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2015 Dirk Beyer * 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. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.util.predicates.interpolation.strategy; import java.util.List; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.cpachecker.core.interfaces.AbstractState; import org.sosy_lab.cpachecker.util.Triple; import org.sosy_lab.cpachecker.util.predicates.interpolation.InterpolationManager; import org.sosy_lab.cpachecker.util.predicates.smt.FormulaManagerView; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.SolverException; public class SequentialInterpolationWithSolver<T> extends ITPStrategy<T> { /** * This strategy uses a SMT solver that directly computes a sequence of inductive interpolants. * Currently all SMT solvers except MathSat support this. */ public SequentialInterpolationWithSolver(LogManager pLogger, ShutdownNotifier pShutdownNotifier, FormulaManagerView pFmgr, BooleanFormulaManager pBfmgr) { super(pLogger, pShutdownNotifier, pFmgr, pBfmgr); } @Override public List<BooleanFormula> getInterpolants( final InterpolationManager.Interpolator<T> interpolator, final List<Triple<BooleanFormula, AbstractState, T>> formulasWithStatesAndGroupdIds) throws InterruptedException, SolverException { return interpolator.itpProver.getSeqInterpolants0( projectToThird(formulasWithStatesAndGroupdIds)); } }
39.896552
100
0.762316
07014a337ad846e462c7d44b3f41662a8e95652b
2,378
package it.chiarani.meteotrentinoapp.db; import android.content.Context; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import it.chiarani.meteotrentinoapp.api.MeteoTrentinoForecastModel.MeteoTrentinoForecast; import it.chiarani.meteotrentinoapp.api.OpenWeatherDataForecastModel.OpenWeatherDataForecast; import it.chiarani.meteotrentinoapp.db.converters.OpenWeatherDataCloudsConverter; import it.chiarani.meteotrentinoapp.db.converters.OpenWeatherDataCoordsConverter; import it.chiarani.meteotrentinoapp.db.converters.OpenWeatherDataMainConverter; import it.chiarani.meteotrentinoapp.db.converters.OpenWeatherDataSysConverter; import it.chiarani.meteotrentinoapp.db.converters.OpenWeatherDataWeatherConverter; import it.chiarani.meteotrentinoapp.db.converters.OpenWeatherDataWindConverter; import it.chiarani.meteotrentinoapp.db.converters.PrevisioneConverter; @Database(entities = { MeteoTrentinoForecast.class, OpenWeatherDataForecast.class }, version = 3, exportSchema = false) @TypeConverters( { PrevisioneConverter.class, OpenWeatherDataCoordsConverter.class, OpenWeatherDataMainConverter.class, OpenWeatherDataSysConverter.class, OpenWeatherDataWindConverter.class, OpenWeatherDataCloudsConverter.class, OpenWeatherDataWeatherConverter.class }) public abstract class AppDatabase extends RoomDatabase { private static volatile AppDatabase INSTANCE; // DAO's public abstract ForecastDao forecastDao(); public abstract OpenWeatherDataForecastDao openWeatherDataForecastDao(); /** * Get a singleton istance * @param context * @return AppDatabase db istance */ public static AppDatabase getInstance(Context context) { if (INSTANCE == null) { synchronized (AppDatabase.class) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "database.db") .fallbackToDestructiveMigration() .build(); } } } return INSTANCE; } }
37.15625
93
0.700168
1e98a7282417ef47e85c845ec3390983aca282e3
500
package com.tgithubc.kumao.bean; import java.util.List; /** * Created by tc :) */ public class SongListArray extends BaseData { private List<SongList> songLists; public List<SongList> getSongLists() { return songLists; } public void setSongLists(List<SongList> songLists) { this.songLists = songLists; } @Override public String toString() { return "SongListArray{" + "songLists=" + songLists + '}'; } }
17.857143
56
0.596
24e2b1ca8d2a8d7911d0a02b652669f5075a0094
11,651
/* * Copyright 2000-2014 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.buildServer.buildTriggers.vcs.git; import com.intellij.openapi.diagnostic.Logger; import jetbrains.buildServer.buildTriggers.vcs.git.submodules.IgnoreSubmoduleErrorsTreeFilter; import jetbrains.buildServer.buildTriggers.vcs.git.submodules.SubmoduleAwareTreeIterator; import jetbrains.buildServer.vcs.ModificationData; import jetbrains.buildServer.vcs.VcsChange; import jetbrains.buildServer.vcs.VcsException; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevSort; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author dmitry.neverov */ class ModificationDataRevWalk extends RevWalk { private static final Logger LOG = Logger.getInstance(ModificationDataRevWalk.class.getName()); private final ServerPluginConfig myConfig; private final OperationContext myContext; private final GitVcsRoot myGitRoot; private final Repository myRepository; private final int mySearchDepth; private int myNextCallCount = 0; private RevCommit myCurrentCommit; private int myNumberOfCommitsToVisit = -1; ModificationDataRevWalk(@NotNull ServerPluginConfig config, @NotNull OperationContext context) throws VcsException { super(context.getRepository()); myConfig = config; myContext = context; myGitRoot = context.getGitRoot(); myRepository = context.getRepository(); mySearchDepth = myConfig.getFixedSubmoduleCommitSearchDepth(); } @Override public RevCommit next() throws IOException { myCurrentCommit = super.next(); myNextCallCount++; if (myCurrentCommit != null && shouldLimitByNumberOfCommits() && myNextCallCount > myNumberOfCommitsToVisit) { myCurrentCommit = null; } return myCurrentCommit; } public void limitByNumberOfCommits(final int numberOfCommitsToVisit) { myNumberOfCommitsToVisit = numberOfCommitsToVisit; } @NotNull public ModificationData createModificationData() throws IOException, VcsException { if (myCurrentCommit == null) throw new IllegalStateException("Current commit is null"); final String commitId = myCurrentCommit.getId().name(); if (LOG.isDebugEnabled()) { LOG.debug("Collecting changes in commit " + commitId + ":" + myCurrentCommit.getShortMessage() + " (" + myCurrentCommit.getCommitterIdent().getWhen() + ") for " + myGitRoot.debugInfo()); } final String parentVersion = getFirstParentVersion(myCurrentCommit); final CommitChangesBuilder builder = new CommitChangesBuilder(myCurrentCommit, commitId, parentVersion); builder.collectCommitChanges(); final List<VcsChange> changes = builder.getChanges(); final PersonIdent authorIdent = getPersonIdent(); final ModificationData result = new ModificationData( authorIdent.getWhen(), changes, getFullMessage(), GitServerUtil.getUser(myGitRoot, authorIdent), myGitRoot.getOriginalRoot(), commitId, commitId); if (myCurrentCommit.getParentCount() > 0) { for (RevCommit parent : myCurrentCommit.getParents()) { parseBody(parent); result.addParentRevision(parent.getId().name()); } } else { result.addParentRevision(ObjectId.zeroId().name()); } return result; } private String getFullMessage() { try { return myCurrentCommit.getFullMessage(); } catch (UnsupportedCharsetException e) { LOG.warn("Cannot parse the " + myCurrentCommit.name() + " commit message due to unknown commit encoding '" + e.getCharsetName() + "'"); return "Cannot parse commit message due to unknown commit encoding '" + e.getCharsetName() + "'"; } } private PersonIdent getPersonIdent() { try { return myCurrentCommit.getAuthorIdent(); } catch (UnsupportedCharsetException e) { LOG.warn("Cannot parse the " + myCurrentCommit.name() + " commit author due to unknown commit encoding '" + e.getCharsetName() + "'"); return new PersonIdent("Can not parse", "Can not parse"); } } private boolean shouldLimitByNumberOfCommits() { return myNumberOfCommitsToVisit != -1; } private boolean shouldIgnoreSubmodulesErrors() { return myNextCallCount > 1;//ignore submodule errors for all commits excluding the first one } @NotNull private String getFirstParentVersion(@NotNull final RevCommit commit) throws IOException { final RevCommit[] parents = commit.getParents(); if (parents.length == 0) { return ObjectId.zeroId().name(); } else { RevCommit parent = parents[0]; parseBody(parent); return parent.getId().name(); } } private class CommitChangesBuilder { private final RevCommit commit; private final String currentVersion; private final String parentVersion; private final List<VcsChange> changes = new ArrayList<VcsChange>(); private final String repositoryDebugInfo = myGitRoot.debugInfo(); private final IgnoreSubmoduleErrorsTreeFilter filter = new IgnoreSubmoduleErrorsTreeFilter(myGitRoot); private final Map<String, RevCommit> commitsWithFix = new HashMap<String, RevCommit>(); /** * @param commit current commit * @param currentVersion teamcity version of current commit (sha@time) * @param parentVersion parent version to use in VcsChange objects */ public CommitChangesBuilder(@NotNull final RevCommit commit, @NotNull final String currentVersion, @NotNull final String parentVersion) { this.commit = commit; this.currentVersion = currentVersion; this.parentVersion = parentVersion; } @NotNull public List<VcsChange> getChanges() { return changes; } /** * collect changes for the commit */ public void collectCommitChanges() throws IOException, VcsException { final VcsChangeTreeWalk tw = new VcsChangeTreeWalk(myRepository, repositoryDebugInfo, myConfig.verboseTreeWalkLog()); try { tw.setFilter(filter); tw.setRecursive(true); myContext.addTree(myGitRoot, tw, myRepository, commit, shouldIgnoreSubmodulesErrors()); for (RevCommit parentCommit : commit.getParents()) { myContext.addTree(myGitRoot, tw, myRepository, parentCommit, true); } new VcsChangesTreeWalker(tw).walk(); } finally { tw.release(); } } private class VcsChangesTreeWalker { private final VcsChangeTreeWalk tw; private VcsChangesTreeWalker(@NotNull final VcsChangeTreeWalk tw) { this.tw = tw; } private void walk() throws IOException, VcsException { while (tw.next()) { final String path = tw.getPathString(); processChange(path); } } private void processChange(@NotNull final String path) throws IOException, VcsException { if (!myGitRoot.isCheckoutSubmodules()) { addVcsChange(); return; } if (filter.isBrokenSubmoduleEntry(path)) { final RevCommit commitWithFix = getPreviousCommitWithFixedSubmodule(commit, path); commitsWithFix.put(path, commitWithFix); if (commitWithFix != null) { subWalk(path, commitWithFix); return; } } if (filter.isChildOfBrokenSubmoduleEntry(path)) { final String brokenSubmodulePath = filter.getSubmodulePathForChildPath(path); final RevCommit commitWithFix = commitsWithFix.get(brokenSubmodulePath); if (commitWithFix != null) { subWalk(path, commitWithFix); return; } } addVcsChange(); } private void subWalk(@NotNull final String path, @NotNull final RevCommit commitWithFix) throws IOException, VcsException { final VcsChangeTreeWalk tw2 = new VcsChangeTreeWalk(myRepository, repositoryDebugInfo, myConfig.verboseTreeWalkLog()); try { tw2.setFilter(TreeFilter.ANY_DIFF); tw2.setRecursive(true); myContext.addTree(myGitRoot, tw2, myRepository, commit, true); myContext.addTree(myGitRoot, tw2, myRepository, commitWithFix, true); while (tw2.next()) { if (tw2.getPathString().equals(path)) { addVcsChange(currentVersion, commitWithFix.getId().name(), tw2); } } } finally { tw2.release(); } } private void addVcsChange() { addVcsChange(currentVersion, parentVersion, tw); } private void addVcsChange(@NotNull final String currentVersion, @NotNull final String parentVersion, @NotNull final VcsChangeTreeWalk tw) { final VcsChange change = tw.getVcsChange(currentVersion, parentVersion); if (change != null) changes.add(change); } } @Nullable private RevCommit getPreviousCommitWithFixedSubmodule(@NotNull final RevCommit fromCommit, @NotNull final String submodulePath) throws IOException, VcsException { if (mySearchDepth == 0) return null; final RevWalk revWalk = new RevWalk(myRepository); try { final RevCommit fromRev = revWalk.parseCommit(fromCommit.getId()); revWalk.markStart(fromRev); revWalk.sort(RevSort.TOPO); RevCommit result = null; RevCommit prevRev; revWalk.next(); int depth = 0; while (result == null && depth < mySearchDepth && (prevRev = revWalk.next()) != null) { depth++; final TreeWalk prevTreeWalk = new TreeWalk(myRepository); try { prevTreeWalk.setFilter(TreeFilter.ALL); prevTreeWalk.setRecursive(true); myContext.addTree(myGitRoot, prevTreeWalk, myRepository, prevRev, true, false); while(prevTreeWalk.next()) { String path = prevTreeWalk.getPathString(); if (path.startsWith(submodulePath + "/")) { final SubmoduleAwareTreeIterator iter = prevTreeWalk.getTree(0, SubmoduleAwareTreeIterator.class); final SubmoduleAwareTreeIterator parentIter = iter.getParent(); if (iter != null && !iter.isSubmoduleError() && parentIter != null && parentIter.isOnSubmodule()) { result = prevRev; break; } } } } finally { prevTreeWalk.release(); } } return result; } finally { revWalk.release(); } } } }
35.739264
141
0.677195
f4d793778a8566bbc3f7b10735f33a4357fdb0a5
164
package com.example.snaptrackapp.data; import com.google.firebase.database.annotations.Nullable; public interface Listener<T> { void update(@Nullable T t); }
20.5
57
0.77439
c44c9e860daec8e3f5f4add2705259912a4c5188
2,082
/** * 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.cxf.systest.brave; public abstract class BraveTestSupport { public static final String TRACE_ID_NAME = "X-B3-TraceId"; public static final String SPAN_ID_NAME = "X-B3-SpanId"; public static final String PARENT_SPAN_ID_NAME = "X-B3-ParentSpanId"; public static final String SAMPLED_NAME = "X-B3-Sampled"; public static class SpanId { private long traceId; private long spanId; private Long parentId; private boolean sampled; public SpanId traceId(long id) { this.traceId = id; return this; } public SpanId parentId(Long id) { this.parentId = id; return this; } public SpanId spanId(long id) { this.spanId = id; return this; } public SpanId sampled(boolean s) { this.sampled = s; return this; } public long traceId() { return traceId; } public long spanId() { return spanId; } public Long parentId() { return parentId; } public boolean sampled() { return sampled; } } }
29.323944
73
0.614313
2656b675fad277c6acef939b98e21c6f16ab24cc
2,373
/* * The MIT License (MIT) * * Copyright (c) 2019 Chathura Buddhika * * 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 lk.chathurabuddi.file.type.jrxml; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class JrxmlFileTypeFactory { @NonNls public static final String JRXML_EXTENSION = "jrxml"; @NonNls static final String DOT_JRXML_EXTENSION = "." + JRXML_EXTENSION; public static boolean isJrxml(@NotNull PsiFile file) { final VirtualFile virtualFile = file.getViewProvider().getVirtualFile(); return isJrxml(virtualFile); } public static boolean isJrxml(@NotNull VirtualFile virtualFile) { if (JRXML_EXTENSION.equals(virtualFile.getExtension())) { final FileType fileType = virtualFile.getFileType(); if (fileType == getFileType() && !fileType.isBinary()) { return virtualFile.getName().endsWith(DOT_JRXML_EXTENSION); } } return false; } @NotNull public static FileType getFileType() { return FileTypeManager.getInstance().getFileTypeByExtension(JRXML_EXTENSION); } }
40.913793
85
0.736199
ee114c2ac7ed5677db47808f297097266b9fe732
1,481
package slimeknights.tconstruct.library.book.content; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.content.ContentImageText; import slimeknights.mantle.client.book.data.element.ImageData; import slimeknights.mantle.client.screen.book.BookScreen; import slimeknights.mantle.client.screen.book.element.BookElement; import slimeknights.mantle.client.screen.book.element.ImageElement; import slimeknights.mantle.client.screen.book.element.TextElement; import java.util.ArrayList; @Environment(EnvType.CLIENT) public class ContentImageText2 extends ContentImageText { public static final transient String ID = "imageText2"; @Override public void build(BookData book, ArrayList<BookElement> list, boolean rightSide) { int y = TITLE_HEIGHT; if (this.title == null || this.title.isEmpty()) { y = 0; } else { this.addTitle(list, this.title); } if (this.image != null && this.image.location != null) { int x = (BookScreen.PAGE_HEIGHT - this.image.width) / 2; list.add(new ImageElement(x, y, -1, -1, this.image)); y += this.image.height; } else { list.add(new ImageElement(0, y, 32, 32, ImageData.MISSING)); } if (this.text != null && this.text.length > 0) { y += 5; list.add(new TextElement(0, y, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT - y, this.text)); } } }
32.911111
100
0.719109
acd740b1fd53378d475575017f1cc75100ed17e7
5,881
/* * Copyright 2020 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.tools.opensource.classpath; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.google.cloud.tools.opensource.dependencies.DependencyPath; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.UnmodifiableIterator; import java.nio.file.Paths; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.graph.Dependency; import org.junit.Test; public class ClassPathResultTest { private Artifact artifactA = new DefaultArtifact("com.google:a:1").setFile(Paths.get("a.jar").toFile()); private Artifact artifactB = new DefaultArtifact("com.google:b:1").setFile(Paths.get("b.jar").toFile()); private DependencyPath dependencyPath_A = new DependencyPath(null).append(new Dependency(artifactA, "compile")); private DependencyPath dependencyPath_B = new DependencyPath(null).append(new Dependency(artifactB, "compile")); private DependencyPath dependencyPath_B_A = new DependencyPath(null) .append(new Dependency(artifactB, "compile")) .append(new Dependency(artifactA, "compile")); private DependencyPath dependencyPath_A_B_A = new DependencyPath(null) .append(new Dependency(artifactA, "compile")) .append(new Dependency(artifactB, "compile")) .append(new Dependency(artifactA, "compile")); private ClassPathEntry jarA = new ClassPathEntry(artifactA); private ClassPathEntry jarB = new ClassPathEntry(artifactB); @Test public void testFormatDependencyPaths_onePath() { AnnotatedClassPath annotatedClassPath = AnnotatedClassPath.fromMultimap( ImmutableListMultimap.of(jarA, dependencyPath_A, jarB, dependencyPath_B)); ClassPathResult classPathResult = new ClassPathResult(annotatedClassPath, ImmutableSet.of()); String actual = classPathResult.formatDependencyPaths(ImmutableList.of(jarA)); assertEquals("com.google:a:1 is at:\n" + " com.google:a:1 (compile)\n", actual); } @Test public void testFormatDependencyPaths_path_A_B() { AnnotatedClassPath annotatedClassPath = AnnotatedClassPath.fromMultimap( ImmutableListMultimap.of(jarA, dependencyPath_A, jarB, dependencyPath_B)); ClassPathResult classPathResult = new ClassPathResult(annotatedClassPath, ImmutableSet.of()); String actual = classPathResult.formatDependencyPaths(ImmutableList.of(jarA, jarB)); assertEquals( "com.google:a:1 is at:\n" + " com.google:a:1 (compile)\n" + "com.google:b:1 is at:\n" + " com.google:b:1 (compile)\n", actual); } @Test public void testFormatDependencyPaths_twoPathsForA() { AnnotatedClassPath annotatedClassPath = AnnotatedClassPath.fromMultimap( ImmutableListMultimap.of(jarA, dependencyPath_A, jarA, dependencyPath_B_A)); ClassPathResult classPathResult = new ClassPathResult(annotatedClassPath, ImmutableSet.of()); String actual = classPathResult.formatDependencyPaths(ImmutableList.of(jarA)); assertEquals( "com.google:a:1 is at:\n" + " com.google:a:1 (compile)\n" + " and 1 dependency path.\n", actual); } @Test public void testFormatDependencyPaths_threePathsForA() { AnnotatedClassPath annotatedClassPath = AnnotatedClassPath.fromMultimap( ImmutableListMultimap.of( jarA, dependencyPath_A, jarA, dependencyPath_B_A, jarA, dependencyPath_A_B_A)); ClassPathResult classPathResult = new ClassPathResult(annotatedClassPath, ImmutableSet.of()); String actual = classPathResult.formatDependencyPaths(ImmutableList.of(jarA)); assertEquals( "com.google:a:1 is at:\n" + " com.google:a:1 (compile)\n" + " and 2 other dependency paths.\n", actual); } @Test public void testFormatDependencyPaths_irrelevantJar() { AnnotatedClassPath annotatedClassPath = AnnotatedClassPath.fromMultimap(ImmutableListMultimap.of(jarA, dependencyPath_A)); ClassPathResult classPathResult = new ClassPathResult(annotatedClassPath, ImmutableSet.of()); try { classPathResult.formatDependencyPaths(ImmutableList.of(jarB)); fail("The irrelevant JAR file should be invalidated."); } catch (IllegalArgumentException expected) { assertEquals("com.google:b:1 is not in the class path", expected.getMessage()); } } @Test public void testGetClassPathEntries() { AnnotatedClassPath annotatedClassPath = AnnotatedClassPath.fromMultimap( ImmutableListMultimap.of( jarA, dependencyPath_A, jarB, dependencyPath_B, jarA, dependencyPath_A_B_A)); ClassPathResult result = new ClassPathResult(annotatedClassPath, ImmutableSet.of()); ImmutableSet<ClassPathEntry> classPathEntries = result.getClassPathEntries("com.google:a:1"); assertEquals(1, classPathEntries.size()); UnmodifiableIterator<ClassPathEntry> iterator = classPathEntries.iterator(); assertEquals(Paths.get("a.jar"), iterator.next().getJar()); } }
39.206667
98
0.725897
643227068dbc13b52029a25b0143afbe8e2a1aec
1,684
package net.minecraft.client.gui; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.client.resources.I18n; import net.minecraft.network.play.client.C0BPacketEntityAction; public class GuiSleepMP extends GuiChat { /** * Adds the buttons (and other controls) to the screen in question. */ public void initGui() { super.initGui(); this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height - 40, I18n.format("multiplayer.stopSleeping", new Object[0]))); } /** * Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e). */ protected void keyTyped(char p_73869_1_, int p_73869_2_) { if (p_73869_2_ == 1) { this.func_146418_g(); } else if (p_73869_2_ != 28 && p_73869_2_ != 156) { super.keyTyped(p_73869_1_, p_73869_2_); } else { String var3 = this.field_146415_a.getText().trim(); if (!var3.isEmpty()) { this.mc.thePlayer.sendChatMessage(var3); } this.field_146415_a.setText(""); this.mc.ingameGUI.getChatGUI().resetScroll(); } } protected void actionPerformed(GuiButton p_146284_1_) { if (p_146284_1_.id == 1) { this.func_146418_g(); } else { super.actionPerformed(p_146284_1_); } } private void func_146418_g() { NetHandlerPlayClient var1 = this.mc.thePlayer.sendQueue; var1.addToSendQueue(new C0BPacketEntityAction(this.mc.thePlayer, 3)); } }
26.3125
142
0.589667
180952ba4932a0fac746e94e2523e72439554bb6
7,933
package com.helencoder.util; import com.helencoder.util.json.JSONException; import com.helencoder.util.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * LTP组件调用类 * * Created by helencoder on 2017/9/18. */ public class LtpUtil { private static String api_key = "l1v3x7B6k9kYJCwxQytFkp7BPixDQXRKOZvo4m2a"; public static void main(String[] args) { // 测试用例 } /** * LTP组件分词外部调用方法 * * @param data 带分词的句子或文本 * @param optFlag true 分词优化 false 未优化 * @param posFlag true 附带词性 false 不附带词性 * @param filterFlag true 词性过滤 false 未过滤 * @return List<String> (单词list 或者 单词\t词性) * */ // public static List<String> ws(String data, Boolean optFlag, Boolean posFlag, Boolean filterFlag) { // String s = data; // String x = "n"; // String t = "dp"; // // String response = ltpRequest(s, x, t); // List<JSONObject> originalList = ltpResponseParse(response); // // } /** * LTP组件分词优化方法(默认依存句法分析) * * @param data 待分词句子或文本 * @return List<String> 分词优化后的单词list */ public static List<String> run(String data) { String s = data; String x = "n"; String t = "dp"; String response = ltpRequest(s, x, t, false); List<JSONObject> originalList = ltpResponseParse(response); // 分词优化 List<String> optimizeList = segOptimization(originalList); return optimizeList; } /** * LTP词性过滤 * * @param wordData 分词后结果(单词\t词性),某些不包含词性的单词为已处理过,默认保留 * @return Boolean true 保留 false 过滤 */ public static Boolean isWordAllow(String wordData) { if (wordData.indexOf("\t") == -1) { return true; } String[] filterPos = {"wp", "u", "c", "p", "nd", "o", "e", "g", "h", "k", "q"}; List<String> filterPosList = Arrays.asList(filterPos); if (filterPosList.contains(wordData.split("\t")[1])) { return false; } return true; } /** * LTP组件请求方法 * * 请求参数和数据 形式"s=xxx&x=xxx&t=xxx" * @param s 输入字符串,在xml选项x为n的时候,代表输入句子,为y时代表输入xml * @param x 用以志明是否使用xml * @param t 用以指明分析目标,t可以为分词(ws),词性标注(pos),命名实体识别(ner),依存句法分析(dp),语义角色标注(srl)或者全部任务(all) * @param flag 在线 true;离线 false * @return json数据(自定义方法解析) */ public static String ltpRequest(String s, String x, String t, boolean flag) { String response = ""; if (flag) { // 在线版本 String api_url = "http://api.ltp-cloud.com/analysis/"; String pattern = "all"; String format = "json"; try { String param = "api_key=" + api_key + "&text=" + URLEncoder.encode(s, "UTF-8") + "&pattern=" + pattern + "&format=" + format; response = Request.get(api_url, param); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } } else { // 离线版本 String url = "http://99.6.184.75:12345/ltp"; String param = "s=" + s + "&x=" + x + "&t=" + t; response = Request.post(url, param); } return response; } /** * LTP server返回数据解析 * 基本思路: 遍历查找,配对截取{} * * @param data ltp返回的json数据格式 (三层[]中包含多个{},每个分词结果对应一个{}) * @return List<JSONObeject> 分词信息list(包含词性,依存句法信息等的json对象) */ public static List<JSONObject> ltpResponseParse(String data) { List<JSONObject> list = new ArrayList<JSONObject>(); // '{'和'}'两个符号索引值和出现次数记录 int leftIndex = 0; int leftCount = 0; int rightIndex = 0; int rightCount = 0; for (int i = 0; i < data.length(); i++) { if (leftCount == rightCount && leftCount != 0) { // 将原有统计数置0 leftCount = 0; rightCount = 0; // 此时进行截取 String str = data.substring(leftIndex, rightIndex + 1); // json数据解析 try { JSONObject json = new JSONObject(str); list.add(json); } catch (JSONException ex) { ex.printStackTrace(); } } // 碰到左侧'{'的情况 if (data.charAt(i) == '{') { if (leftCount == 0) { leftIndex = i; } leftCount++; } // 碰到右侧'}'的情况 if (data.charAt(i) == '}') { rightCount++; rightIndex = i; } } return list; } /** * 分词优化,遇到id为0重新进行截取计算 * 基本思路:按照句子(id为0)进行截取,按照句子进行分词优化 * * @param list 未经优化的ltp分词信息结果list * @param list<String> 优化后的分词结果list(单词\t词性) */ private static List<String> segOptimization(List<JSONObject> list) { // 分词优化的单词记录 List<String> words = new ArrayList<String>(); // 进行遍历截取 int startIndex = 0; List<JSONObject> listCopy = new ArrayList<JSONObject>(list); for (int i = 1; i < list.size(); i++) { try { JSONObject json = list.get(i); if (json.getInt("id") == 0) { int endIndex = i; // list截取 List<JSONObject> sentenceList = list.subList(startIndex, endIndex); // 进行分词优化 List<String> segWords = segSentenceOptimization(sentenceList); words.addAll(segWords); startIndex = i; } // 当进行到最后时进行进一步截取 if (i == list.size() - 1) { List<JSONObject> sentenceList = list.subList(startIndex, list.size()); List<String> segWords = segSentenceOptimization(sentenceList); words.addAll(segWords); } } catch (JSONException ex) { ex.printStackTrace(); } } return words; } /** * LTP组件分词优化(单个句子)(依存句法分析) * 基本思路:利用依存句法分析,将定中关系(ATT)进行合成,仅对相邻的单词进行操作 * * @param list 单个句子的ltp分词信息结果list * @return List<String> 优化分词结果list(单词\t词性) */ private static List<String> segSentenceOptimization(List<JSONObject> list) { // 分词优化的单词记录 List<String> words = new ArrayList<String>(); // 已处理的id号记录 List<Integer> handleFlag = new ArrayList<Integer>(); for (int i = 0; i < list.size(); i++) { // 是否已处理的检测 if (handleFlag.contains(i)) { continue; } handleFlag.add(i); JSONObject json = list.get(i); try { // 定中关系(ATT)的合并,仅对前后单词进行合并 //if (json.has("relate") && (json.getString("relate").equals("ATT") || json.getString("relate").equals("ADV")) && (i + 1) == json.getInt("parent")) { if (json.has("relate") && json.getString("relate").equals("ATT") && json.getString("pos").equals("n") && (i + 1) == json.getInt("parent")) { // 获取其对应的parent的id号 String tmpWord = json.getString("cont"); int parentid = json.getInt("parent"); handleFlag.add(parentid); // 获取对应的父类信息 JSONObject parentData = list.get(parentid); String parentWord = parentData.getString("cont"); String word = tmpWord + parentWord; words.add(word); } else { // 获取单词的词性 words.add(json.getString("cont") + "\t" + json.getString("pos")); } } catch (JSONException ex) { ex.printStackTrace(); } } return words; } }
31.355731
165
0.507752
e1f9531e2a5fbebe9ea46d7dc6243463831b6dad
1,483
package com.github.cstettler.dddttc.support.test; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import static org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData; import static org.springframework.test.context.junit.jupiter.SpringExtension.getApplicationContext; public class DatabaseCleaner implements AfterEachCallback { @SuppressWarnings("ConstantConditions") @Override public void afterEach(ExtensionContext context) throws Exception { JdbcTemplate jdbcTemplate = getApplicationContext(context).getBean(JdbcTemplate.class); DataSource dataSource = jdbcTemplate.getDataSource(); extractDatabaseMetaData(dataSource, (databaseMetaData) -> { truncateTables(jdbcTemplate, databaseMetaData); return null; }); } @SuppressWarnings("SqlResolve") private static void truncateTables(JdbcTemplate jdbcTemplate, DatabaseMetaData databaseMetaData) throws SQLException { ResultSet resultSet = databaseMetaData.getTables(null, null, "%", new String[]{"TABLE"}); while (resultSet.next()) { String tableName = resultSet.getString(3); jdbcTemplate.execute("DELETE FROM \"" + tableName + "\""); } } }
35.309524
122
0.74646
26e43f3a031fc42f5382d783ce66be170d64044f
8,970
package com.codejam.amadeha.game.core.widget; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.graphics.RectF; import android.os.Build; import android.support.v7.widget.AppCompatTextView; import android.text.Layout.Alignment; import android.text.StaticLayout; import android.text.TextPaint; import android.util.AttributeSet; import android.util.SparseIntArray; import android.util.TypedValue; public class AutoResizeTextView extends AppCompatTextView { private interface SizeTester { /** * @param suggestedSize Size of text to be tested * @param availableSpace available space in which text must fit * @return an integer < 0 if after applying {@code suggestedSize} to * text, it takes less space than {@code availableSpace}, > 0 * otherwise */ int onTestSize(int suggestedSize, RectF availableSpace); } private static final int NO_LINE_LIMIT = -1; private RectF mTextRect = new RectF(); private RectF mAvailableSpaceRect; private SparseIntArray mTextCachedSizes; private TextPaint mPaint; private float mMaxTextSize; private float mSpacingMult = 1.0f; private float mSpacingAdd = 0.0f; private float mMinTextSize = 20; private int mWidthLimit; private int mMaxLines; private boolean mEnableSizeCache = true; private boolean mInitiallized; public AutoResizeTextView(Context context) { super(context); initialize(); } public AutoResizeTextView(Context context, AttributeSet attrs) { super(context, attrs); initialize(); } public AutoResizeTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initialize(); } private void initialize() { mPaint = new TextPaint(getPaint()); mMaxTextSize = getTextSize(); mAvailableSpaceRect = new RectF(); mTextCachedSizes = new SparseIntArray(); if (mMaxLines == 0) { // no value was assigned during construction mMaxLines = NO_LINE_LIMIT; } mInitiallized = true; } @Override public void setText(final CharSequence text, BufferType type) { super.setText(text, type); adjustTextSize(text.toString()); } @Override public void setTextSize(float size) { mMaxTextSize = size; mTextCachedSizes.clear(); adjustTextSize(getText().toString()); } @Override public void setMaxLines(int maxlines) { super.setMaxLines(maxlines); mMaxLines = maxlines; reAdjust(); } public int getMaxLines() { return mMaxLines; } @Override public void setSingleLine() { super.setSingleLine(); mMaxLines = 1; reAdjust(); } @Override public void setSingleLine(boolean singleLine) { super.setSingleLine(singleLine); if (singleLine) mMaxLines = 1; else mMaxLines = NO_LINE_LIMIT; reAdjust(); } @Override public void setLines(int lines) { super.setLines(lines); mMaxLines = lines; reAdjust(); } @Override public void setTextSize(int unit, float size) { Context c = getContext(); Resources r; if (c == null) r = Resources.getSystem(); else r = c.getResources(); mMaxTextSize = TypedValue.applyDimension(unit, size, r.getDisplayMetrics()); mTextCachedSizes.clear(); adjustTextSize(getText().toString()); } @Override public void setLineSpacing(float add, float mult) { super.setLineSpacing(add, mult); mSpacingMult = mult; mSpacingAdd = add; } /** * SetType the lower text size limit and invalidate the view * * @param minTextSize Minimum text size */ public void setMinTextSize(float minTextSize) { mMinTextSize = minTextSize; reAdjust(); } private void reAdjust() { adjustTextSize(getText().toString()); } private void adjustTextSize(String string) { if (!mInitiallized) { return; } int startSize = (int) mMinTextSize; int heightLimit = getMeasuredHeight() - getCompoundPaddingBottom() - getCompoundPaddingTop(); mWidthLimit = getMeasuredWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight(); mAvailableSpaceRect.right = mWidthLimit; mAvailableSpaceRect.bottom = heightLimit; super.setTextSize( TypedValue.COMPLEX_UNIT_PX, efficientTextSizeSearch(startSize, (int) mMaxTextSize, mSizeTester, mAvailableSpaceRect)); } private final SizeTester mSizeTester = new SizeTester() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public int onTestSize(int suggestedSize, RectF availableSPace) { mPaint.setTextSize(suggestedSize); String text = getText().toString(); boolean singleline = getMaxLines() == 1; if (singleline) { mTextRect.bottom = mPaint.getFontSpacing(); mTextRect.right = mPaint.measureText(text); } else { StaticLayout layout = new StaticLayout(text, mPaint, mWidthLimit, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true); // return early if we have more lines if (getMaxLines() != NO_LINE_LIMIT && layout.getLineCount() > getMaxLines()) { return 1; } mTextRect.bottom = layout.getHeight(); int maxWidth = -1; for (int i = 0; i < layout.getLineCount(); i++) { if (maxWidth < layout.getLineWidth(i)) { maxWidth = (int) layout.getLineWidth(i); } } mTextRect.right = maxWidth; } mTextRect.offsetTo(0, 0); if (availableSPace.contains(mTextRect)) { // may be too small, don't worry we will find the best match return -1; } else { // too big return 1; } } }; /** * Enables or disables size caching, enabling it will improve performance * where you are animating a value inside TextView. This stores the font * size against getText().length() Be careful though while enabling it as 0 * takes more space than 1 on some fonts and so on. * * @param enable enable font size caching */ public void enableSizeCache(boolean enable) { mEnableSizeCache = enable; mTextCachedSizes.clear(); adjustTextSize(getText().toString()); } private int efficientTextSizeSearch(int start, int end, SizeTester sizeTester, RectF availableSpace) { if (!mEnableSizeCache) { return binarySearch(start, end, sizeTester, availableSpace); } String text = getText().toString(); int key = text == null ? 0 : text.length(); int size = mTextCachedSizes.get(key); if (size != 0) { return size; } size = binarySearch(start, end, sizeTester, availableSpace); mTextCachedSizes.put(key, size); return size; } private static int binarySearch(int start, int end, SizeTester sizeTester, RectF availableSpace) { int lastBest = start; int lo = start; int hi = end - 1; int mid; while (lo <= hi) { mid = (lo + hi) >>> 1; int midValCmp = sizeTester.onTestSize(mid, availableSpace); if (midValCmp < 0) { lastBest = lo; lo = mid + 1; } else if (midValCmp > 0) { hi = mid - 1; lastBest = hi; } else { return mid; } } // bake sure to return last best // this is what should always be returned return lastBest; } @Override protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) { super.onTextChanged(text, start, before, after); reAdjust(); } @Override protected void onSizeChanged(int width, int height, int oldwidth, int oldheight) { mTextCachedSizes.clear(); super.onSizeChanged(width, height, oldwidth, oldheight); if (width != oldwidth || height != oldheight) { reAdjust(); } } }
31.473684
86
0.580491
a079fbe1db61b03ea30d876b66f40946693f2928
3,125
package com.cy.core.region.action; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.cy.core.region.entity.Region; import com.cy.core.region.service.RegionService; import org.apache.log4j.Logger; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.springframework.beans.factory.annotation.Autowired; import com.cy.base.action.AdminBaseAction; import com.cy.base.entity.Message; import com.cy.core.region.entity.Country; import com.cy.core.region.service.CountryService; @Namespace("/country") @Action(value = "countryAction") public class CountryAction extends AdminBaseAction { private static final Logger logger = Logger.getLogger(CountryAction.class); //add by jiangling @Autowired private RegionService regionService; @Autowired private CountryService countryService; public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } private Country country; private Region region; // public String getSid() { // return sid; // } // // public void setSid(String sid) { // this.sid = sid; // } // // private String sid; public void doNotNeedSecurity_getCountry2ComboBox() { List<Country> list = countryService.selectAll(); super.writeJson(list); } public void save() { Message message = new Message(); try { if(country==null){ message.setMsg("传参为空"); message.setSuccess(false); return; } int count = countryService.countByCountryName(country); if (count > 0) { message.setMsg("国家名称已被占用"); message.setSuccess(false); } else { country.setCreateuser(getUser().getUserId()+""); country.setCreatetime(new Date()); country.setDelstate("0"); countryService.save(country); message.setMsg("新增成功"); message.setSuccess(true); } } catch (Exception e) { logger.error(e, e); message.setMsg("新增失败"); message.setSuccess(false); } super.writeJson(message); } public void update() { Message message = new Message(); try { int count = countryService.countByCountryName(country); if (count > 0) { message.setMsg("国家名称已被占用"); message.setSuccess(false); } else { country.setUpdateuser(getUser().getUserId()+""); country.setUpdatetime(new Date()); countryService.update(country); message.setMsg("修改成功"); message.setSuccess(true); } } catch (Exception e) { logger.error(e, e); message.setMsg("修改失败"); message.setSuccess(false); } super.writeJson(message); } public void delete() { Message message = new Message(); try { List<Country> countries = new ArrayList<Country>(); countries.add(country); for (Country city : countries) { countryService.delete(city); } message.setMsg("删除成功"); message.setSuccess(true); } catch (Exception e) { logger.error(e, e); message.setMsg("删除失败"); message.setSuccess(false); } super.writeJson(message); } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } }
23.148148
76
0.70016
80ebf6aae7868b1c6f4c9a8086eeb8833b5fd991
585
package com.songjachin.himalaya.interfaces; import com.songjachin.himalaya.base.IBasePresenter; /** * Created by matthew on 2020/4/25 9:44 * day day up! */ public interface IRecommendPresenter extends IBasePresenter<IRecommendViewCallback> { /** *获取推荐内容 */ void getRecommendList(); /** *下拉加载更多 */ void refreshMore(); /** * 加载更多 */ void loadMore(); /** * note:这个方法用于注册UI的回调 */ /* void registerViewCallback(IRecommendViewCallback callback); void unregisterViewCallback(IRecommendViewCallback callback);*/ }
20.172414
85
0.659829
c50c5797eeee1050d0c88b6676377f97468ddb3b
2,130
/* * Copyright 2000-2017 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 com.intellij.java.codeInsight; import com.intellij.openapi.project.Project; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.search.GlobalSearchScope; public class ClsGenerics18HighlightingTest extends ClsGenericsHighlightingTest { public void testIDEA121866() { doTest(); } public void testIDEA127714() { doTest(); } public void testoverload() { doTest(); } public void testIDEA151367() throws Exception { doTest(); } public void testIDEA157254() throws Exception { doTest(); } public void testOuterClassTypeArgs() throws Exception { doTest(); } public void testCaptureContext() { String name = getTestName(false); addLibrary(name + ".jar", name + "-sources.jar"); Project project = myFixture.getProject(); PsiClass aClass = JavaPsiFacade.getInstance(project).findClass("a.Pair", GlobalSearchScope.allScope(project)); assertNotNull(aClass); PsiFile containingFile = aClass.getContainingFile(); PsiElement navigationElement = containingFile.getNavigationElement(); assertInstanceOf(navigationElement, PsiFileImpl.class); myFixture.openFileInEditor(((PsiFile)navigationElement).getVirtualFile()); myFixture.checkHighlighting(); } @Override protected LanguageLevel getLanguageLevel() { return LanguageLevel.JDK_1_8; } }
33.28125
114
0.752582
cf57453535cb9a75c29c833ccb48123f79b7b0e4
2,116
// Copyright (c) 2021, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.ir.desugar; import com.android.tools.r8.graph.DexEncodedMethod; import com.android.tools.r8.graph.DexMember; import com.android.tools.r8.graph.DexProgramClass; import com.android.tools.r8.graph.DexReference; import com.android.tools.r8.graph.ProgramMethod; import com.android.tools.r8.utils.ThreadUtils; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.function.BiConsumer; import java.util.function.Supplier; public class ProgramAdditions implements BiConsumer<DexMember<?, ?>, Supplier<ProgramMethod>> { private final Set<DexReference> added = Sets.newConcurrentHashSet(); private final Map<DexProgramClass, List<DexEncodedMethod>> additions = new ConcurrentHashMap<>(); @Override public synchronized void accept( DexMember<?, ?> reference, Supplier<ProgramMethod> programMethodSupplier) { if (added.add(reference)) { ProgramMethod method = programMethodSupplier.get(); List<DexEncodedMethod> methods = additions.computeIfAbsent(method.getHolder(), k -> new ArrayList<>()); synchronized (methods) { assert !methods.contains(method.getDefinition()); assert method.getHolder().lookupProgramMethod(method.getReference()) == null; methods.add(method.getDefinition()); } } } public void apply(ExecutorService executorService) throws ExecutionException { ThreadUtils.processMap( additions, (clazz, methods) -> { methods.sort(Comparator.comparing(DexEncodedMethod::getReference)); clazz.getMethodCollection().addDirectMethods(methods); }, executorService); } }
39.185185
99
0.747637
de1068b39158d18620a654ab5a9df84ce36c5de2
762
package br.com.lorenzowindmoller.projecthub.service.repository.Project; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import java.util.List; import br.com.lorenzowindmoller.projecthub.service.model.Project.Project; @Dao public interface ProjectDao { @Insert void insert(Project project); @Update void update(Project project); @Delete void delete(Project project); @Query("DELETE FROM projects_table WHERE user_id = :user_id") void deleteAllProjects(int user_id); @Query("SELECT * FROM projects_table WHERE user_id = :user_id") LiveData<List<Project>> getAllProjects(int user_id); }
23.8125
73
0.761155
e50f5abe455fed48ec69acfc360d408dbce95617
1,504
package com.readytalk.cultivar.health; import static com.google.common.util.concurrent.Service.State.FAILED; import static com.google.common.util.concurrent.Service.State.STOPPING; import static com.google.common.util.concurrent.Service.State.TERMINATED; import com.codahale.metrics.health.HealthCheck; import com.google.common.util.concurrent.Service.State; import com.google.inject.Inject; import com.google.inject.Singleton; import com.readytalk.cultivar.CultivarStartStopManager; /** * Checks to determine if the connection to ZK is either NEW, STARTING, or has started properly. Fails if the * CultivarStartStopManager is in the states FAILED, STOPPING, or TERMINATED. */ @Singleton public class CuratorManagerStatus extends HealthCheck { private final CultivarStartStopManager startStopManager; @Inject CuratorManagerStatus(final CultivarStartStopManager startStopManager) { this.startStopManager = startStopManager; } @Override protected Result check() throws Exception { State state = startStopManager.state(); Result retval; if (FAILED.equals(state)) { retval = Result.unhealthy(startStopManager.failureCause()); } else if (TERMINATED.equals(state) || STOPPING.equals(state)) { retval = HealthCheck.Result.unhealthy("State is %s!", state); } else { retval = HealthCheck.Result.healthy("Current state is: %s", String.valueOf(state)); } return retval; } }
33.422222
109
0.731383
638b3d83c0f185e36d06af9e4a0773007f8b71f7
1,521
/*- * #%L * Bobcat * %% * Copyright (C) 2016 Wunderman Thompson Technology * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.cognifide.qa.bobcumber; import com.cognifide.bdd.demo.po.customersurvey.RadioComponent; import com.cognifide.bdd.demo.po.feedback.TextFieldComponent; import com.cognifide.bdd.demo.po.feedback.TitleComponent; import com.cognifide.qa.bb.aem.Components; /** * Enum that maps a component to its related PageObject class. */ public enum DemoComponents implements Components { TEXT_FIELD_COMPONENT(TextFieldComponent.class), TITLE(TitleComponent.class), RADIO_GROUP(RadioComponent.class); private final Class<?> clazz; DemoComponents(Class<?> clazz) { this.clazz = clazz; } public static DemoComponents fromString(String componentName) { String normalized = componentName.replace(" ", "_").toUpperCase(); return DemoComponents.valueOf(normalized); } @Override public Class<?> getComponentClass() { return clazz; } }
29.25
75
0.738988