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
0f1bad8845fc45936379cc9167f71574a9856dc2
3,106
/* * Copyright 2007 The Depan Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.devtools.depan.view_doc.eclipse.ui.editor; import com.google.devtools.depan.platform.NewEditorHelper; import com.google.devtools.depan.view_doc.eclipse.ViewDocResources; import com.google.devtools.depan.view_doc.layout.model.LayoutPlan; import com.google.devtools.depan.view_doc.model.ViewDocument; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IPersistableElement; /** * @author ycoppel@google.com (Yohann Coppel) */ public class ViewEditorInput implements IEditorInput { private static final String NEW_VIEW = "New View"; private final ViewDocument viewInfo; private final String baseName; private LayoutPlan initialLayout; private String displayName; public ViewEditorInput(ViewDocument viewInfo, String baseName) { this.viewInfo = viewInfo; this.baseName = baseName; } public String getBaseName() { return baseName; } private String calcDisplayName() { if (null == baseName) { return NEW_VIEW; } if (baseName.isEmpty()) { return NEW_VIEW; } return NewEditorHelper.newEditorLabel(baseName + " - " + NEW_VIEW); } public ViewDocument getViewDocument() { return viewInfo; } public void setInitialLayout(LayoutPlan initialLayout) { this.initialLayout = initialLayout; } public LayoutPlan getInitialLayout() { return initialLayout; } @Override public boolean equals(Object compare) { // ViewEditorInputs only match themselves, never other entities, // even if the content is the same. return this == compare; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean exists() { return false; } @Override public ImageDescriptor getImageDescriptor() { return ViewDocResources.IMAGE_DESC_VIEWDOC; } @Override public String getName() { if (null == displayName) { displayName = calcDisplayName(); } return displayName; } @Override public IPersistableElement getPersistable() { return null; } @Override public String getToolTipText() { // Any distinction provided by NewEditorHelper in // calcDisplayName() return getName(); } @Override // warning suppressed because Class should be parameterized. however the // implemented method doesn't use parameter here. @SuppressWarnings({ "rawtypes", "unchecked" }) public Object getAdapter(Class adapter) { return null; } }
25.048387
80
0.724082
e98bb96bbed4fa5c73f4f749f3bca5f3242f3898
2,230
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package emit.ipcv.engines.interfaces; /** * * @author rinelfi */ public abstract class NonLinearLocalTransformation { protected int[][] image; protected abstract int[][] execute(); protected int changeLineAxis(int line, float[][] image) { float lineCenter = (image.length - 1) / 2.0f; float axe = (float) line - lineCenter; return (int) (axe <= 0 ? Math.floor(axe) : Math.ceil(axe)); } protected int changeLineAxis(int line, int[][] image) { float lineCenter = (float) (image.length - 1) / 2.0f; float axe = (float) line - lineCenter; return (int) (axe <= 0 ? Math.floor(axe) : Math.ceil(axe)); } protected int changeColumnAxis(int column, float[][] image) { float columnCenter = (image[0].length - 1) / 2.0f; float axe = (float) column - columnCenter; return (int) (axe <= 0 ? Math.floor(axe) : Math.ceil(axe)); } protected int changeColumnAxis(int column, int[][] image) { float columnCenter = (float) (image[0].length - 1) / 2.0f; float axe = (float) column - columnCenter; return (int) (axe <= 0 ? Math.floor(axe) : Math.ceil(axe)); } protected int retablirAxeX(int line, float[][] image) { float centreLigne = (image.length - 1) / 2.0f; float axe = (float) line + centreLigne; return (int) (line <= 0 ? Math.ceil(axe) : Math.floor(axe)); } protected int retablirAxeX(int line, int[][] image) { float centreLigne = (float) (image.length - 1) / 2.0f; float axe = (float) line + centreLigne; return (int) (line <= 0 ? Math.ceil(axe) : Math.floor(axe)); } protected int retablirAxeY(int column, float[][] image) { float columnCenter = (image[0].length - 1) / 2.0f; float axe = (float) column + columnCenter; return (int) (column <= 0 ? Math.ceil(axe) : Math.floor(axe)); } protected int retablirAxeY(int column, int[][] image) { float columnCenter = (float) (image[0].length - 1) / 2.0f; float axe = (float) column + columnCenter; return (int) (column <= 0 ? Math.ceil(axe) : Math.floor(axe)); } }
33.787879
79
0.635426
93189dc220c282d01b16345007288cd5d470de24
761
package ticTacToe; import java.util.Random; import java.util.function.Predicate; /** * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) */ public class RandomPlayer implements Player { private final Random random; public RandomPlayer(final Random random) { this.random = random; } public RandomPlayer() { this(new Random()); } @Override public Move move(int rows, int columns, Cell cell, String boardString, Predicate<Move> isValid) { while (true) { int r = random.nextInt(rows); int c = random.nextInt(columns); final Move move = new Move(r, c, cell); if (isValid.test(move)) { return move; } } } }
22.382353
101
0.582129
43df5bfce26366552838c96b508a6be146baf0bc
3,891
package de.httptandooripalace.restaurantorderprinter; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONArray; import org.json.JSONObject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import Adapters.HistoryAdapter; import cz.msebera.android.httpclient.Header; import entities.Bill; import entities.Product; import helpers.DatabaseHelper; import helpers.RequestClient; /** * Created by uiz on 30/05/2017. */ public class HistoryActivity extends BaseActivity { private entities.Settings settings; public static List<Bill> bills = new ArrayList<>(); public List<Product> products = new ArrayList<>(); Context context; int id =0; String boolstr = null; boolean is_open = true; String datestr = null; SimpleDateFormat sdf = null; Date date = null; String table_nr = null; JSONArray jsonarray = null; JSONObject jsonobject = null; String waiter_name = ""; Double total_price_excl = 0.0; FloatingActionButton prin; HistoryAdapter adapter = null; private RecyclerView recyclerView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.history); setContentView(R.layout.history_activity); recyclerView = (RecyclerView) findViewById(R.id.list_closed_bills); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.action_settings: Intent i = new Intent(this, SettingsActivity.class); startActivity(i); onBackPressed(); return true; case R.id.bills_overview: Intent i2 = new Intent(this, OverviewActivity.class); startActivity(i2); return true; case R.id.bills_history: Intent i3 = new Intent(this, HistoryActivity.class); startActivity(i3); return true; case R.id.filter: Intent i4 = new Intent(this, FilterActivity.class); startActivity(i4); return true; } return super.onOptionsItemSelected(item); } private void loadData() { RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); adapter = new HistoryAdapter(context, bills); recyclerView.setAdapter(adapter); hideLoading(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_history, menu); return true; } @Override protected void onPause() { super.onPause(); } private void refreshContent() { finish(); startActivity(getIntent()); } public void new_bill(View view){ Intent i = new Intent(this, MainActivity.class); startActivity(i); } public void print_history(View view){ //TODO : access the good table nr Intent i = new Intent(this, PrintHistoryActivity.class); startActivity(i); } }
29.255639
82
0.675148
878036dee3cb3cd55a2874c0bd81313d82364bfa
1,469
/* * Copyright Siemens AG, 2014-2015. Part of the SW360 Portal Project. * * SPDX-License-Identifier: EPL-1.0 * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.sw360.datahandler.couchdb; import org.eclipse.sw360.datahandler.common.Duration; import org.eclipse.sw360.datahandler.thrift.attachments.AttachmentContent; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; /** * @author daniele.fognini@tngtech.com */ public class AttachmentContentDownloader { /** * download an incomplete AttachmentContent from its URL * * @todo setup DI and move timeout to a member */ public InputStream download(AttachmentContent attachmentContent, Duration timeout) throws IOException { int millisTimeout = ((Number) timeout.toMillis()).intValue(); URL remoteURL = new URL(attachmentContent.getRemoteUrl()); URLConnection urlConnection = remoteURL.openConnection(); urlConnection.setConnectTimeout(millisTimeout); urlConnection.setReadTimeout(millisTimeout); InputStream downloadStream = urlConnection.getInputStream(); return new BufferedInputStream(downloadStream); } }
33.386364
107
0.748809
b037dedbad456d66427f45bea78ee0b2f968e321
93
package com.moesrc.socketio; public interface AckRequest { void send(Object... args); }
15.5
30
0.72043
52ed45b9d944b37a2d77f37735efd36d2f6c6eab
2,289
package com.timeline.api.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.timeline.api.entity.CommentEntity; import com.timeline.api.entity.UserEntity; import com.timeline.api.forresponse.CommentResponse; import com.timeline.api.graphEntity.HttpFactory; import com.timeline.api.repository.CommentRepository; import com.timeline.api.repository.UserRepository; @Service public class CommentServiceImpl implements CommentService{ @Autowired HttpFactory factory; @Autowired CommentRepository commentRepository; @Autowired UserRepository userRepository; /* * 필요한 정보들 : * 댓글id, 소식id, 유저id, 유저이름, 유저프로필사진, 댓글 본문, 작성 시간 * 이 정보들을 각각 수집해서 조합해준다 */ private CommentResponse formattingComment(CommentEntity comment) { UserEntity user = userRepository.findById(comment.getUserID()); CommentResponse responseElement = new CommentResponse() .setCommentID(comment.getId()) .setArticleID(comment.getArticleID()) .setUserID(user.getId()) .setUsername(user.getUsername()) .setProfile(user.getProfile()) .setContent(comment.getContent()) .setCreatedtime(comment.getCreatedtime()); return responseElement; } @Override public CommentResponse insertComment(CommentEntity commentEntity) { commentEntity.setCreatedtime(factory.getTimeStamp()); CommentEntity comment = commentRepository.save(commentEntity); return formattingComment(comment); } @Override public CommentResponse[] findByArticleID(long articleID) { //해당 소식에 달려있는 모든 댓글들을 리스트로 가져온다 List<CommentEntity> commentList = commentRepository.findByArticleID(articleID); //해당 댓글의 개수를 가져와서 뷰에서 필요한 정보들의 클래스인 commentResponse 배열의 개수로 지정해준다 int length = commentList.size(); //각 댓글들을 뷰에서 필요한 정보들로 조합해준다 CommentResponse[] formmedCommentList = new CommentResponse[length]; for (int i=0 ; i<length ; i++) { CommentEntity comment = commentList.get(i); formmedCommentList[i] = formattingComment(comment); } return formmedCommentList; } @Override public void deleteAllComments(long articleID) { commentRepository.deleteByArticleID(articleID); } @Override public void deleteComment(long commentID) { commentRepository.deleteById(commentID); } }
28.6125
81
0.773263
5275547be48fda357555dc0517495d47a69999b1
5,252
package io.mateu.erp.model.invoicing; import io.mateu.erp.model.authentication.ERPUser; import io.mateu.erp.model.config.AppConfig; import io.mateu.erp.model.partners.Agency; import io.mateu.mdd.core.MDD; import io.mateu.mdd.core.annotations.IFrame; import io.mateu.mdd.core.annotations.Ignored; import io.mateu.mdd.core.interfaces.WizardPage; import io.mateu.mdd.core.model.authentication.User; import io.mateu.mdd.core.util.Helper; import io.mateu.mdd.vaadinport.vaadin.MDDUI; import lombok.Getter; import lombok.Setter; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import javax.persistence.EntityManager; import javax.xml.transform.stream.StreamSource; import java.io.File; import java.io.FileOutputStream; import java.io.StringReader; import java.net.URL; import java.util.*; import java.util.stream.Collectors; @Getter@Setter public class IssueInvoicesShowProformaPage implements WizardPage { @Ignored private final IssueInvoicesParametersPage issueInvoicesParametersPage; @IFrame private URL proforma; public IssueInvoicesShowProformaPage(IssueInvoicesParametersPage issueInvoicesParametersPage) throws Throwable { this.issueInvoicesParametersPage = issueInvoicesParametersPage; Helper.notransact(em -> { Map<Agency, List<BookingCharge>> chargesByPartner = split(em, issueInvoicesParametersPage.getPending()); Document xml = new Document(new Element("invoices")); User u = MDD.getCurrentUser(); chargesByPartner.keySet().forEach(p -> { try { xml.getRootElement().addContent(new IssuedInvoice(u, chargesByPartner.get(p), true, p.getCompany().getFinancialAgent(), p.getFinancialAgent(), null).toXml(em)); } catch (Throwable throwable) { MDD.alert(throwable); } }); System.out.println(Helper.toString(xml.getRootElement())); String archivo = UUID.randomUUID().toString(); File temp = (System.getProperty("tmpdir") == null) ? File.createTempFile(archivo, ".pdf") : new File(new File(System.getProperty("tmpdir")), archivo + ".pdf"); System.out.println("java.io.tmpdir=" + System.getProperty("java.io.tmpdir")); System.out.println("Temp file : " + temp.getAbsolutePath()); FileOutputStream fileOut = new FileOutputStream(temp); //String sxslfo = Resources.toString(Resources.getResource(Contract.class, xslfo), Charsets.UTF_8); String sxml = new XMLOutputter(Format.getPrettyFormat()).outputString(xml); System.out.println("xml=" + sxml); fileOut.write(Helper.fop(new StreamSource(new StringReader(AppConfig.get(em).getXslfoForIssuedInvoice())), new StreamSource(new StringReader(sxml)))); fileOut.close(); String baseUrl = System.getProperty("tmpurl"); if (baseUrl == null) { proforma = temp.toURI().toURL(); } proforma = new URL(baseUrl + "/" + temp.getName()); }); } @Override public String toString() { return "Proforma"; } @Override public WizardPage getPrevious() { return issueInvoicesParametersPage; } @Override public boolean hasNext() { return false; } @Override public WizardPage getNext() { return null; } @Override public void onOk() throws Throwable { Helper.transact(em -> { Map<Agency, List<BookingCharge>> chargesByPartner = split(em, issueInvoicesParametersPage.getPending()); chargesByPartner.keySet().forEach(p -> { Invoice i = null; try { i = new IssuedInvoice(em.find(ERPUser.class, MDD.getUserData().getLogin()), chargesByPartner.get(p), false, p.getCompany().getFinancialAgent(), p.getFinancialAgent(), null); em.persist(i); chargesByPartner.get(p).forEach(c -> em.merge(c)); } catch (Throwable throwable) { MDD.alert(throwable); } }); chargesByPartner.values().forEach(l -> { }); }); MDDUI.get().getNavegador().goBack(); } private Map<Agency,List<BookingCharge>> split(EntityManager em, Set<IssueInvoicesItem> pending) { Map<Agency, List<BookingCharge>> chargesByPartner = new HashMap<>(); Set<Agency> partners = issueInvoicesParametersPage.getPending().stream().map(i -> i.getAgency()).collect(Collectors.toSet()); for (BookingCharge c : (List<BookingCharge>) em.createQuery("select x from " + BookingCharge.class.getName() + " x where x.invoice = null and x.agency in :ps").setParameter("ps", partners).getResultList()) { Agency p = c.getBooking().getAgency(); List<BookingCharge> charges = chargesByPartner.get(p); if (charges == null) { chargesByPartner.put(p, charges = new ArrayList<>()); } charges.add(c); } return chargesByPartner; } }
32.825
215
0.637852
59e9713d22ab865fb17f45bcfd33148160f6c5e6
1,654
/* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.ibm.sbt.jslibrary; import java.util.List; import com.ibm.commons.runtime.Application; import com.ibm.commons.runtime.Context; /** * SBT Environment Factory. * * @author Philippe Riand */ public abstract class SBTEnvironmentFactory { public static final String ENVIRONMENT_FACTORY = "com.ibm.sbt.core.environmentfactory"; /** * Get an environment by its name. * @param name * @return the corresponding environment, or null if not found */ public static SBTEnvironment get(String name) { Application app = Application.getUnchecked(); if (app != null) { List<Object> factories = app.findServices(ENVIRONMENT_FACTORY); for(int i=0; i<factories.size(); i++) { SBTEnvironmentFactory factory = (SBTEnvironmentFactory)factories.get(i); SBTEnvironment env = factory.getEnvironment(name); if(env!=null) { return env; } } } return null; } /** * Get the a environment from its name. * * @param name * @return */ public abstract SBTEnvironment getEnvironment(String name); }
26.677419
88
0.709794
c83139e9d68eee2dea71d95ea1677e5214d6ff86
11,347
// Copyright 2015 The Vanadium Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package io.v.v23.vdl; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Type represents VDL types. */ public final class VdlType implements Serializable { private static final long serialVersionUID = 1L; private Kind kind; // used by all kinds private String name; // used by all kinds private ImmutableList<String> labels; // used by enum private int length; // used by array private VdlType key; // used by set, map private VdlType elem; // used by array, list, map, optional private ImmutableList<VdlField> fields; // used by struct and union private String typeString; // used by all kinds, filled in by getUniqueType /** * Stores a mapping from type string to VDL type instance. This is used to make sure that * vdlTypeA.typeString == vdlTypeB.typeString => vdlTypeA == vdlTypeB. */ private static final Map<String, VdlType> uniqueTypes = new ConcurrentHashMap<String, VdlType>(); /** * Generated a type string representing type, which also is its human-readable representation. * To break loops we cache named types only, as you can't define an unnamed cyclic type in VDL. * We also ensure that there is at most one VDL type instance for each name. These two * assumptions make VDL type graph isomorphism check based on type strings straightforward. */ private static String typeString(VdlType type, final Map<String, VdlType> seen) { if (!Strings.isNullOrEmpty(type.name)) { VdlType seenType = seen.get(type.name); if (seenType != null) { if (seenType != type) { throw new IllegalArgumentException("Duplicate type name " + type.name); } return type.name; } seen.put(type.name, type); } String result = ""; if (!Strings.isNullOrEmpty(type.name)) { result = type.name + " "; } switch (type.kind) { case ENUM: return result + "enum{" + Joiner.on(";").join(type.labels) + "}"; case ARRAY: return result + "[" + type.length + "]" + typeString(type.elem, seen); case LIST: return result + "[]" + typeString(type.elem, seen); case SET: return result + "set[" + typeString(type.key, seen) + "]"; case MAP: return result + "map[" + typeString(type.key, seen) + "]" + typeString(type.elem, seen); case STRUCT: case UNION: if (type.kind == Kind.STRUCT) { result += "struct{"; } else { result += "union{"; } for (int i = 0; i < type.fields.size(); i++) { if (i > 0) { result += ";"; } VdlField field = type.fields.get(i); result += field.getName() + " " + typeString(field.getType(), seen); } return result + "}"; case OPTIONAL: return result + "?" + typeString(type.elem, seen); default: return result + type.kind.name().toLowerCase(); } } private Object readResolve() { return getUniqueType(this); } private static synchronized VdlType getUniqueType(VdlType type) { if (type == null) { return null; } if (type.typeString == null) { type.typeString = typeString(type, new HashMap<String, VdlType>()); } VdlType uniqueType = uniqueTypes.get(type.typeString); if (uniqueType != null) { return uniqueType; } uniqueTypes.put(type.typeString, type); type.key = getUniqueType(type.key); type.elem = getUniqueType(type.elem); if (type.fields != null) { ImmutableList.Builder<VdlField> builder = new ImmutableList.Builder<VdlField>(); for (VdlField field : type.fields) { builder.add(new VdlField(field.getName(), getUniqueType(field.getType()))); } type.fields = builder.build(); } return type; } private VdlType() {} public Kind getKind() { return kind; } public String getName() { return name; } public List<String> getLabels() { return labels; } public int getLength() { return length; } public VdlType getKey() { return key; } public VdlType getElem() { return elem; } public List<VdlField> getFields() { return fields; } @Override public String toString() { return typeString; } /** * Builder builds Types. There are two phases: 1) Create PendingType objects and describe each * type, and 2) call build(). When build() is called, all types are created and may be retrieved * by calling built() on the pending type. This two-phase building enables support for recursive * types, and also makes it easy to construct a group of dependent types without determining * their dependency ordering. */ public static final class Builder { private final List<PendingType> pendingTypes; public Builder() { pendingTypes = new ArrayList<PendingType>(); } public PendingType newPending() { PendingType type = new PendingType(); pendingTypes.add(type); return type; } public PendingType newPending(Kind kind) { return newPending().setKind(kind); } public PendingType listOf(PendingType elem) { return newPending(Kind.LIST).setElem(elem); } public PendingType setOf(PendingType key) { return newPending(Kind.SET).setKey(key); } public PendingType mapOf(PendingType key, PendingType elem) { return newPending(Kind.MAP).setKey(key).setElem(elem); } public PendingType optionalOf(PendingType elem) { return newPending(Kind.OPTIONAL).setElem(elem); } public PendingType builtPendingFromType(VdlType vdlType) { return new PendingType(vdlType); } public void build() { for (PendingType type : pendingTypes) { type.prepare(); } for (PendingType type : pendingTypes) { type.build(); } pendingTypes.clear(); } } public static final class PendingType { private VdlType vdlType; private final List<String> labels; private final List<VdlField> fields; private boolean built; private PendingType(VdlType vdlType) { this.vdlType = vdlType; labels = null; fields = null; built = true; } private PendingType() { vdlType = new VdlType(); labels = new ArrayList<String>(); fields = new ArrayList<VdlField>(); built = false; } private void prepare() { if (built) { return; } switch (vdlType.kind) { case ENUM: vdlType.labels = ImmutableList.copyOf(labels); break; case STRUCT: case UNION: vdlType.fields = ImmutableList.copyOf(fields); break; default: // do nothing } } private void build() { if (built) { return; } vdlType = getUniqueType(vdlType); built = true; } public PendingType setKind(Kind kind) { assertNotBuilt(); vdlType.kind = kind; return this; } public PendingType setName(String name) { assertNotBuilt(); vdlType.name = name; return this; } public PendingType addLabel(String label) { assertNotBuilt(); assertOneOfKind(Kind.ENUM); labels.add(label); return this; } public PendingType setLength(int length) { assertNotBuilt(); assertOneOfKind(Kind.ARRAY); vdlType.length = length; return this; } public PendingType setKey(VdlType key) { assertNotBuilt(); assertOneOfKind(Kind.SET, Kind.MAP); vdlType.key = key; return this; } public PendingType setKey(PendingType key) { return setKey(key.vdlType); } public PendingType setElem(VdlType elem) { assertNotBuilt(); assertOneOfKind(Kind.ARRAY, Kind.LIST, Kind.MAP, Kind.OPTIONAL); vdlType.elem = elem; return this; } public PendingType setElem(PendingType elem) { return setElem(elem.vdlType); } public PendingType addField(String name, VdlType type) { assertNotBuilt(); assertOneOfKind(Kind.STRUCT, Kind.UNION); fields.add(new VdlField(name, type)); return this; } public PendingType addField(String name, PendingType type) { return addField(name, type.vdlType); } public PendingType assignBase(VdlType type) { assertNotBuilt(); this.vdlType.kind = type.kind; this.vdlType.length = type.length; this.vdlType.key = type.key; this.vdlType.elem = type.elem; labels.clear(); if (type.labels != null) { labels.addAll(type.labels); } fields.clear(); if (type.fields != null) { fields.addAll(type.fields); } return this; } public PendingType assignBase(PendingType pending) { return assignBase(pending.vdlType); } public VdlType built() { if (!built) { throw new IllegalStateException("The pending type is not built yet"); } return vdlType; } private void assertNotBuilt() { if (built) { throw new IllegalStateException("The pending type is already built"); } } private void assertOneOfKind(Kind... kinds) { for (Kind kind : kinds) { if (vdlType.kind == kind) { return; } } throw new IllegalArgumentException("Unsupported operation for kind " + vdlType.kind); } } }
31.432133
100
0.542787
9dc1ac5562fdc3ddc348787a056bc70b157bcd5c
1,794
/* * Copyright 2000-2013 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.siyeh.ipp.asserttoif; import com.intellij.java.codeInspection.DataFlowInspectionTest; import com.intellij.testFramework.LightProjectDescriptor; import com.siyeh.IntentionPowerPackBundle; import com.siyeh.ipp.IPPTestCase; import org.jetbrains.annotations.NotNull; /** * @see com.siyeh.ipp.asserttoif.ObjectsRequireNonNullIntention * @author Bas Leijdekkers */ public class ObjectsRequireNonNullIntentionTest extends IPPTestCase { @NotNull @Override protected LightProjectDescriptor getProjectDescriptor() { return JAVA_8; } @Override protected void setUp() throws Exception { super.setUp(); DataFlowInspectionTest.addJavaxNullabilityAnnotations(myFixture); DataFlowInspectionTest.addJavaxDefaultNullabilityAnnotations(myFixture); } public void testOne() { doTest(); } public void testTwo() { doTest(); } public void testThree() { doTest(); } public void testContainer() { doTest(); } @Override protected String getRelativePath() { return "asserttoif/objects_require_non_null"; } @Override protected String getIntentionName() { return IntentionPowerPackBundle.message("objects.require.non.null.intention.name"); } }
31.473684
87
0.761984
11696639f5d1aef25d2e9df6dc22cb3a50f9a84d
2,011
package com.newsapp.android.ViewPageTitle; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; import com.newsapp.android.NewsAdapter; import com.newsapp.android.R; import com.newsapp.android.gson.Data; import com.newsapp.android.gson.News; import java.util.ArrayList; import java.util.List; import static com.newsapp.android.ViewPageTitle.TabAdapter.TITLES; @SuppressLint("ValidFragment") public class MainFragment extends Fragment { private int newsType= 0 ; private int currentPage = 1; private ListView lvNews; private NewsAdapter adapter; private List<Data> dataList; public MainFragment() { /* this.category = category;*/ } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); /* lvNews = (ListView) getView().findViewById(R.id.lvNews); adapter = new NewsAdapter(getActivity(), dataList); lvNews.setAdapter(adapter);*/ /*mAdapter = new NewsAdapter(getActivity(),mDatas); mListView = (ListView) getView().findViewById(R.id.lvNews); mListView.setAdapter(mAdapter);*/ } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.news_item,null ); /* ListView lvNews = (ListView) view.findViewById(R.id.lvNews); lvNews = (ListView) view.findViewById(R.id.lvNews); Bundle mBundle = getArguments(); String title = mBundle.getString("arg");*/ return view; } }
30.938462
132
0.73098
71cbf0a2e85038843c4861439f5ba988f7dba65d
61,371
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.v7.view; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.*; import android.support.v4.internal.view.SupportMenu; import android.support.v4.view.ActionProvider; import android.support.v4.view.MenuItemCompat; import android.support.v7.view.menu.MenuItemImpl; import android.support.v7.view.menu.MenuItemWrapperICS; import android.util.*; import android.view.*; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; public class SupportMenuInflater extends MenuInflater { static class InflatedOnMenuItemClickListener implements android.view.MenuItem.OnMenuItemClickListener { public boolean onMenuItemClick(MenuItem menuitem) { boolean flag; if(mMethod.getReturnType() != Boolean.TYPE) break MISSING_BLOCK_LABEL_41; // 0 0:aload_0 // 1 1:getfield #43 <Field Method mMethod> // 2 4:invokevirtual #77 <Method Class Method.getReturnType()> // 3 7:getstatic #83 <Field Class Boolean.TYPE> // 4 10:if_acmpne 41 flag = ((Boolean)mMethod.invoke(mRealOwner, new Object[] { menuitem })).booleanValue(); // 5 13:aload_0 // 6 14:getfield #43 <Field Method mMethod> // 7 17:aload_0 // 8 18:getfield #33 <Field Object mRealOwner> // 9 21:iconst_1 // 10 22:anewarray Object[] // 11 25:dup // 12 26:iconst_0 // 13 27:aload_1 // 14 28:aastore // 15 29:invokevirtual #87 <Method Object Method.invoke(Object, Object[])> // 16 32:checkcast #79 <Class Boolean> // 17 35:invokevirtual #91 <Method boolean Boolean.booleanValue()> // 18 38:istore_2 return flag; // 19 39:iload_2 // 20 40:ireturn try { mMethod.invoke(mRealOwner, new Object[] { menuitem }); // 21 41:aload_0 // 22 42:getfield #43 <Field Method mMethod> // 23 45:aload_0 // 24 46:getfield #33 <Field Object mRealOwner> // 25 49:iconst_1 // 26 50:anewarray Object[] // 27 53:dup // 28 54:iconst_0 // 29 55:aload_1 // 30 56:aastore // 31 57:invokevirtual #87 <Method Object Method.invoke(Object, Object[])> // 32 60:pop } //* 33 61:iconst_1 //* 34 62:ireturn // Misplaced declaration of an exception variable catch(MenuItem menuitem) //* 35 63:astore_1 { throw new RuntimeException(((Throwable) (menuitem))); // 36 64:new #93 <Class RuntimeException> // 37 67:dup // 38 68:aload_1 // 39 69:invokespecial #96 <Method void RuntimeException(Throwable)> // 40 72:athrow } return true; } private static final Class PARAM_TYPES[] = { android/view/MenuItem }; private Method mMethod; private Object mRealOwner; static { // 0 0:iconst_1 // 1 1:anewarray Class[] // 2 4:dup // 3 5:iconst_0 // 4 6:ldc1 #22 <Class MenuItem> // 5 8:aastore // 6 9:putstatic #24 <Field Class[] PARAM_TYPES> //* 7 12:return } public InflatedOnMenuItemClickListener(Object obj, String s) { // 0 0:aload_0 // 1 1:invokespecial #31 <Method void Object()> mRealOwner = obj; // 2 4:aload_0 // 3 5:aload_1 // 4 6:putfield #33 <Field Object mRealOwner> Class class1 = obj.getClass(); // 5 9:aload_1 // 6 10:invokevirtual #37 <Method Class Object.getClass()> // 7 13:astore_3 try { mMethod = class1.getMethod(s, PARAM_TYPES); // 8 14:aload_0 // 9 15:aload_3 // 10 16:aload_2 // 11 17:getstatic #24 <Field Class[] PARAM_TYPES> // 12 20:invokevirtual #41 <Method Method Class.getMethod(String, Class[])> // 13 23:putfield #43 <Field Method mMethod> return; // 14 26:return } // Misplaced declaration of an exception variable catch(Object obj) //* 15 27:astore_1 { s = ((String) (new InflateException((new StringBuilder()).append("Couldn't resolve menu item onClick handler ").append(s).append(" in class ").append(class1.getName()).toString()))); // 16 28:new #45 <Class InflateException> // 17 31:dup // 18 32:new #47 <Class StringBuilder> // 19 35:dup // 20 36:invokespecial #48 <Method void StringBuilder()> // 21 39:ldc1 #50 <String "Couldn't resolve menu item onClick handler "> // 22 41:invokevirtual #54 <Method StringBuilder StringBuilder.append(String)> // 23 44:aload_2 // 24 45:invokevirtual #54 <Method StringBuilder StringBuilder.append(String)> // 25 48:ldc1 #56 <String " in class "> // 26 50:invokevirtual #54 <Method StringBuilder StringBuilder.append(String)> // 27 53:aload_3 // 28 54:invokevirtual #60 <Method String Class.getName()> // 29 57:invokevirtual #54 <Method StringBuilder StringBuilder.append(String)> // 30 60:invokevirtual #63 <Method String StringBuilder.toString()> // 31 63:invokespecial #66 <Method void InflateException(String)> // 32 66:astore_2 } ((InflateException) (s)).initCause(((Throwable) (obj))); // 33 67:aload_2 // 34 68:aload_1 // 35 69:invokevirtual #70 <Method Throwable InflateException.initCause(Throwable)> // 36 72:pop throw s; // 37 73:aload_2 // 38 74:athrow } } class MenuState { private char getShortcut(String s) { if(s == null) //* 0 0:aload_1 //* 1 1:ifnonnull 6 return '\0'; // 2 4:iconst_0 // 3 5:ireturn else return s.charAt(0); // 4 6:aload_1 // 5 7:iconst_0 // 6 8:invokevirtual #74 <Method char String.charAt(int)> // 7 11:ireturn } private Object newInstance(String s, Class aclass[], Object aobj[]) { try { aclass = ((Class []) (mContext.getClassLoader().loadClass(s).getConstructor(aclass))); // 0 0:aload_0 // 1 1:getfield #57 <Field SupportMenuInflater this$0> // 2 4:getfield #82 <Field Context SupportMenuInflater.mContext> // 3 7:invokevirtual #88 <Method ClassLoader Context.getClassLoader()> // 4 10:aload_1 // 5 11:invokevirtual #94 <Method Class ClassLoader.loadClass(String)> // 6 14:aload_2 // 7 15:invokevirtual #100 <Method Constructor Class.getConstructor(Class[])> // 8 18:astore_2 ((Constructor) (aclass)).setAccessible(true); // 9 19:aload_2 // 10 20:iconst_1 // 11 21:invokevirtual #106 <Method void Constructor.setAccessible(boolean)> aclass = ((Class []) (((Constructor) (aclass)).newInstance(aobj))); // 12 24:aload_2 // 13 25:aload_3 // 14 26:invokevirtual #109 <Method Object Constructor.newInstance(Object[])> // 15 29:astore_2 } //* 16 30:aload_2 //* 17 31:areturn // Misplaced declaration of an exception variable catch(Class aclass[]) //* 18 32:astore_2 { Log.w("SupportMenuInflater", (new StringBuilder()).append("Cannot instantiate class: ").append(s).toString(), ((Throwable) (aclass))); // 19 33:ldc1 #111 <String "SupportMenuInflater"> // 20 35:new #113 <Class StringBuilder> // 21 38:dup // 22 39:invokespecial #114 <Method void StringBuilder()> // 23 42:ldc1 #116 <String "Cannot instantiate class: "> // 24 44:invokevirtual #120 <Method StringBuilder StringBuilder.append(String)> // 25 47:aload_1 // 26 48:invokevirtual #120 <Method StringBuilder StringBuilder.append(String)> // 27 51:invokevirtual #124 <Method String StringBuilder.toString()> // 28 54:aload_2 // 29 55:invokestatic #130 <Method int Log.w(String, String, Throwable)> // 30 58:pop return ((Object) (null)); // 31 59:aconst_null // 32 60:areturn } return ((Object) (aclass)); } private void setItem(MenuItem menuitem) { Object obj = ((Object) (menuitem.setChecked(itemChecked).setVisible(itemVisible).setEnabled(itemEnabled))); // 0 0:aload_1 // 1 1:aload_0 // 2 2:getfield #136 <Field boolean itemChecked> // 3 5:invokeinterface #142 <Method MenuItem MenuItem.setChecked(boolean)> // 4 10:aload_0 // 5 11:getfield #144 <Field boolean itemVisible> // 6 14:invokeinterface #147 <Method MenuItem MenuItem.setVisible(boolean)> // 7 19:aload_0 // 8 20:getfield #149 <Field boolean itemEnabled> // 9 23:invokeinterface #152 <Method MenuItem MenuItem.setEnabled(boolean)> // 10 28:astore 4 boolean flag1; if(itemCheckable >= 1) //* 11 30:aload_0 //* 12 31:getfield #154 <Field int itemCheckable> //* 13 34:iconst_1 //* 14 35:icmplt 43 flag1 = true; // 15 38:iconst_1 // 16 39:istore_3 else //* 17 40:goto 45 flag1 = false; // 18 43:iconst_0 // 19 44:istore_3 ((MenuItem) (obj)).setCheckable(flag1).setTitleCondensed(itemTitleCondensed).setIcon(itemIconResId).setAlphabeticShortcut(itemAlphabeticShortcut).setNumericShortcut(itemNumericShortcut); // 20 45:aload 4 // 21 47:iload_3 // 22 48:invokeinterface #157 <Method MenuItem MenuItem.setCheckable(boolean)> // 23 53:aload_0 // 24 54:getfield #159 <Field CharSequence itemTitleCondensed> // 25 57:invokeinterface #163 <Method MenuItem MenuItem.setTitleCondensed(CharSequence)> // 26 62:aload_0 // 27 63:getfield #165 <Field int itemIconResId> // 28 66:invokeinterface #169 <Method MenuItem MenuItem.setIcon(int)> // 29 71:aload_0 // 30 72:getfield #171 <Field char itemAlphabeticShortcut> // 31 75:invokeinterface #175 <Method MenuItem MenuItem.setAlphabeticShortcut(char)> // 32 80:aload_0 // 33 81:getfield #177 <Field char itemNumericShortcut> // 34 84:invokeinterface #180 <Method MenuItem MenuItem.setNumericShortcut(char)> // 35 89:pop if(itemShowAsAction >= 0) //* 36 90:aload_0 //* 37 91:getfield #182 <Field int itemShowAsAction> //* 38 94:iflt 107 menuitem.setShowAsAction(itemShowAsAction); // 39 97:aload_1 // 40 98:aload_0 // 41 99:getfield #182 <Field int itemShowAsAction> // 42 102:invokeinterface #186 <Method void MenuItem.setShowAsAction(int)> if(itemListenerMethodName != null) //* 43 107:aload_0 //* 44 108:getfield #188 <Field String itemListenerMethodName> //* 45 111:ifnull 162 { if(mContext.isRestricted()) //* 46 114:aload_0 //* 47 115:getfield #57 <Field SupportMenuInflater this$0> //* 48 118:getfield #82 <Field Context SupportMenuInflater.mContext> //* 49 121:invokevirtual #192 <Method boolean Context.isRestricted()> //* 50 124:ifeq 137 throw new IllegalStateException("The android:onClick attribute cannot be used within a restricted context"); // 51 127:new #194 <Class IllegalStateException> // 52 130:dup // 53 131:ldc1 #196 <String "The android:onClick attribute cannot be used within a restricted context"> // 54 133:invokespecial #199 <Method void IllegalStateException(String)> // 55 136:athrow menuitem.setOnMenuItemClickListener(((android.view.MenuItem.OnMenuItemClickListener) (new InflatedOnMenuItemClickListener(getRealOwner(), itemListenerMethodName)))); // 56 137:aload_1 // 57 138:new #201 <Class SupportMenuInflater$InflatedOnMenuItemClickListener> // 58 141:dup // 59 142:aload_0 // 60 143:getfield #57 <Field SupportMenuInflater this$0> // 61 146:invokevirtual #205 <Method Object SupportMenuInflater.getRealOwner()> // 62 149:aload_0 // 63 150:getfield #188 <Field String itemListenerMethodName> // 64 153:invokespecial #208 <Method void SupportMenuInflater$InflatedOnMenuItemClickListener(Object, String)> // 65 156:invokeinterface #212 <Method MenuItem MenuItem.setOnMenuItemClickListener(android.view.MenuItem$OnMenuItemClickListener)> // 66 161:pop } if(menuitem instanceof MenuItemImpl) //* 67 162:aload_1 //* 68 163:instanceof #214 <Class MenuItemImpl> //* 69 166:ifeq 178 obj = ((Object) ((MenuItemImpl)menuitem)); // 70 169:aload_1 // 71 170:checkcast #214 <Class MenuItemImpl> // 72 173:astore 4 //* 73 175:goto 178 if(itemCheckable >= 2) //* 74 178:aload_0 //* 75 179:getfield #154 <Field int itemCheckable> //* 76 182:iconst_2 //* 77 183:icmplt 219 if(menuitem instanceof MenuItemImpl) //* 78 186:aload_1 //* 79 187:instanceof #214 <Class MenuItemImpl> //* 80 190:ifeq 204 ((MenuItemImpl)menuitem).setExclusiveCheckable(true); // 81 193:aload_1 // 82 194:checkcast #214 <Class MenuItemImpl> // 83 197:iconst_1 // 84 198:invokevirtual #217 <Method void MenuItemImpl.setExclusiveCheckable(boolean)> else //* 85 201:goto 219 if(menuitem instanceof MenuItemWrapperICS) //* 86 204:aload_1 //* 87 205:instanceof #219 <Class MenuItemWrapperICS> //* 88 208:ifeq 219 ((MenuItemWrapperICS)menuitem).setExclusiveCheckable(true); // 89 211:aload_1 // 90 212:checkcast #219 <Class MenuItemWrapperICS> // 91 215:iconst_1 // 92 216:invokevirtual #220 <Method void MenuItemWrapperICS.setExclusiveCheckable(boolean)> boolean flag = false; // 93 219:iconst_0 // 94 220:istore_2 if(itemActionViewClassName != null) //* 95 221:aload_0 //* 96 222:getfield #222 <Field String itemActionViewClassName> //* 97 225:ifnull 258 { menuitem.setActionView((View)newInstance(itemActionViewClassName, SupportMenuInflater.ACTION_VIEW_CONSTRUCTOR_SIGNATURE, mActionViewConstructorArguments)); // 98 228:aload_1 // 99 229:aload_0 // 100 230:aload_0 // 101 231:getfield #222 <Field String itemActionViewClassName> // 102 234:getstatic #226 <Field Class[] SupportMenuInflater.ACTION_VIEW_CONSTRUCTOR_SIGNATURE> // 103 237:aload_0 // 104 238:getfield #57 <Field SupportMenuInflater this$0> // 105 241:getfield #230 <Field Object[] SupportMenuInflater.mActionViewConstructorArguments> // 106 244:invokespecial #232 <Method Object newInstance(String, Class[], Object[])> // 107 247:checkcast #234 <Class View> // 108 250:invokeinterface #238 <Method MenuItem MenuItem.setActionView(View)> // 109 255:pop flag = true; // 110 256:iconst_1 // 111 257:istore_2 } if(itemActionViewLayout > 0) //* 112 258:aload_0 //* 113 259:getfield #240 <Field int itemActionViewLayout> //* 114 262:ifle 291 if(!flag) //* 115 265:iload_2 //* 116 266:ifne 283 menuitem.setActionView(itemActionViewLayout); // 117 269:aload_1 // 118 270:aload_0 // 119 271:getfield #240 <Field int itemActionViewLayout> // 120 274:invokeinterface #242 <Method MenuItem MenuItem.setActionView(int)> // 121 279:pop else //* 122 280:goto 291 Log.w("SupportMenuInflater", "Ignoring attribute 'itemActionViewLayout'. Action view already specified."); // 123 283:ldc1 #111 <String "SupportMenuInflater"> // 124 285:ldc1 #244 <String "Ignoring attribute 'itemActionViewLayout'. Action view already specified."> // 125 287:invokestatic #247 <Method int Log.w(String, String)> // 126 290:pop if(itemActionProvider != null) //* 127 291:aload_0 //* 128 292:getfield #249 <Field ActionProvider itemActionProvider> //* 129 295:ifnull 307 MenuItemCompat.setActionProvider(menuitem, itemActionProvider); // 130 298:aload_1 // 131 299:aload_0 // 132 300:getfield #249 <Field ActionProvider itemActionProvider> // 133 303:invokestatic #255 <Method MenuItem MenuItemCompat.setActionProvider(MenuItem, ActionProvider)> // 134 306:pop MenuItemCompat.setContentDescription(menuitem, itemContentDescription); // 135 307:aload_1 // 136 308:aload_0 // 137 309:getfield #257 <Field CharSequence itemContentDescription> // 138 312:invokestatic #261 <Method void MenuItemCompat.setContentDescription(MenuItem, CharSequence)> MenuItemCompat.setTooltipText(menuitem, itemTooltipText); // 139 315:aload_1 // 140 316:aload_0 // 141 317:getfield #263 <Field CharSequence itemTooltipText> // 142 320:invokestatic #266 <Method void MenuItemCompat.setTooltipText(MenuItem, CharSequence)> // 143 323:return } public void addItem() { itemAdded = true; // 0 0:aload_0 // 1 1:iconst_1 // 2 2:putfield #269 <Field boolean itemAdded> setItem(menu.add(groupId, itemId, itemCategoryOrder, itemTitle)); // 3 5:aload_0 // 4 6:aload_0 // 5 7:getfield #62 <Field Menu menu> // 6 10:aload_0 // 7 11:getfield #271 <Field int groupId> // 8 14:aload_0 // 9 15:getfield #273 <Field int itemId> // 10 18:aload_0 // 11 19:getfield #275 <Field int itemCategoryOrder> // 12 22:aload_0 // 13 23:getfield #277 <Field CharSequence itemTitle> // 14 26:invokeinterface #283 <Method MenuItem Menu.add(int, int, int, CharSequence)> // 15 31:invokespecial #285 <Method void setItem(MenuItem)> // 16 34:return } public SubMenu addSubMenuItem() { itemAdded = true; // 0 0:aload_0 // 1 1:iconst_1 // 2 2:putfield #269 <Field boolean itemAdded> SubMenu submenu = menu.addSubMenu(groupId, itemId, itemCategoryOrder, itemTitle); // 3 5:aload_0 // 4 6:getfield #62 <Field Menu menu> // 5 9:aload_0 // 6 10:getfield #271 <Field int groupId> // 7 13:aload_0 // 8 14:getfield #273 <Field int itemId> // 9 17:aload_0 // 10 18:getfield #275 <Field int itemCategoryOrder> // 11 21:aload_0 // 12 22:getfield #277 <Field CharSequence itemTitle> // 13 25:invokeinterface #291 <Method SubMenu Menu.addSubMenu(int, int, int, CharSequence)> // 14 30:astore_1 setItem(submenu.getItem()); // 15 31:aload_0 // 16 32:aload_1 // 17 33:invokeinterface #297 <Method MenuItem SubMenu.getItem()> // 18 38:invokespecial #285 <Method void setItem(MenuItem)> return submenu; // 19 41:aload_1 // 20 42:areturn } public boolean hasAddedItem() { return itemAdded; // 0 0:aload_0 // 1 1:getfield #269 <Field boolean itemAdded> // 2 4:ireturn } public void readGroup(AttributeSet attributeset) { attributeset = ((AttributeSet) (mContext.obtainStyledAttributes(attributeset, android.support.v7.appcompat.R.styleable.MenuGroup))); // 0 0:aload_0 // 1 1:getfield #57 <Field SupportMenuInflater this$0> // 2 4:getfield #82 <Field Context SupportMenuInflater.mContext> // 3 7:aload_1 // 4 8:getstatic #306 <Field int[] android.support.v7.appcompat.R$styleable.MenuGroup> // 5 11:invokevirtual #310 <Method TypedArray Context.obtainStyledAttributes(AttributeSet, int[])> // 6 14:astore_1 groupId = ((TypedArray) (attributeset)).getResourceId(android.support.v7.appcompat.R.styleable.MenuGroup_android_id, 0); // 7 15:aload_0 // 8 16:aload_1 // 9 17:getstatic #313 <Field int android.support.v7.appcompat.R$styleable.MenuGroup_android_id> // 10 20:iconst_0 // 11 21:invokevirtual #319 <Method int TypedArray.getResourceId(int, int)> // 12 24:putfield #271 <Field int groupId> groupCategory = ((TypedArray) (attributeset)).getInt(android.support.v7.appcompat.R.styleable.MenuGroup_android_menuCategory, 0); // 13 27:aload_0 // 14 28:aload_1 // 15 29:getstatic #322 <Field int android.support.v7.appcompat.R$styleable.MenuGroup_android_menuCategory> // 16 32:iconst_0 // 17 33:invokevirtual #325 <Method int TypedArray.getInt(int, int)> // 18 36:putfield #327 <Field int groupCategory> groupOrder = ((TypedArray) (attributeset)).getInt(android.support.v7.appcompat.R.styleable.MenuGroup_android_orderInCategory, 0); // 19 39:aload_0 // 20 40:aload_1 // 21 41:getstatic #330 <Field int android.support.v7.appcompat.R$styleable.MenuGroup_android_orderInCategory> // 22 44:iconst_0 // 23 45:invokevirtual #325 <Method int TypedArray.getInt(int, int)> // 24 48:putfield #332 <Field int groupOrder> groupCheckable = ((TypedArray) (attributeset)).getInt(android.support.v7.appcompat.R.styleable.MenuGroup_android_checkableBehavior, 0); // 25 51:aload_0 // 26 52:aload_1 // 27 53:getstatic #335 <Field int android.support.v7.appcompat.R$styleable.MenuGroup_android_checkableBehavior> // 28 56:iconst_0 // 29 57:invokevirtual #325 <Method int TypedArray.getInt(int, int)> // 30 60:putfield #337 <Field int groupCheckable> groupVisible = ((TypedArray) (attributeset)).getBoolean(android.support.v7.appcompat.R.styleable.MenuGroup_android_visible, true); // 31 63:aload_0 // 32 64:aload_1 // 33 65:getstatic #340 <Field int android.support.v7.appcompat.R$styleable.MenuGroup_android_visible> // 34 68:iconst_1 // 35 69:invokevirtual #344 <Method boolean TypedArray.getBoolean(int, boolean)> // 36 72:putfield #346 <Field boolean groupVisible> groupEnabled = ((TypedArray) (attributeset)).getBoolean(android.support.v7.appcompat.R.styleable.MenuGroup_android_enabled, true); // 37 75:aload_0 // 38 76:aload_1 // 39 77:getstatic #349 <Field int android.support.v7.appcompat.R$styleable.MenuGroup_android_enabled> // 40 80:iconst_1 // 41 81:invokevirtual #344 <Method boolean TypedArray.getBoolean(int, boolean)> // 42 84:putfield #351 <Field boolean groupEnabled> ((TypedArray) (attributeset)).recycle(); // 43 87:aload_1 // 44 88:invokevirtual #354 <Method void TypedArray.recycle()> // 45 91:return } public void readItem(AttributeSet attributeset) { attributeset = ((AttributeSet) (mContext.obtainStyledAttributes(attributeset, android.support.v7.appcompat.R.styleable.MenuItem))); // 0 0:aload_0 // 1 1:getfield #57 <Field SupportMenuInflater this$0> // 2 4:getfield #82 <Field Context SupportMenuInflater.mContext> // 3 7:aload_1 // 4 8:getstatic #358 <Field int[] android.support.v7.appcompat.R$styleable.MenuItem> // 5 11:invokevirtual #310 <Method TypedArray Context.obtainStyledAttributes(AttributeSet, int[])> // 6 14:astore_1 itemId = ((TypedArray) (attributeset)).getResourceId(android.support.v7.appcompat.R.styleable.MenuItem_android_id, 0); // 7 15:aload_0 // 8 16:aload_1 // 9 17:getstatic #361 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_id> // 10 20:iconst_0 // 11 21:invokevirtual #319 <Method int TypedArray.getResourceId(int, int)> // 12 24:putfield #273 <Field int itemId> itemCategoryOrder = 0xffff0000 & ((TypedArray) (attributeset)).getInt(android.support.v7.appcompat.R.styleable.MenuItem_android_menuCategory, groupCategory) | 0xffff & ((TypedArray) (attributeset)).getInt(android.support.v7.appcompat.R.styleable.MenuItem_android_orderInCategory, groupOrder); // 13 27:aload_0 // 14 28:ldc2 #362 <Int 0xffff0000> // 15 31:aload_1 // 16 32:getstatic #365 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_menuCategory> // 17 35:aload_0 // 18 36:getfield #327 <Field int groupCategory> // 19 39:invokevirtual #325 <Method int TypedArray.getInt(int, int)> // 20 42:iand // 21 43:ldc2 #366 <Int 65535> // 22 46:aload_1 // 23 47:getstatic #369 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_orderInCategory> // 24 50:aload_0 // 25 51:getfield #332 <Field int groupOrder> // 26 54:invokevirtual #325 <Method int TypedArray.getInt(int, int)> // 27 57:iand // 28 58:ior // 29 59:putfield #275 <Field int itemCategoryOrder> itemTitle = ((TypedArray) (attributeset)).getText(android.support.v7.appcompat.R.styleable.MenuItem_android_title); // 30 62:aload_0 // 31 63:aload_1 // 32 64:getstatic #372 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_title> // 33 67:invokevirtual #376 <Method CharSequence TypedArray.getText(int)> // 34 70:putfield #277 <Field CharSequence itemTitle> itemTitleCondensed = ((TypedArray) (attributeset)).getText(android.support.v7.appcompat.R.styleable.MenuItem_android_titleCondensed); // 35 73:aload_0 // 36 74:aload_1 // 37 75:getstatic #379 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_titleCondensed> // 38 78:invokevirtual #376 <Method CharSequence TypedArray.getText(int)> // 39 81:putfield #159 <Field CharSequence itemTitleCondensed> itemIconResId = ((TypedArray) (attributeset)).getResourceId(android.support.v7.appcompat.R.styleable.MenuItem_android_icon, 0); // 40 84:aload_0 // 41 85:aload_1 // 42 86:getstatic #382 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_icon> // 43 89:iconst_0 // 44 90:invokevirtual #319 <Method int TypedArray.getResourceId(int, int)> // 45 93:putfield #165 <Field int itemIconResId> itemAlphabeticShortcut = getShortcut(((TypedArray) (attributeset)).getString(android.support.v7.appcompat.R.styleable.MenuItem_android_alphabeticShortcut)); // 46 96:aload_0 // 47 97:aload_0 // 48 98:aload_1 // 49 99:getstatic #385 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_alphabeticShortcut> // 50 102:invokevirtual #389 <Method String TypedArray.getString(int)> // 51 105:invokespecial #391 <Method char getShortcut(String)> // 52 108:putfield #171 <Field char itemAlphabeticShortcut> itemNumericShortcut = getShortcut(((TypedArray) (attributeset)).getString(android.support.v7.appcompat.R.styleable.MenuItem_android_numericShortcut)); // 53 111:aload_0 // 54 112:aload_0 // 55 113:aload_1 // 56 114:getstatic #394 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_numericShortcut> // 57 117:invokevirtual #389 <Method String TypedArray.getString(int)> // 58 120:invokespecial #391 <Method char getShortcut(String)> // 59 123:putfield #177 <Field char itemNumericShortcut> if(((TypedArray) (attributeset)).hasValue(android.support.v7.appcompat.R.styleable.MenuItem_android_checkable)) //* 60 126:aload_1 //* 61 127:getstatic #397 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_checkable> //* 62 130:invokevirtual #401 <Method boolean TypedArray.hasValue(int)> //* 63 133:ifeq 162 { int i; if(((TypedArray) (attributeset)).getBoolean(android.support.v7.appcompat.R.styleable.MenuItem_android_checkable, false)) //* 64 136:aload_1 //* 65 137:getstatic #397 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_checkable> //* 66 140:iconst_0 //* 67 141:invokevirtual #344 <Method boolean TypedArray.getBoolean(int, boolean)> //* 68 144:ifeq 152 i = 1; // 69 147:iconst_1 // 70 148:istore_2 else //* 71 149:goto 154 i = 0; // 72 152:iconst_0 // 73 153:istore_2 itemCheckable = i; // 74 154:aload_0 // 75 155:iload_2 // 76 156:putfield #154 <Field int itemCheckable> } else //* 77 159:goto 170 { itemCheckable = groupCheckable; // 78 162:aload_0 // 79 163:aload_0 // 80 164:getfield #337 <Field int groupCheckable> // 81 167:putfield #154 <Field int itemCheckable> } itemChecked = ((TypedArray) (attributeset)).getBoolean(android.support.v7.appcompat.R.styleable.MenuItem_android_checked, false); // 82 170:aload_0 // 83 171:aload_1 // 84 172:getstatic #404 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_checked> // 85 175:iconst_0 // 86 176:invokevirtual #344 <Method boolean TypedArray.getBoolean(int, boolean)> // 87 179:putfield #136 <Field boolean itemChecked> itemVisible = ((TypedArray) (attributeset)).getBoolean(android.support.v7.appcompat.R.styleable.MenuItem_android_visible, groupVisible); // 88 182:aload_0 // 89 183:aload_1 // 90 184:getstatic #407 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_visible> // 91 187:aload_0 // 92 188:getfield #346 <Field boolean groupVisible> // 93 191:invokevirtual #344 <Method boolean TypedArray.getBoolean(int, boolean)> // 94 194:putfield #144 <Field boolean itemVisible> itemEnabled = ((TypedArray) (attributeset)).getBoolean(android.support.v7.appcompat.R.styleable.MenuItem_android_enabled, groupEnabled); // 95 197:aload_0 // 96 198:aload_1 // 97 199:getstatic #410 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_enabled> // 98 202:aload_0 // 99 203:getfield #351 <Field boolean groupEnabled> // 100 206:invokevirtual #344 <Method boolean TypedArray.getBoolean(int, boolean)> // 101 209:putfield #149 <Field boolean itemEnabled> itemShowAsAction = ((TypedArray) (attributeset)).getInt(android.support.v7.appcompat.R.styleable.MenuItem_showAsAction, -1); // 102 212:aload_0 // 103 213:aload_1 // 104 214:getstatic #413 <Field int android.support.v7.appcompat.R$styleable.MenuItem_showAsAction> // 105 217:iconst_m1 // 106 218:invokevirtual #325 <Method int TypedArray.getInt(int, int)> // 107 221:putfield #182 <Field int itemShowAsAction> itemListenerMethodName = ((TypedArray) (attributeset)).getString(android.support.v7.appcompat.R.styleable.MenuItem_android_onClick); // 108 224:aload_0 // 109 225:aload_1 // 110 226:getstatic #416 <Field int android.support.v7.appcompat.R$styleable.MenuItem_android_onClick> // 111 229:invokevirtual #389 <Method String TypedArray.getString(int)> // 112 232:putfield #188 <Field String itemListenerMethodName> itemActionViewLayout = ((TypedArray) (attributeset)).getResourceId(android.support.v7.appcompat.R.styleable.MenuItem_actionLayout, 0); // 113 235:aload_0 // 114 236:aload_1 // 115 237:getstatic #419 <Field int android.support.v7.appcompat.R$styleable.MenuItem_actionLayout> // 116 240:iconst_0 // 117 241:invokevirtual #319 <Method int TypedArray.getResourceId(int, int)> // 118 244:putfield #240 <Field int itemActionViewLayout> itemActionViewClassName = ((TypedArray) (attributeset)).getString(android.support.v7.appcompat.R.styleable.MenuItem_actionViewClass); // 119 247:aload_0 // 120 248:aload_1 // 121 249:getstatic #422 <Field int android.support.v7.appcompat.R$styleable.MenuItem_actionViewClass> // 122 252:invokevirtual #389 <Method String TypedArray.getString(int)> // 123 255:putfield #222 <Field String itemActionViewClassName> itemActionProviderClassName = ((TypedArray) (attributeset)).getString(android.support.v7.appcompat.R.styleable.MenuItem_actionProviderClass); // 124 258:aload_0 // 125 259:aload_1 // 126 260:getstatic #425 <Field int android.support.v7.appcompat.R$styleable.MenuItem_actionProviderClass> // 127 263:invokevirtual #389 <Method String TypedArray.getString(int)> // 128 266:putfield #427 <Field String itemActionProviderClassName> boolean flag; if(itemActionProviderClassName != null) //* 129 269:aload_0 //* 130 270:getfield #427 <Field String itemActionProviderClassName> //* 131 273:ifnull 281 flag = true; // 132 276:iconst_1 // 133 277:istore_2 else //* 134 278:goto 283 flag = false; // 135 281:iconst_0 // 136 282:istore_2 if(flag && itemActionViewLayout == 0 && itemActionViewClassName == null) //* 137 283:iload_2 //* 138 284:ifeq 329 //* 139 287:aload_0 //* 140 288:getfield #240 <Field int itemActionViewLayout> //* 141 291:ifne 329 //* 142 294:aload_0 //* 143 295:getfield #222 <Field String itemActionViewClassName> //* 144 298:ifnonnull 329 { itemActionProvider = (ActionProvider)newInstance(itemActionProviderClassName, SupportMenuInflater.ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE, mActionProviderConstructorArguments); // 145 301:aload_0 // 146 302:aload_0 // 147 303:aload_0 // 148 304:getfield #427 <Field String itemActionProviderClassName> // 149 307:getstatic #430 <Field Class[] SupportMenuInflater.ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE> // 150 310:aload_0 // 151 311:getfield #57 <Field SupportMenuInflater this$0> // 152 314:getfield #433 <Field Object[] SupportMenuInflater.mActionProviderConstructorArguments> // 153 317:invokespecial #232 <Method Object newInstance(String, Class[], Object[])> // 154 320:checkcast #435 <Class ActionProvider> // 155 323:putfield #249 <Field ActionProvider itemActionProvider> } else //* 156 326:goto 347 { if(flag) //* 157 329:iload_2 //* 158 330:ifeq 342 Log.w("SupportMenuInflater", "Ignoring attribute 'actionProviderClass'. Action view already specified."); // 159 333:ldc1 #111 <String "SupportMenuInflater"> // 160 335:ldc2 #437 <String "Ignoring attribute 'actionProviderClass'. Action view already specified."> // 161 338:invokestatic #247 <Method int Log.w(String, String)> // 162 341:pop itemActionProvider = null; // 163 342:aload_0 // 164 343:aconst_null // 165 344:putfield #249 <Field ActionProvider itemActionProvider> } itemContentDescription = ((TypedArray) (attributeset)).getText(android.support.v7.appcompat.R.styleable.MenuItem_contentDescription); // 166 347:aload_0 // 167 348:aload_1 // 168 349:getstatic #440 <Field int android.support.v7.appcompat.R$styleable.MenuItem_contentDescription> // 169 352:invokevirtual #376 <Method CharSequence TypedArray.getText(int)> // 170 355:putfield #257 <Field CharSequence itemContentDescription> itemTooltipText = ((TypedArray) (attributeset)).getText(android.support.v7.appcompat.R.styleable.MenuItem_tooltipText); // 171 358:aload_0 // 172 359:aload_1 // 173 360:getstatic #443 <Field int android.support.v7.appcompat.R$styleable.MenuItem_tooltipText> // 174 363:invokevirtual #376 <Method CharSequence TypedArray.getText(int)> // 175 366:putfield #263 <Field CharSequence itemTooltipText> ((TypedArray) (attributeset)).recycle(); // 176 369:aload_1 // 177 370:invokevirtual #354 <Method void TypedArray.recycle()> itemAdded = false; // 178 373:aload_0 // 179 374:iconst_0 // 180 375:putfield #269 <Field boolean itemAdded> // 181 378:return } public void resetGroup() { groupId = 0; // 0 0:aload_0 // 1 1:iconst_0 // 2 2:putfield #271 <Field int groupId> groupCategory = 0; // 3 5:aload_0 // 4 6:iconst_0 // 5 7:putfield #327 <Field int groupCategory> groupOrder = 0; // 6 10:aload_0 // 7 11:iconst_0 // 8 12:putfield #332 <Field int groupOrder> groupCheckable = 0; // 9 15:aload_0 // 10 16:iconst_0 // 11 17:putfield #337 <Field int groupCheckable> groupVisible = true; // 12 20:aload_0 // 13 21:iconst_1 // 14 22:putfield #346 <Field boolean groupVisible> groupEnabled = true; // 15 25:aload_0 // 16 26:iconst_1 // 17 27:putfield #351 <Field boolean groupEnabled> // 18 30:return } private static final int defaultGroupId = 0; private static final int defaultItemCategory = 0; private static final int defaultItemCheckable = 0; private static final boolean defaultItemChecked = false; private static final boolean defaultItemEnabled = true; private static final int defaultItemId = 0; private static final int defaultItemOrder = 0; private static final boolean defaultItemVisible = true; private int groupCategory; private int groupCheckable; private boolean groupEnabled; private int groupId; private int groupOrder; private boolean groupVisible; ActionProvider itemActionProvider; private String itemActionProviderClassName; private String itemActionViewClassName; private int itemActionViewLayout; private boolean itemAdded; private char itemAlphabeticShortcut; private int itemCategoryOrder; private int itemCheckable; private boolean itemChecked; private CharSequence itemContentDescription; private boolean itemEnabled; private int itemIconResId; private int itemId; private String itemListenerMethodName; private char itemNumericShortcut; private int itemShowAsAction; private CharSequence itemTitle; private CharSequence itemTitleCondensed; private CharSequence itemTooltipText; private boolean itemVisible; private Menu menu; final SupportMenuInflater this$0; public MenuState(Menu menu1) { this$0 = SupportMenuInflater.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #57 <Field SupportMenuInflater this$0> super(); // 3 5:aload_0 // 4 6:invokespecial #60 <Method void Object()> menu = menu1; // 5 9:aload_0 // 6 10:aload_2 // 7 11:putfield #62 <Field Menu menu> resetGroup(); // 8 14:aload_0 // 9 15:invokevirtual #65 <Method void resetGroup()> // 10 18:return } } public SupportMenuInflater(Context context) { super(context); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokespecial #56 <Method void MenuInflater(Context)> mContext = context; // 3 5:aload_0 // 4 6:aload_1 // 5 7:putfield #58 <Field Context mContext> mActionViewConstructorArguments = (new Object[] { context }); // 6 10:aload_0 // 7 11:iconst_1 // 8 12:anewarray Object[] // 9 15:dup // 10 16:iconst_0 // 11 17:aload_1 // 12 18:aastore // 13 19:putfield #62 <Field Object[] mActionViewConstructorArguments> mActionProviderConstructorArguments = mActionViewConstructorArguments; // 14 22:aload_0 // 15 23:aload_0 // 16 24:getfield #62 <Field Object[] mActionViewConstructorArguments> // 17 27:putfield #64 <Field Object[] mActionProviderConstructorArguments> // 18 30:return } private Object findRealOwner(Object obj) { if(obj instanceof Activity) //* 0 0:aload_1 //* 1 1:instanceof #68 <Class Activity> //* 2 4:ifeq 9 return obj; // 3 7:aload_1 // 4 8:areturn if(obj instanceof ContextWrapper) //* 5 9:aload_1 //* 6 10:instanceof #70 <Class ContextWrapper> //* 7 13:ifeq 28 return findRealOwner(((Object) (((ContextWrapper)obj).getBaseContext()))); // 8 16:aload_0 // 9 17:aload_1 // 10 18:checkcast #70 <Class ContextWrapper> // 11 21:invokevirtual #74 <Method Context ContextWrapper.getBaseContext()> // 12 24:invokespecial #76 <Method Object findRealOwner(Object)> // 13 27:areturn else return obj; // 14 28:aload_1 // 15 29:areturn } private void parseMenu(XmlPullParser xmlpullparser, AttributeSet attributeset, Menu menu) throws XmlPullParserException, IOException { MenuState menustate = new MenuState(menu); // 0 0:new #9 <Class SupportMenuInflater$MenuState> // 1 3:dup // 2 4:aload_0 // 3 5:aload_3 // 4 6:invokespecial #85 <Method void SupportMenuInflater$MenuState(SupportMenuInflater, Menu)> // 5 9:astore 10 int i = xmlpullparser.getEventType(); // 6 11:aload_1 // 7 12:invokeinterface #91 <Method int XmlPullParser.getEventType()> // 8 17:istore 4 boolean flag2 = false; // 9 19:iconst_0 // 10 20:istore 6 Menu menu1 = null; // 11 22:aconst_null // 12 23:astore 9 do { if(i == 2) //* 13 25:iload 4 //* 14 27:iconst_2 //* 15 28:icmpne 85 { menu = ((Menu) (xmlpullparser.getName())); // 16 31:aload_1 // 17 32:invokeinterface #95 <Method String XmlPullParser.getName()> // 18 37:astore_3 if(((String) (menu)).equals("menu")) //* 19 38:aload_3 //* 20 39:ldc1 #34 <String "menu"> //* 21 41:invokevirtual #101 <Method boolean String.equals(Object)> //* 22 44:ifeq 58 i = xmlpullparser.next(); // 23 47:aload_1 // 24 48:invokeinterface #104 <Method int XmlPullParser.next()> // 25 53:istore 4 else //* 26 55:goto 107 throw new RuntimeException((new StringBuilder()).append("Expecting menu, got ").append(((String) (menu))).toString()); // 27 58:new #106 <Class RuntimeException> // 28 61:dup // 29 62:new #108 <Class StringBuilder> // 30 65:dup // 31 66:invokespecial #110 <Method void StringBuilder()> // 32 69:ldc1 #112 <String "Expecting menu, got "> // 33 71:invokevirtual #116 <Method StringBuilder StringBuilder.append(String)> // 34 74:aload_3 // 35 75:invokevirtual #116 <Method StringBuilder StringBuilder.append(String)> // 36 78:invokevirtual #119 <Method String StringBuilder.toString()> // 37 81:invokespecial #122 <Method void RuntimeException(String)> // 38 84:athrow break; } int j = xmlpullparser.next(); // 39 85:aload_1 // 40 86:invokeinterface #104 <Method int XmlPullParser.next()> // 41 91:istore 5 i = j; // 42 93:iload 5 // 43 95:istore 4 if(j != 1) continue; // 44 97:iload 5 // 45 99:iconst_1 // 46 100:icmpne 25 i = j; // 47 103:iload 5 // 48 105:istore 4 break; } while(true); boolean flag1 = false; // 49 107:iconst_0 // 50 108:istore 5 int k = i; // 51 110:iload 4 // 52 112:istore 8 boolean flag3; for(; !flag1; flag1 = flag3) //* 53 114:iload 5 //* 54 116:ifne 507 { boolean flag; switch(k) //* 55 119:iload 8 { //* 56 121:tableswitch 1 3: default 148 // 1 475 // 2 162 // 3 290 default: flag = flag2; // 57 148:iload 6 // 58 150:istore 4 menu = menu1; // 59 152:aload 9 // 60 154:astore_3 flag3 = flag1; // 61 155:iload 5 // 62 157:istore 7 break; // 63 159:goto 485 case 2: // '\002' if(flag2) //* 64 162:iload 6 //* 65 164:ifeq 181 { flag = flag2; // 66 167:iload 6 // 67 169:istore 4 menu = menu1; // 68 171:aload 9 // 69 173:astore_3 flag3 = flag1; // 70 174:iload 5 // 71 176:istore 7 break; // 72 178:goto 485 } menu = ((Menu) (xmlpullparser.getName())); // 73 181:aload_1 // 74 182:invokeinterface #95 <Method String XmlPullParser.getName()> // 75 187:astore_3 if(((String) (menu)).equals("group")) //* 76 188:aload_3 //* 77 189:ldc1 #28 <String "group"> //* 78 191:invokevirtual #101 <Method boolean String.equals(Object)> //* 79 194:ifeq 217 { menustate.readGroup(attributeset); // 80 197:aload 10 // 81 199:aload_2 // 82 200:invokevirtual #126 <Method void SupportMenuInflater$MenuState.readGroup(AttributeSet)> flag = flag2; // 83 203:iload 6 // 84 205:istore 4 menu = menu1; // 85 207:aload 9 // 86 209:astore_3 flag3 = flag1; // 87 210:iload 5 // 88 212:istore 7 break; // 89 214:goto 485 } if(((String) (menu)).equals("item")) //* 90 217:aload_3 //* 91 218:ldc1 #31 <String "item"> //* 92 220:invokevirtual #101 <Method boolean String.equals(Object)> //* 93 223:ifeq 246 { menustate.readItem(attributeset); // 94 226:aload 10 // 95 228:aload_2 // 96 229:invokevirtual #129 <Method void SupportMenuInflater$MenuState.readItem(AttributeSet)> flag = flag2; // 97 232:iload 6 // 98 234:istore 4 menu = menu1; // 99 236:aload 9 // 100 238:astore_3 flag3 = flag1; // 101 239:iload 5 // 102 241:istore 7 break; // 103 243:goto 485 } if(((String) (menu)).equals("menu")) //* 104 246:aload_3 //* 105 247:ldc1 #34 <String "menu"> //* 106 249:invokevirtual #101 <Method boolean String.equals(Object)> //* 107 252:ifeq 280 { parseMenu(xmlpullparser, attributeset, ((Menu) (menustate.addSubMenuItem()))); // 108 255:aload_0 // 109 256:aload_1 // 110 257:aload_2 // 111 258:aload 10 // 112 260:invokevirtual #133 <Method SubMenu SupportMenuInflater$MenuState.addSubMenuItem()> // 113 263:invokespecial #135 <Method void parseMenu(XmlPullParser, AttributeSet, Menu)> flag = flag2; // 114 266:iload 6 // 115 268:istore 4 menu = menu1; // 116 270:aload 9 // 117 272:astore_3 flag3 = flag1; // 118 273:iload 5 // 119 275:istore 7 } else //* 120 277:goto 485 { flag = true; // 121 280:iconst_1 // 122 281:istore 4 flag3 = flag1; // 123 283:iload 5 // 124 285:istore 7 } break; // 125 287:goto 485 case 3: // '\003' String s = xmlpullparser.getName(); // 126 290:aload_1 // 127 291:invokeinterface #95 <Method String XmlPullParser.getName()> // 128 296:astore 11 if(flag2 && s.equals(((Object) (menu1)))) //* 129 298:iload 6 //* 130 300:ifeq 325 //* 131 303:aload 11 //* 132 305:aload 9 //* 133 307:invokevirtual #101 <Method boolean String.equals(Object)> //* 134 310:ifeq 325 { flag = false; // 135 313:iconst_0 // 136 314:istore 4 menu = null; // 137 316:aconst_null // 138 317:astore_3 flag3 = flag1; // 139 318:iload 5 // 140 320:istore 7 break; // 141 322:goto 485 } if(s.equals("group")) //* 142 325:aload 11 //* 143 327:ldc1 #28 <String "group"> //* 144 329:invokevirtual #101 <Method boolean String.equals(Object)> //* 145 332:ifeq 354 { menustate.resetGroup(); // 146 335:aload 10 // 147 337:invokevirtual #138 <Method void SupportMenuInflater$MenuState.resetGroup()> flag = flag2; // 148 340:iload 6 // 149 342:istore 4 menu = menu1; // 150 344:aload 9 // 151 346:astore_3 flag3 = flag1; // 152 347:iload 5 // 153 349:istore 7 break; // 154 351:goto 485 } if(s.equals("item")) //* 155 354:aload 11 //* 156 356:ldc1 #31 <String "item"> //* 157 358:invokevirtual #101 <Method boolean String.equals(Object)> //* 158 361:ifeq 441 { flag = flag2; // 159 364:iload 6 // 160 366:istore 4 menu = menu1; // 161 368:aload 9 // 162 370:astore_3 flag3 = flag1; // 163 371:iload 5 // 164 373:istore 7 if(menustate.hasAddedItem()) break; // 165 375:aload 10 // 166 377:invokevirtual #142 <Method boolean SupportMenuInflater$MenuState.hasAddedItem()> // 167 380:ifne 485 if(menustate.itemActionProvider != null && menustate.itemActionProvider.hasSubMenu()) //* 168 383:aload 10 //* 169 385:getfield #146 <Field ActionProvider SupportMenuInflater$MenuState.itemActionProvider> //* 170 388:ifnull 422 //* 171 391:aload 10 //* 172 393:getfield #146 <Field ActionProvider SupportMenuInflater$MenuState.itemActionProvider> //* 173 396:invokevirtual #151 <Method boolean ActionProvider.hasSubMenu()> //* 174 399:ifeq 422 { menustate.addSubMenuItem(); // 175 402:aload 10 // 176 404:invokevirtual #133 <Method SubMenu SupportMenuInflater$MenuState.addSubMenuItem()> // 177 407:pop flag = flag2; // 178 408:iload 6 // 179 410:istore 4 menu = menu1; // 180 412:aload 9 // 181 414:astore_3 flag3 = flag1; // 182 415:iload 5 // 183 417:istore 7 } else //* 184 419:goto 485 { menustate.addItem(); // 185 422:aload 10 // 186 424:invokevirtual #154 <Method void SupportMenuInflater$MenuState.addItem()> flag = flag2; // 187 427:iload 6 // 188 429:istore 4 menu = menu1; // 189 431:aload 9 // 190 433:astore_3 flag3 = flag1; // 191 434:iload 5 // 192 436:istore 7 } break; // 193 438:goto 485 } flag = flag2; // 194 441:iload 6 // 195 443:istore 4 menu = menu1; // 196 445:aload 9 // 197 447:astore_3 flag3 = flag1; // 198 448:iload 5 // 199 450:istore 7 if(s.equals("menu")) //* 200 452:aload 11 //* 201 454:ldc1 #34 <String "menu"> //* 202 456:invokevirtual #101 <Method boolean String.equals(Object)> //* 203 459:ifeq 485 { flag3 = true; // 204 462:iconst_1 // 205 463:istore 7 flag = flag2; // 206 465:iload 6 // 207 467:istore 4 menu = menu1; // 208 469:aload 9 // 209 471:astore_3 } break; //* 210 472:goto 485 case 1: // '\001' throw new RuntimeException("Unexpected end of document"); // 211 475:new #106 <Class RuntimeException> // 212 478:dup // 213 479:ldc1 #156 <String "Unexpected end of document"> // 214 481:invokespecial #122 <Method void RuntimeException(String)> // 215 484:athrow } k = xmlpullparser.next(); // 216 485:aload_1 // 217 486:invokeinterface #104 <Method int XmlPullParser.next()> // 218 491:istore 8 flag2 = flag; // 219 493:iload 4 // 220 495:istore 6 menu1 = menu; // 221 497:aload_3 // 222 498:astore 9 } // 223 500:iload 7 // 224 502:istore 5 //* 225 504:goto 114 // 226 507:return } Object getRealOwner() { if(mRealOwner == null) //* 0 0:aload_0 //* 1 1:getfield #161 <Field Object mRealOwner> //* 2 4:ifnonnull 19 mRealOwner = findRealOwner(((Object) (mContext))); // 3 7:aload_0 // 4 8:aload_0 // 5 9:aload_0 // 6 10:getfield #58 <Field Context mContext> // 7 13:invokespecial #76 <Method Object findRealOwner(Object)> // 8 16:putfield #161 <Field Object mRealOwner> return mRealOwner; // 9 19:aload_0 // 10 20:getfield #161 <Field Object mRealOwner> // 11 23:areturn } public void inflate(int i, Menu menu) { XmlResourceParser xmlresourceparser; XmlResourceParser xmlresourceparser1; XmlResourceParser xmlresourceparser2; if(!(menu instanceof SupportMenu)) //* 0 0:aload_2 //* 1 1:instanceof #165 <Class SupportMenu> //* 2 4:ifne 14 { super.inflate(i, menu); // 3 7:aload_0 // 4 8:iload_1 // 5 9:aload_2 // 6 10:invokespecial #167 <Method void MenuInflater.inflate(int, Menu)> return; // 7 13:return } xmlresourceparser2 = null; // 8 14:aconst_null // 9 15:astore 5 xmlresourceparser = null; // 10 17:aconst_null // 11 18:astore_3 xmlresourceparser1 = null; // 12 19:aconst_null // 13 20:astore 4 XmlResourceParser xmlresourceparser3 = mContext.getResources().getLayout(i); // 14 22:aload_0 // 15 23:getfield #58 <Field Context mContext> // 16 26:invokevirtual #171 <Method Resources Context.getResources()> // 17 29:iload_1 // 18 30:invokevirtual #177 <Method XmlResourceParser Resources.getLayout(int)> // 19 33:astore 6 xmlresourceparser1 = xmlresourceparser3; // 20 35:aload 6 // 21 37:astore 4 xmlresourceparser2 = xmlresourceparser3; // 22 39:aload 6 // 23 41:astore 5 xmlresourceparser = xmlresourceparser3; // 24 43:aload 6 // 25 45:astore_3 parseMenu(((XmlPullParser) (xmlresourceparser3)), Xml.asAttributeSet(((XmlPullParser) (xmlresourceparser3))), menu); // 26 46:aload_0 // 27 47:aload 6 // 28 49:aload 6 // 29 51:invokestatic #183 <Method AttributeSet Xml.asAttributeSet(XmlPullParser)> // 30 54:aload_2 // 31 55:invokespecial #135 <Method void parseMenu(XmlPullParser, AttributeSet, Menu)> if(xmlresourceparser3 != null) //* 32 58:aload 6 //* 33 60:ifnull 114 { xmlresourceparser3.close(); // 34 63:aload 6 // 35 65:invokeinterface #188 <Method void XmlResourceParser.close()> return; // 36 70:return } else //* 37 71:astore_2 //* 38 72:aload 4 //* 39 74:astore_3 //* 40 75:new #190 <Class InflateException> //* 41 78:dup //* 42 79:ldc1 #192 <String "Error inflating menu XML"> //* 43 81:aload_2 //* 44 82:invokespecial #195 <Method void InflateException(String, Throwable)> //* 45 85:athrow //* 46 86:astore_2 //* 47 87:aload 5 //* 48 89:astore_3 //* 49 90:new #190 <Class InflateException> //* 50 93:dup //* 51 94:ldc1 #192 <String "Error inflating menu XML"> //* 52 96:aload_2 //* 53 97:invokespecial #195 <Method void InflateException(String, Throwable)> //* 54 100:athrow //* 55 101:astore_2 //* 56 102:aload_3 //* 57 103:ifnull 112 //* 58 106:aload_3 //* 59 107:invokeinterface #188 <Method void XmlResourceParser.close()> //* 60 112:aload_2 //* 61 113:athrow { return; // 62 114:return } menu; xmlresourceparser = xmlresourceparser1; throw new InflateException("Error inflating menu XML", ((Throwable) (menu))); menu; xmlresourceparser = xmlresourceparser2; throw new InflateException("Error inflating menu XML", ((Throwable) (menu))); menu; if(xmlresourceparser != null) xmlresourceparser.close(); throw menu; } static final Class ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE[] = ACTION_VIEW_CONSTRUCTOR_SIGNATURE; static final Class ACTION_VIEW_CONSTRUCTOR_SIGNATURE[] = { android/content/Context }; static final String LOG_TAG = "SupportMenuInflater"; static final int NO_ID = 0; private static final String XML_GROUP = "group"; private static final String XML_ITEM = "item"; private static final String XML_MENU = "menu"; final Object mActionProviderConstructorArguments[]; final Object mActionViewConstructorArguments[]; Context mContext; private Object mRealOwner; static { // 0 0:iconst_1 // 1 1:anewarray Class[] // 2 4:dup // 3 5:iconst_0 // 4 6:ldc1 #47 <Class Context> // 5 8:aastore // 6 9:putstatic #49 <Field Class[] ACTION_VIEW_CONSTRUCTOR_SIGNATURE> // 7 12:getstatic #49 <Field Class[] ACTION_VIEW_CONSTRUCTOR_SIGNATURE> // 8 15:putstatic #51 <Field Class[] ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE> //* 9 18:return } }
42.856844
295
0.584608
91210d343873762dc29f818aad2723fb93af4d31
5,164
package org.broadinstitute.ddp.db; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.typesafe.config.Config; import org.broadinstitute.ddp.TxnAwareBaseTest; import org.broadinstitute.ddp.constants.ConfigFile; import org.broadinstitute.ddp.exception.DDPException; import org.broadinstitute.ddp.util.ConfigManager; import org.broadinstitute.ddp.util.MySqlTestContainerUtil; import org.jdbi.v3.core.Handle; import org.junit.After; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PooledPasswordRotationTest extends TxnAwareBaseTest { private static final Logger LOG = LoggerFactory.getLogger(PooledPasswordRotationTest.class); private static final String BOGUS_TEST_PASSWORD = "bogus-test-password"; private static Config configWithUpdatedPassword; // the temporary config file used during this test private static String originalConfigFileContents; private static Config originalConfigPlusTestDbValues; private static Map<String, String> originalConfigOverrides = new HashMap<>(); @BeforeClass public static void saveConfig() throws IOException { ConfigManager originalConfigManager = ConfigManager.getInstance(); originalConfigPlusTestDbValues = originalConfigManager.getConfig(); originalConfigOverrides = originalConfigManager.getOverrides(); originalConfigFileContents = ConfigManager.readConfigFile(); configWithUpdatedPassword = MySqlTestContainerUtil.overrideConfigFileDbPasswords(BOGUS_TEST_PASSWORD); } /** * Changes the password for the currently logged in user and * refreshes all pooled connections so they will use the * new password. */ private void changePassword(Handle handle, String newPassword) { handle.execute("set password = password(?)", newPassword); handle.execute("flush privileges"); } /** * Verifies that password rotations can be performed by editing the conf * file in-place, without an app restart. */ @Test public void testPasswordRotation() throws Exception { try { TransactionWrapper.useTxn(handle -> changePassword(handle, BOGUS_TEST_PASSWORD)); } catch (Exception e) { LOG.error("Could not reset password. Is the test database using an unusual password?", e); } // write out the original config file plus the dynamically substituted testcontainer db config values // otherwise, automatic reread-the-config code will fail and leave the txnwrapper in an unrecoverable state ConfigManager.rewriteConfigFile(originalConfigPlusTestDbValues); TransactionWrapper.closePool(); try { TransactionWrapper.useTxn(handle -> { Assert.fail("Attempt to get a connection should have failed since we changed the password"); }); } catch (Exception e) { LOG.info("Login attempt failed as expected, since we rotated the password internally but didn't reload configuration."); // as expected; password has been reset but the pool doesn't know it yet } // since we are dealing with a connection pool, first we should // reload connections so that any new connection picks up the new password ConfigManager.rewriteConfigFile(configWithUpdatedPassword); TransactionWrapper.reloadDbPoolConfiguration(false); try { TransactionWrapper.useTxn(handle -> { LOG.info("Successfully updated password"); }); } catch (Exception e) { LOG.error("Failed to get a connection after updating the config file with new password", e); } } /** * Restores the db passwords to their original default, * wiping the connection pool so that subsequent tests * pickup the original credentials */ @After public void restoreConfiguration() throws IOException { try { String originalPassword = MySqlTestContainerUtil .parseDbUrlPassword(originalConfigPlusTestDbValues.getString(ConfigFile.DB_URL)) .orElseThrow(() -> new DDPException("no original password in original config!")); TransactionWrapper.useTxn(h -> changePassword(h, originalPassword)); } catch (Exception e) { LOG.error("Restoring password failed. Expect many downstream tests to fail.", e); } // restore the original config file ConfigManager.rewriteConfigFile(originalConfigFileContents); LOG.info("Restored config file after password rotation test"); // re-apply overrides ConfigManager configManager = ConfigManager.getInstance(); for (Map.Entry<String, String> override : originalConfigOverrides.entrySet()) { configManager.overrideValue(override.getKey(), override.getValue()); } TransactionWrapper.reloadDbPoolConfiguration(true); LOG.info("Reset test database config file to its original state."); } }
41.98374
132
0.704686
e51c9304e2dec6a65090d5636d5d3495e0e83bd1
879
package io.eventuate.tram.consumer.kafka; import io.eventuate.messaging.kafka.consumer.MessageConsumerKafkaConfiguration; import io.eventuate.messaging.kafka.consumer.MessageConsumerKafkaImpl; import io.eventuate.tram.consumer.common.MessageConsumerImplementation; import io.eventuate.tram.consumer.common.TramConsumerCommonConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({TramConsumerCommonConfiguration.class, MessageConsumerKafkaConfiguration.class}) public class EventuateTramKafkaMessageConsumerConfiguration { @Bean public MessageConsumerImplementation messageConsumerImplementation(MessageConsumerKafkaImpl messageConsumerKafka) { return new EventuateTramKafkaMessageConsumer(messageConsumerKafka); } }
46.263158
117
0.875995
3c4f0e1b1f10ac3ecbd251166ef1929258300f42
83
package com.infoskillstechnology.sinetop.data.room; public class AppDatabase { }
13.833333
51
0.807229
424b3e48cbe3cafe33ac9b593bc160d33bac60e2
2,026
/* * 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.geode.distributed.internal.tcpserver; import java.io.IOException; import org.apache.geode.cache.GemFireCache; import org.apache.geode.distributed.DistributedSystem; import org.apache.geode.distributed.internal.InternalConfigurationPersistenceService; /** * A handler which responds to messages for the {@link TcpServer} * * @since GemFire 5.7 */ public interface TcpHandler { /** * Process a request and return a response * * @return the response, or null if there is no reponse */ Object processRequest(Object request) throws IOException; void endRequest(Object request, long startTime); void endResponse(Object request, long startTime); /** * Perform any shutdown code in the handler after the TCP server has closed the socket. */ void shutDown(); /** * Informs the handler that TcpServer is restarting with the given distributed system and cache * * @param sharedConfig TODO */ void restarting(DistributedSystem ds, GemFireCache cache, InternalConfigurationPersistenceService sharedConfig); /** * Initialize the handler with the TcpServer. Called before the TcpServer starts accepting * connections. */ void init(TcpServer tcpServer); }
34.338983
100
0.755183
5a5a24e14bad0559f0cfc995ad8826e7902790eb
299
package org.library.result; public record Failure(Reason reason, String message) { public static Failure of(Reason reason, String message) { return new Failure(reason, message); } public enum Reason { CONFLICT, FORBIDDEN, NOT_FOUND, UNAUTHORIZED, USER_FAILURE } }
23
66
0.695652
aea7eebd38ad83de5e242029077b097807cfeefd
18,168
/* * $Id$ */ /* Copyright (c) 2000-2005 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.hasher; import java.util.*; import java.text.*; import java.math.*; import java.security.MessageDigest; import org.lockss.config.Configuration; import org.lockss.daemon.*; import org.lockss.daemon.status.*; import org.lockss.scheduler.*; import org.lockss.util.*; import org.lockss.app.*; import org.lockss.plugin.*; /** * Implementation of API for content and name hashing services that uses * the SchedService to execute tasks. */ public class HashSvcSchedImpl extends BaseLockssDaemonManager implements HashService, ConfigurableManager { protected static Logger log = Logger.getLogger("HashSvcSchedImpl"); public static final String HASH_STATUS_TABLE = "HashQ"; private SchedService sched = null; private long estPadConstant = 0; private long estPadPercent = 0; private List queue = new LinkedList(); private HistoryList completed = new HistoryList(DEFAULT_COMPLETED_MAX); // lock object for both queue and completed private Object queueLock = new Object(); private int hashStepBytes = DEFAULT_STEP_BYTES; private BigInteger totalBytesHashed = BigInteger.valueOf(0); private int reqCtr = 0; private long totalTime = 0; private long nameHashEstimate = DEFAULT_NAME_HASH_ESTIMATE; public HashSvcSchedImpl() {} /** * start the hash service. * @see org.lockss.app.LockssManager#startService() */ public void startService() { super.startService(); log.debug("startService()"); sched = getDaemon().getSchedService(); StatusService statSvc = getDaemon().getStatusService(); statSvc.registerStatusAccessor(HASH_STATUS_TABLE, new Status()); statSvc.registerOverviewAccessor(HASH_STATUS_TABLE, new HashOverview()); } /** * stop the hash service * @see org.lockss.app.LockssManager#stopService() */ public void stopService() { StatusService statSvc = getDaemon().getStatusService(); statSvc.unregisterStatusAccessor(HASH_STATUS_TABLE); statSvc.unregisterOverviewAccessor(HASH_STATUS_TABLE); super.stopService(); } public void setConfig(Configuration config, Configuration prevConfig, Configuration.Differences changedKeys) { estPadConstant = config.getLong(PARAM_ESTIMATE_PAD_CONSTANT, DEFAULT_ESTIMATE_PAD_CONSTANT); estPadPercent = config.getLong(PARAM_ESTIMATE_PAD_PERCENT, DEFAULT_ESTIMATE_PAD_PERCENT); hashStepBytes = config.getInt(PARAM_STEP_BYTES, DEFAULT_STEP_BYTES); nameHashEstimate = config.getTimeInterval(PARAM_NAME_HASH_ESTIMATE, DEFAULT_NAME_HASH_ESTIMATE); int cMax = config.getInt(PARAM_COMPLETED_MAX, DEFAULT_COMPLETED_MAX); if (changedKeys.contains(PARAM_COMPLETED_MAX) ) { synchronized (queueLock) { completed.setMax(config.getInt(PARAM_COMPLETED_MAX, cMax)); } } } /** * Ask for the <code>CachedUrlSetHasher</code> to be * executed by the <code>hasher</code> before the expiration of * <code>deadline</code>, and the result provided to the * <code>callback</code>. * @param hasher an instance of a <code>CachedUrlSetHasher</code> * representing a specific <code>CachedUrlSet</code> * and hash type * @param deadline the time by which the callback must have been * called. * @param callback the object whose <code>hashComplete()</code> * method will be called when hashing succeds * or fails. * @param cookie used to disambiguate callbacks * @return <code>true</code> if the request has been queued, * <code>false</code> if the resources to do it are not * available. */ public boolean scheduleHash(CachedUrlSetHasher hasher, Deadline deadline, Callback callback, Object cookie) { HashTask task = new HashTask(hasher, deadline, callback, cookie); return scheduleTask(task); } /** Cancel all hashes on the specified AU. Temporary until a better * cancel mechanism is implemented. * @param au the AU */ public void cancelAuHashes(ArchivalUnit au) { synchronized (queueLock) { for (Iterator iter = queue.listIterator(); iter.hasNext(); ) { HashTask task = (HashTask)iter.next(); if (task.urlset.getArchivalUnit() == au) { task.cancel(); iter.remove(); } } } } /** Return the average hash speed, or -1 if not known. * @param digest the hashing algorithm * @return hash speed in bytes/ms, or -1 if not known */ public int getHashSpeed(MessageDigest digest) { if (sched == null) { throw new IllegalStateException("HashService has not been initialized"); } if (totalTime < 5 * Constants.SECOND) { return -1; } int bpms = totalBytesHashed.divide(BigInteger.valueOf(totalTime)).intValue(); return bpms; } /** Add the configured padding percentage, plus the constant */ public long padHashEstimate(long estimate) { return estimate + ((estimate * estPadPercent) / 100) + estPadConstant; } private boolean scheduleTask(HashTask task) { if (sched == null) { throw new IllegalStateException("HashService has not been initialized"); } task.setOverrunAllowed(true); if (sched.scheduleTask(task)) { task.hashReqSeq = ++reqCtr; synchronized (queueLock) { if (!task.finished) { // Don't put on waiting queue if task has already finished (and // been removed from waiting queue). queue.add(task); } } return true; } else { return false; } } /** Test whether a hash request could be successfully sceduled before a * given deadline. * @param duration the estimated hash time needed. * @param when the deadline * @return true if such a request could be accepted into the scedule. */ public boolean canHashBeScheduledBefore(long duration, Deadline when) { return sched.isTaskSchedulable(new DummyTask(when, duration)); } /** Return true if the HashService has nothing to do. Useful in unit * tests. */ public boolean isIdle() { return queue.isEmpty(); } List getQueueSnapshot() { synchronized (queueLock) { return new ArrayList(queue); } } List getCompletedSnapshot() { synchronized (queueLock) { return new ArrayList(completed); } } // HashTask class HashTask extends StepTask { CachedUrlSet urlset; HashService.Callback hashCallback; CachedUrlSetHasher urlsetHasher; int hashReqSeq = -1; boolean finished = false; long bytesHashed = 0; long unaccountedBytesHashed = 0; String typeString; boolean isRecalcEstimateHash = false; HashTask(CachedUrlSetHasher urlsetHasher, Deadline deadline, HashService.Callback hashCallback, Object cookie) { super(Deadline.in(0), deadline, urlsetHasher.getEstimatedHashDuration(), new TaskCallback() { public void taskEvent(SchedulableTask task, Schedule.EventType event) { if (log.isDebug2()) log.debug2("taskEvent: " + event); if (event == Schedule.EventType.FINISH) { ((HashTask)task).doFinished(); } } }, cookie); this.urlset = urlsetHasher.getCachedUrlSet(); this.hashCallback = hashCallback; this.urlsetHasher = urlsetHasher; typeString = urlsetHasher.typeString(); isRecalcEstimateHash = typeString.startsWith("E"); } public String typeString() { // this must not reference the urlsetHasher, as it might have been // reset to null return typeString; } public int step(int n) { try { int res = urlsetHasher.hashStep(hashStepBytes); bytesHashed += res; unaccountedBytesHashed += res; return res; } catch (RuntimeException e) { log.error("hashStep threw", e); throw e; } catch (Exception e) { log.error("hashStep threw", e); throw new RuntimeException(e.toString(), e); } } protected void updateStats() { totalTime += unaccountedTime; totalBytesHashed = totalBytesHashed.add(BigInteger.valueOf(unaccountedBytesHashed)); unaccountedBytesHashed = 0; super.updateStats(); } public boolean isFinished() { return super.isFinished() || urlsetHasher.finished(); } private void doFinished() { finished = true; long timeUsed = getTimeUsed(); try { if (!urlsetHasher.finished()) { urlsetHasher.abortHash(); } urlsetHasher.storeActualHashDuration(timeUsed, getException()); } catch (Exception e) { log.error("Hasher threw", e); } if (hashCallback != null) { try { hashCallback.hashingFinished(urlset, timeUsed, cookie, urlsetHasher, e); } catch (Exception e) { log.error("Hash callback threw", e); } } // completed list for status only, don't hold on to caller's objects hashCallback = null; cookie = null; urlsetHasher = null; synchronized (queueLock) { queue.remove(this); completed.add(this); } } public String getShortText() { if (hashReqSeq != -1) { return "Hash " + hashReqSeq; } else { return "Hash"; } } Object getState(boolean done) { if (!done) { return isStepping() ? TASK_STATE_RUN : TASK_STATE_WAIT; } if (getException() == null) { return TASK_STATE_DONE; } else if (getException() instanceof SchedService.Timeout) { if (isRecalcEstimateHash) { // XXX add status accessor to Hasher interface return TASK_STATE_RECALC_UNFINISHED; } else { return TASK_STATE_TIMEOUT; } } else { return TASK_STATE_ERROR; } } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[HTask:"); sb.append(urlset); toStringCommon(sb); sb.append("]"); return sb.toString(); } } static class DummyTask extends StepTask { DummyTask(Deadline deadline, long estimatedDuration) { super(Deadline.in(0), deadline, estimatedDuration, null, null); } public int step(int n) { return 0; } } // status table private static final List statusSortRules = ListUtil.list(new StatusTable.SortRule("state", true), new StatusTable.SortRule("sort", true), new StatusTable.SortRule("sort2", true)); static final String FOOT_IN = "Order in which requests were made."; static final String FOOT_OVER = "Red indicates overrun."; static final String FOOT_TITLE = "Pending requests are first in table, in the order they will be executed."+ " Completed requests follow, in reverse completion order " + "(most recent first)."; private static final List statusColDescs = ListUtil.list( new ColumnDescriptor("sched", "Req", ColumnDescriptor.TYPE_INT, FOOT_IN), new ColumnDescriptor("state", "State", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("au", "Volume", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("cus", "Cached Url Set", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("type", "Type", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("deadline", "Deadline", ColumnDescriptor.TYPE_DATE), new ColumnDescriptor("estimate", "Estimated", ColumnDescriptor.TYPE_TIME_INTERVAL), new ColumnDescriptor("timeused", "Used", ColumnDescriptor.TYPE_TIME_INTERVAL, FOOT_OVER), new ColumnDescriptor("bytesHashed", "Bytes<br>Hashed", ColumnDescriptor.TYPE_INT), new ColumnDescriptor("rate", "Bytes/ms", ColumnDescriptor.TYPE_STRING) ); private static final NumberFormat fmt_2dec = new DecimalFormat("0.00"); private static final BigInteger big1000 = BigInteger.valueOf(1000); private class Status implements StatusAccessor { public String getDisplayName() { return "Hash Queue"; } public void populateTable(StatusTable table) { table.setResortable(false); String key = table.getKey(); table.setTitleFootnote(FOOT_TITLE); if (!table.getOptions().get(StatusTable.OPTION_NO_ROWS)) { table.setColumnDescriptors(statusColDescs); table.setDefaultSortRules(statusSortRules); table.setRows(getRows(key)); } table.setSummaryInfo(getSummaryInfo(key)); } public boolean requiresKey() { return false; } private List getRows(String key) { List table = new ArrayList(); int ix = 0; for (ListIterator iter = getQueueSnapshot().listIterator(); iter.hasNext();) { table.add(makeRow((HashTask)iter.next(), false, ix++)); } for (ListIterator iter = getCompletedSnapshot().listIterator(); iter.hasNext();) { Map row = makeRow((HashTask)iter.next(), true, 0); // if both parts of the table are present (ix is number of pending // requests), add a separator before the first displayed completed // request (which is the last one in the history list) if (ix != 0 && !iter.hasNext()) { row.put(StatusTable.ROW_SEPARATOR, ""); } table.add(row); } return table; } private Map makeRow(HashTask task, boolean done, int qpos) { Map row = new HashMap(); row.put("sort", new Long((done ? -task.getFinishDate().getTime() : task.getLatestFinish().getExpiration().getTime()))); row.put("sort2", new Long(task.hashReqSeq)); row.put("sched", new Integer(task.hashReqSeq)); row.put("state", task.getState(done)); row.put("au", task.urlset.getArchivalUnit().getName()); row.put("cus", task.urlset.getSpec()); row.put("type", task.typeString()); row.put("deadline", task.getLatestFinish()); row.put("estimate", new Long(task.getOrigEst())); long timeUsed = task.getTimeUsed(); Object used = new Long(timeUsed); if (task.hasOverrun()) { StatusTable.DisplayedValue val = new StatusTable.DisplayedValue(used); val.setColor("red"); used = val; } row.put("timeused", used); row.put("bytesHashed", new Long(task.bytesHashed)); if (timeUsed > 0 && task.bytesHashed > 0) { row.put("rate", hashRate(BigInteger.valueOf(task.bytesHashed), timeUsed)); } return row; } private List getSummaryInfo(String key) { List res = new ArrayList(); res.add(new StatusTable.SummaryInfo("Total bytes hashed", ColumnDescriptor.TYPE_INT, totalBytesHashed)); res.add(new StatusTable.SummaryInfo("Total hash time", ColumnDescriptor.TYPE_TIME_INTERVAL, new Long(totalTime))); if (totalTime != 0) { res.add(new StatusTable.SummaryInfo("Bytes/ms", ColumnDescriptor.TYPE_STRING, hashRate(totalBytesHashed, totalTime))); } return res; } } String hashRate(BigInteger bytes, long time) { BigInteger bigTotal = BigInteger.valueOf(time); long bpms = bytes.divide(bigTotal).intValue(); if (bpms >= 100) { return Long.toString(bpms); } else { long bpsec = bytes.multiply(big1000).divide(bigTotal).intValue(); return fmt_2dec.format((double)bpsec / (double)1000); } } static NumberFormat bigIntFmt = NumberFormat.getInstance(); class HashOverview implements OverviewAccessor { public Object getOverview(String tableName, BitSet options) { List res = new ArrayList(); String bytes = bigIntFmt.format(totalBytesHashed) + " bytes hashed"; res.add(bytes); if (totalTime != 0) { res.add(" in " + StringUtil.timeIntervalToString(totalTime)); res.add(" at " + hashRate(totalBytesHashed, totalTime) + " bytes/ms"); } int wait = queue.size(); if (wait != 0) { res.add(wait + " waiting"); } String summ = StringUtil.separatedString(res, ", "); return new StatusTable.Reference(summ, HASH_STATUS_TABLE); } } static class TaskState implements Comparable { String name; int order; TaskState(String name, int order) { this.name = name; this.order = order; } public int compareTo(Object o) { return order - ((TaskState)o).order; } public String toString() { return name; } } static final TaskState TASK_STATE_RUN = new TaskState("Run", 1); static final TaskState TASK_STATE_WAIT = new TaskState("Wait", 2); static final TaskState TASK_STATE_DONE = new TaskState("Done", 3); static final StatusTable.DisplayedValue TASK_STATE_TIMEOUT = new StatusTable.DisplayedValue(new TaskState("Timeout", 3)) .setColor("red"); static final StatusTable.DisplayedValue TASK_STATE_RECALC_UNFINISHED = new StatusTable.DisplayedValue(new TaskState("Recalc Not Done", 3)) .setColor("orange"); static final StatusTable.DisplayedValue TASK_STATE_ERROR = new StatusTable.DisplayedValue(new TaskState("Error", 3)) .setColor("red"); }
31.985915
79
0.679877
9f6b3429f968241e2939887dc69c402cc0bad659
7,430
/* TestBatteryProfile.java Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.deviceplugin.test.profile; import org.deviceconnect.android.message.MessageUtils; import org.deviceconnect.android.profile.BatteryProfile; import org.deviceconnect.message.DConnectMessage; import android.content.Intent; import android.os.Bundle; /** * JUnit用テストデバイスプラグイン、Batteryプロファイル. * * @author NTT DOCOMO, INC. */ public class TestBatteryProfile extends BatteryProfile { /** * バッテリー充電時間を定義する. */ public static final double CHARGING_TIME = 50000; /** * バッテリー放電時間を定義する. */ public static final double DISCHARGING_TIME = 10000; /** * バッテリーレベルを定義する. */ public static final double LEVEL = 0.5; /** * バッテリー充電フラグを定義する. */ public static final boolean CHARGING = false; /** * サービスIDをチェックする. * * @param serviceId サービスID * @return <code>serviceId</code>がテスト用サービスIDに等しい場合はtrue、そうでない場合はfalse */ private boolean checkServiceId(final String serviceId) { return TestServiceDiscoveryProfile.SERVICE_ID.equals(serviceId); } /** * サービスIDが空の場合のエラーを作成する. * * @param response レスポンスを格納するIntent */ private void createEmptyServiceId(final Intent response) { MessageUtils.setEmptyServiceIdError(response, "Service ID is empty."); } /** * デバイスが発見できなかった場合のエラーを作成する. * * @param response レスポンスを格納するIntent */ private void createNotFoundService(final Intent response) { MessageUtils.setNotFoundServiceError(response, "Service is not found."); } @Override protected boolean onGetAll(final Intent request, final Intent response, final String serviceId) { if (serviceId == null) { createEmptyServiceId(response); } else if (!checkServiceId(serviceId)) { createNotFoundService(response); } else { setResult(response, DConnectMessage.RESULT_OK); setCharging(response, CHARGING); setChargingTime(response, CHARGING_TIME); setDischargingTime(response, DISCHARGING_TIME); setLevel(response, LEVEL); } return true; } @Override protected boolean onGetCharging(final Intent request, final Intent response, final String serviceId) { if (serviceId == null) { createEmptyServiceId(response); } else if (!checkServiceId(serviceId)) { createNotFoundService(response); } else { setResult(response, DConnectMessage.RESULT_OK); setCharging(response, CHARGING); } return true; } @Override protected boolean onGetDischargingTime(final Intent request, final Intent response, final String serviceId) { if (serviceId == null) { createEmptyServiceId(response); } else if (!checkServiceId(serviceId)) { createNotFoundService(response); } else { setResult(response, DConnectMessage.RESULT_OK); setDischargingTime(response, DISCHARGING_TIME); } return true; } @Override protected boolean onGetChargingTime(final Intent request, final Intent response, final String serviceId) { if (serviceId == null) { createEmptyServiceId(response); } else if (!checkServiceId(serviceId)) { createNotFoundService(response); } else { setResult(response, DConnectMessage.RESULT_OK); setChargingTime(response, CHARGING_TIME); } return true; } @Override protected boolean onGetLevel(final Intent request, final Intent response, final String serviceId) { if (serviceId == null) { createEmptyServiceId(response); } else if (!checkServiceId(serviceId)) { createNotFoundService(response); } else { setResult(response, DConnectMessage.RESULT_OK); setLevel(response, LEVEL); } return true; } @Override protected boolean onPutOnChargingChange(final Intent request, final Intent response, final String serviceId, final String sessionKey) { if (serviceId == null) { createEmptyServiceId(response); } else if (!checkServiceId(serviceId)) { createNotFoundService(response); } else if (sessionKey == null) { MessageUtils.setInvalidRequestParameterError(response); } else { setResult(response, DConnectMessage.RESULT_OK); Intent message = MessageUtils.createEventIntent(); setSessionKey(message, sessionKey); setServiceID(message, serviceId); setProfile(message, getProfileName()); setAttribute(message, ATTRIBUTE_ON_CHARGING_CHANGE); Bundle charging = new Bundle(); setCharging(charging, false); setBattery(message, charging); Util.sendBroadcast(getContext(), message); } return true; } @Override protected boolean onDeleteOnChargingChange(final Intent request, final Intent response, final String serviceId, final String sessionKey) { if (serviceId == null) { createEmptyServiceId(response); } else if (!checkServiceId(serviceId)) { createNotFoundService(response); } else if (sessionKey == null) { MessageUtils.setInvalidRequestParameterError(response); } else { setResult(response, DConnectMessage.RESULT_OK); } return true; } @Override protected boolean onPutOnBatteryChange(final Intent request, final Intent response, final String serviceId, final String sessionKey) { if (serviceId == null) { createEmptyServiceId(response); } else if (!checkServiceId(serviceId)) { createNotFoundService(response); } else if (sessionKey == null) { MessageUtils.setInvalidRequestParameterError(response); } else { setResult(response, DConnectMessage.RESULT_OK); Intent message = MessageUtils.createEventIntent(); setSessionKey(message, sessionKey); setServiceID(message, serviceId); setProfile(message, getProfileName()); setAttribute(message, ATTRIBUTE_ON_BATTERY_CHANGE); Bundle battery = new Bundle(); setChargingTime(battery, CHARGING_TIME); setDischargingTime(battery, DISCHARGING_TIME); setLevel(battery, LEVEL); setBattery(message, battery); Util.sendBroadcast(getContext(), message); } return true; } @Override protected boolean onDeleteOnBatteryChange(final Intent request, final Intent response, final String serviceId, final String sessionKey) { if (serviceId == null) { createEmptyServiceId(response); } else if (!checkServiceId(serviceId)) { createNotFoundService(response); } else if (sessionKey == null) { MessageUtils.setInvalidRequestParameterError(response); } else { setResult(response, DConnectMessage.RESULT_OK); } return true; } }
33.61991
115
0.635935
98dcc5266575e8e3a2235a3cb743f3428ca63410
1,972
package no.nav.foreldrepenger.melding.dtomapper; import no.nav.foreldrepenger.fpsak.dto.behandling.BehandlingsresultatDto; import no.nav.foreldrepenger.fpsak.dto.kodeverk.KodeDto; import no.nav.foreldrepenger.melding.behandling.Behandlingsresultat; import no.nav.foreldrepenger.melding.behandling.KonsekvensForYtelsen; import no.nav.foreldrepenger.melding.kodeverk.kodeverdi.BehandlingResultatType; import no.nav.foreldrepenger.melding.vedtak.Vedtaksbrev; import no.nav.foreldrepenger.melding.vilkår.Avslagsårsak; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static no.nav.foreldrepenger.melding.behandling.Behandlingsresultat.builder; public class BehandlingsresultatDtoMapper { public static Behandlingsresultat mapBehandlingsresultatFraDto(BehandlingsresultatDto dto) { Behandlingsresultat.Builder builder = builder(); if (dto.getAvslagsarsak() != null) { builder.medAvslagsårsak(Avslagsårsak.fraKode(dto.getAvslagsarsak().getKode())); } if (dto.getType() != null) { builder.medBehandlingResultatType(BehandlingResultatType.fraKode(dto.getType().getKode())); } builder.medFritekstbrev(dto.getFritekstbrev()) .medOverskrift(dto.getOverskrift()) .medVedtaksbrev(Vedtaksbrev.fraKode(dto.getVedtaksbrev().getKode())) .medAvslagarsakFritekst(dto.getAvslagsarsakFritekst()); List<KonsekvensForYtelsen> konsekvenserForYtelsen = new ArrayList<>(); for (KodeDto kodeDto : dto.getKonsekvenserForYtelsen()) { konsekvenserForYtelsen.add(KonsekvensForYtelsen.fraKode(kodeDto.getKode())); } builder.medKonsekvenserForYtelsen(konsekvenserForYtelsen); builder.medErRevurderingMedUendretUtfall(dto.getErRevurderingMedUendretUtfall()); builder.medSkjæringstidspunkt(Optional.ofNullable(dto.getSkjæringstidspunkt())); return builder.build(); } }
46.952381
103
0.755578
437a020e72d11c292a6859d9d456c72fe92c32ce
510
package com.jspiders.ds.LinkedList; public class Mainmethod { public static void main(String[] args) { SingleLinkedList sl=new SingleLinkedList(1888); sl.insertLinkedList(10,5); sl.insertLinkedList(20,1); sl.insertLinkedList(30,2); sl.insertLinkedList(40,3); sl.insertLinkedList(50,4); sl.traverseLinkedlist(); sl.searchNode(30); sl.deleteNode(5); sl.traverseLinkedlist(); } }
22.173913
51
0.576471
9289bb7e7a25999e2b547829ee7ab66f8a830982
6,545
package com.builtbroken.mc.core.network.netty; import com.builtbroken.jlib.data.vector.IPos3D; import com.builtbroken.mc.api.IWorldPosition; import com.builtbroken.mc.core.Engine; import com.builtbroken.mc.core.network.packet.AbstractPacket; import com.builtbroken.mc.lib.mod.loadable.ILoadable; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.FMLEmbeddedChannel; import cpw.mods.fml.common.network.FMLOutboundHandler; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.Packet; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import com.builtbroken.mc.lib.helper.wrapper.ByteBufWrapper; import com.builtbroken.mc.core.network.packet.PacketEntity; import com.builtbroken.mc.core.network.packet.PacketTile; import com.builtbroken.mc.core.network.packet.PacketType; import java.util.EnumMap; /** * @author tgame14 * @since 26/05/14 */ public class PacketManager implements ILoadable { public final String channel; protected EnumMap<Side, FMLEmbeddedChannel> channelEnumMap; public PacketManager(String channel) { this.channel = channel; } @Deprecated public static void writeData(ByteBuf data, Object... sendData) { new ByteBufWrapper.ByteBufWrapper(data).$less$less$less(sendData); } public static PacketType getPacketFor(Object obj) { if (obj instanceof TileEntity) { return new PacketTile((TileEntity) obj); } if (obj instanceof Entity) { return new PacketEntity((Entity) obj); } return null; } public Packet toMCPacket(AbstractPacket packet) { return channelEnumMap.get(FMLCommonHandler.instance().getEffectiveSide()).generatePacketFrom(packet); } @Override public void preInit() { } @Override public void init() { this.channelEnumMap = NetworkRegistry.INSTANCE.newChannel(channel, new ResonantChannelHandler(), new ResonantPacketHandler()); } @Override public void postInit() { } /** * @param packet the packet to send to the player * @param player the player MP object */ public void sendToPlayer(AbstractPacket packet, EntityPlayerMP player) { //Null check is for JUnit if (channelEnumMap != null) { this.channelEnumMap.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER); this.channelEnumMap.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player); this.channelEnumMap.get(Side.SERVER).writeAndFlush(packet); } else { Engine.error("Packet sent to player[" + player + "]"); } } /** * @param packet the packet to send to the players in the dimension * @param dimId the dimension ID to send to. */ public void sendToAllInDimension(AbstractPacket packet, int dimId) { //Null check is for JUnit if (channelEnumMap != null) { this.channelEnumMap.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.DIMENSION); this.channelEnumMap.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(dimId); this.channelEnumMap.get(Side.SERVER).writeAndFlush(packet); } else { Engine.error("Packet sent to dim[" + dimId + "]"); } } public void sendToAllInDimension(AbstractPacket packet, World world) { sendToAllInDimension(packet, world.provider.dimensionId); } /** * sends to all clients connected to the server * * @param packet the packet to send. */ public void sendToAll(AbstractPacket packet) { //Null check is for JUnit if (channelEnumMap != null) { this.channelEnumMap.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL); this.channelEnumMap.get(Side.SERVER).writeAndFlush(packet); } else { Engine.error("Packet sent to all"); } } public void sendToAllAround(AbstractPacket message, NetworkRegistry.TargetPoint point) { //Null check is for JUnit if (channelEnumMap != null) { this.channelEnumMap.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT); this.channelEnumMap.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point); this.channelEnumMap.get(Side.SERVER).writeAndFlush(message); } else { Engine.error("Packet sent to target point: " + point); } } public void sendToAllAround(AbstractPacket message, IWorldPosition point, double range) { sendToAllAround(message, point.world(), point.x(), point.y(), point.z(), range); } public void sendToAllAround(AbstractPacket message, World world, IPos3D point, double range) { sendToAllAround(message, world, point.x(), point.y(), point.z(), range); } public void sendToAllAround(AbstractPacket message, TileEntity tile) { sendToAllAround(message, tile, 64); } public void sendToAllAround(AbstractPacket message, TileEntity tile, double range) { sendToAllAround(message, tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, range); } public void sendToAllAround(AbstractPacket message, World world, double x, double y, double z, double range) { if (world != null) sendToAllAround(message, new NetworkRegistry.TargetPoint(world.provider.dimensionId, x, y, z, range)); } @SideOnly(Side.CLIENT) public void sendToServer(AbstractPacket packet) { //Null check is for JUnit if (channelEnumMap != null) { this.channelEnumMap.get(Side.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER); this.channelEnumMap.get(Side.CLIENT).writeAndFlush(packet); } else { Engine.error("Packet sent to server"); } } }
31.926829
146
0.674255
468da442c700216c94c9d97b78d71c07ccdef39b
1,461
/* * FILE: GridType * Copyright (c) 2015 - 2019 GeoSpark Development Team * * 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.datasyslab.geospark.enums; import java.io.Serializable; // TODO: Auto-generated Javadoc /** * The Enum GridType. */ public enum GridType implements Serializable { /** * The equalgrid. */ EQUALGRID, /** * The hilbert. */ HILBERT, /** * The rtree. */ RTREE, /** * The voronoi. */ VORONOI, /** * The voronoi. */ QUADTREE, /** * K-D-B-tree (k-dimensional B-tree) */ KDBTREE; /** * Gets the grid type. * * @param str the str * @return the grid type */ public static GridType getGridType(String str) { for (GridType me : GridType.values()) { if (me.name().equalsIgnoreCase(str)) { return me; } } return null; } }
20.013699
75
0.602327
e4b697c0bdc0c99d3c05d0e1efa43373dbb3ebd3
554
package stargarth.interpreter; import stargarth.parser.AbstractSyntaxTree; public class AstUtil { private AstUtil() { // TODO Auto-generated constructor stub } public static AbstractSyntaxTree createSimpleAst(String leftValue, String operator, String rightValue) { AbstractSyntaxTree ast = new AbstractSyntaxTree(operator); AbstractSyntaxTree leftNode = new AbstractSyntaxTree(leftValue); AbstractSyntaxTree rightNode = new AbstractSyntaxTree(rightValue); ast.setLeftChild(leftNode); ast.setRightChild(rightNode); return ast; } }
26.380952
105
0.796029
a3d48f4e03bb1c998180a01dcd5b029328afb727
1,097
package tasks.quest1javasyntax.level2.task0219; public class Solution { /* Задача: Да хоть на Луну! - Амиго, ты знал, что сила тяжести на Луне составляет примерно 17% от силы тяжести на Земле? - Нет. - Вот и я не знал. А теперь этой информацией нужно пользоваться часто, и, чтобы не считать каждый раз, реализуй метод getWeight(int), который принимает вес тела (в Ньютонах) на Земле, и возвращает, сколько это тело будет весить на Луне (в Ньютонах). Тип возвращаемого значения - double. Пример: Метод getWeight вызывается с параметром 888. Пример вывода: 150.96 Требования: 1. Метод getWeight(int) должен быть публичным и статическим. 2. Метод getWeight должен возвращать значение типа double. 3. Метод getWeight не должен ничего выводить на экран. 4. Метод getWeight должен правильно переводить вес тела в Ньютонах на Земле в вес этого же тела на Луне, и возвращать это значение. */ public static void main(String[] args) { System.out.println(getWeight(888)); } public static double getWeight(int weightEarth) { return weightEarth*0.17; } }
33.242424
146
0.742935
d851852b2a3f99b8dbe58726653ab03a9f2b4a4e
558
package com.dao; import java.util.ArrayList; import com.model.Food; import com.model.User; public interface FoodDAO { public boolean validateUser(User u); public String giveRole(User u); public boolean addUser(User u); public boolean removeUser(User u); public boolean updateUser(User u); public boolean addFood(Food f); public boolean removeFood(Food f); public boolean removeFoodById(Food f); public boolean updateFood(Food f); public boolean addToCart(User u,Food f); public boolean removeFromCart(User u,Food f); }
24.26087
47
0.738351
0a99a6bf645d12a3d3dc1707af227268243e43ae
176
class Types { public char <caret>method(CharSequence v) { return v.charAt(0); } public void context() { String v = "child type"; char c = v.charAt(0); } }
16
45
0.590909
4d498a294c38d3d2913ef2d0dbab1240f2553606
979
package org.hzero.scheduler.infra.util; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.hzero.scheduler.infra.constant.HsdrConstant; /** * description * * @author shuangfei.zhu@hand-china.com 2020/02/24 10:44 */ public class AddressUtils { private AddressUtils() { } public static String getAddressString(List<String> addressList) { StringBuilder sb = new StringBuilder(); if (CollectionUtils.isEmpty(addressList)) { return StringUtils.EMPTY; } addressList.forEach(item -> sb.append(item).append(HsdrConstant.COMMA)); return sb.substring(0, sb.length() - 1); } public static List<String> getAddressList(String addressStr) { return StringUtils.isNotBlank(addressStr) ? Arrays.asList(addressStr.split(HsdrConstant.COMMA)) : new ArrayList<>(); } }
28.794118
124
0.71093
1655e235467d0ee1db074b4b191c3ee06f10959a
3,245
/* * Copyright 2006-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.consol.citrus.admin.service.spring; import com.consol.citrus.variable.dictionary.DataDictionary; import com.consol.citrus.variable.dictionary.json.JsonMappingDataDictionary; import com.consol.citrus.variable.dictionary.xml.NodeMappingDataDictionary; import com.consol.citrus.variable.dictionary.xml.XpathMappingDataDictionary; import org.junit.Assert; import org.mockito.Mockito; import org.springframework.context.annotation.Bean; import org.springframework.core.io.Resource; import java.io.File; import java.io.IOException; import static org.mockito.Mockito.when; /** * @author Christoph Deppisch */ public class DataDictionaryConfig { @Bean public NodeMappingDataDictionary xmlDataDictionary() { NodeMappingDataDictionary xmlDataDictionary = new NodeMappingDataDictionary(); xmlDataDictionary.setName("xmlDataDictionary"); xmlDataDictionary.getMappings().put("foo.text", "newFoo"); xmlDataDictionary.getMappings().put("bar.text", "newBar"); xmlDataDictionary.setMappingFile(mappingFile()); return xmlDataDictionary; } @Bean public XpathMappingDataDictionary xpathDataDictionary() { XpathMappingDataDictionary xpathDataDictionary = new XpathMappingDataDictionary(); xpathDataDictionary.setName("xpathDataDictionary"); xpathDataDictionary.getMappings().put("//foo/text", "newFoo"); xpathDataDictionary.getMappings().put("//bar/text", "newBar"); xpathDataDictionary.setMappingFile(mappingFile()); xpathDataDictionary.setGlobalScope(false); return xpathDataDictionary; } @Bean public JsonMappingDataDictionary jsonDataDictionary() { JsonMappingDataDictionary jsonDataDictionary = new JsonMappingDataDictionary(); jsonDataDictionary.setName("jsonDataDictionary"); jsonDataDictionary.getMappings().put("foo.text", "newFoo"); jsonDataDictionary.getMappings().put("bar.text", "newBar"); jsonDataDictionary.setMappingFile(mappingFile()); jsonDataDictionary.setPathMappingStrategy(DataDictionary.PathMappingStrategy.ENDS_WITH); return jsonDataDictionary; } private Resource mappingFile() { Resource mappingResource = Mockito.mock(Resource.class); File mappingFile = Mockito.mock(File.class); try { when(mappingResource.getFile()).thenReturn(mappingFile); when(mappingFile.getCanonicalPath()).thenReturn("path/to/some/mapping/file.map"); } catch (IOException e) { Assert.fail(); } return mappingResource; } }
34.157895
96
0.731279
0c3e36d70ed71ff35278a032d44bcefe3ab1b7a0
2,858
package frame.plugin.easyui; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSONObject; public class TreeJson implements Serializable { private static final long serialVersionUID = -3134720687910504403L; private String id; private String pid; private String text; private String iconCls; private String state; private String checked; private JSONObject attributes = new JSONObject(); private List<TreeJson> children = new ArrayList<TreeJson>(); public TreeJson() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getIconCls() { return iconCls; } public void setIconCls(String iconCls) { this.iconCls = iconCls; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getChecked() { return checked; } public void setChecked(String checked) { this.checked = checked; } public JSONObject getAttributes() { return attributes; } public void setAttributes(JSONObject attributes) { this.attributes = attributes; } public List<TreeJson> getChildren() { return children; } public void setChildren(List<TreeJson> children) { this.children = children; } public static List<TreeJson> formatTree(List<TreeJson> list) { TreeJson root = new TreeJson(); TreeJson node = new TreeJson(); List<TreeJson> treelist = new ArrayList<TreeJson>();// 拼凑好的json格式的数据 List<TreeJson> parentnodes = new ArrayList<TreeJson>();// parentnodes存放所有的父节点 if (list != null && list.size() > 0) { root = list.get(0); // 循环遍历oracle树查询的所有节点 for (int i = 1; i < list.size(); i++) { node = list.get(i); if (node.getPid().equals(root.getId())) { // 为tree root 增加子节点 parentnodes.add(node); root.getChildren().add(node); } else {// 获取root子节点的孩子节点 getChildrenNodes(parentnodes, node); parentnodes.add(node); } } } treelist.add(root); return treelist; } private static void getChildrenNodes(List<TreeJson> parentnodes, TreeJson node) { // 循环遍历所有父节点和node进行匹配,确定父子关系 for (int i = parentnodes.size() - 1; i >= 0; i--) { TreeJson pnode = parentnodes.get(i); // 如果是父子关系,为父节点增加子节点,退出for循环 if (pnode.getId().equals(node.getPid())) { pnode.setState("closed");// 关闭二级树 pnode.getChildren().add(node); return; } else { // 如果不是父子关系,删除父节点栈里当前的节点, // 继续此次循环,直到确定父子关系或不存在退出for循环 parentnodes.remove(i); } } } }
21.488722
83
0.651155
35d843e2b7cd761c918ae942f0c056e90770b96d
1,714
package com.tool4us.common.task; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; import com.tool4us.common.Logs; import lib.turbok.task.ITask; import lib.turbok.task.ITaskMonitor; import lib.turbok.task.TaskQueue; public enum JobQueue implements ITaskMonitor { JQ; private TaskQueue _taskMgr = null; private Map<String, Integer> _working = null; private JobQueue() { _taskMgr = new TaskQueue(this); _working = new ConcurrentSkipListMap<String, Integer>(); } public void begin() { _taskMgr.startQueue(4, "treatdb-job-queue"); } public void end() { _taskMgr.endQueue(); } public void pushTask(ITask task) { _taskMgr.pushTask(task); } @Override public boolean isContinuing(ITask task) { // TODO Auto-generated method stub return false; } @Override public void stopTask(ITask task) { // TODO Auto-generated method stub } @Override public void OnStartTask(ITask task) { // TODO Auto-generated method stub } @Override public boolean OnProgress(ITask task, long progress) { // TODO Auto-generated method stub return false; } @Override public void OnEndTask(ITask task) { // TODO } @Override public void OnErrorRaised(ITask task, Throwable e) { if( e instanceof JobException ) { JobException xe = (JobException) e; _working.remove(xe.getKey()); Logs.warn("Error occured: {}", task.toString()); Logs.trace(xe); } } }
18.835165
64
0.592765
a9bd6a7fc0dad3612bf03c4e636f1d29b03023ae
937
package jports.data; import jports.ShowStopper; public class TableRow { private final Table table; private Object[] values; public TableRow(Table table, Object... values) { this.table = table; this.values = values; } public Object get(int ordinal) { return ordinal < 0 || ordinal >= values.length ? null : values[ordinal]; } public Object get(String name) { return get(table.getColumnOrdinal(name)); } public void set(int ordinal, Object value) { if (ordinal < 0 || ordinal >= table.getColumnCount()) { throw new ShowStopper( "Invalid column ordinal: " + ordinal + ". Range is [0," + table.getColumnCount() + "["); } else { values[ordinal] = value; } } public void set(String name, Object value) { set(table.getColumnOrdinal(name), value); } public Table getTable() { return this.table; } public Object[] getValues() { return this.values; } }
18.372549
57
0.643543
e0270aa5dca217d774cd1b66baa6a50725a0a929
1,173
package com.olair.ask_test.gps; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import com.olair.ask.AskTask; /** * 这个类将用于获取定位信息 */ public abstract class AskLocation extends AskTask<LocationListener, Location> { private Location mLocation = null; protected AskLocation(int maxWaitMillis) { super(maxWaitMillis); } @Override protected LocationListener buildListener0() { return new LocationListener() { @Override public void onLocationChanged(Location location) { mLocation = location; postExecute(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; } @Override public boolean isSuccess() { return mLocation != null; } @Override public Location get() { return mLocation; } }
20.946429
85
0.601876
28ba4053fd29c135345909bc402e40a713949295
3,571
package io.github.iamsomraj.inventory.dao; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.logging.FileHandler; import java.util.logging.Logger; import io.github.iamsomraj.inventory.database.DatabaseUtil; import io.github.iamsomraj.inventory.model.OrderItem; import io.github.iamsomraj.inventory.model.PurchaseOrder; import io.github.iamsomraj.inventory.model.StockItem; public class OrderItemDao { Connection conn = DatabaseUtil.createConnection(); private static String tableName = "order_items".toUpperCase(); static Logger logger = Logger.getLogger(OrderItemDao.class.getName()); static { try { logger.addHandler(new FileHandler(OrderItemDao.class.getSimpleName() + "-logs.xml", true)); } catch (SecurityException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void init() { dropOrderItem(); createOrderItem(); } public void createOrderItem() { try { PreparedStatement statement = conn.prepareStatement("" + "" + "CREATE TABLE " + tableName + " (\r\n" + " noOfItems INT(10),\r\n" + " poNumber INT(10),\r\n" + " itemNumber INT(10),\r\n" + " FOREIGN KEY (poNumber)\r\n" + " REFERENCES " + PurchaseOrderDao.getTableName() + " (poNumber),\r\n" + " FOREIGN KEY (itemNumber)\r\n" + " REFERENCES " + StockItemDao.getTableName() + " (itemNumber)\r\n" + ");\r\n" + "" + ""); statement.executeUpdate(); System.out.println(tableName + " created!"); } catch (Exception e) { logger.info(e.getMessage()); // System.out.println("Failed to create " + tableName); } } public void dropOrderItem() { try { PreparedStatement statement = conn.prepareStatement("drop table " + tableName); statement.executeUpdate(); System.out.println(tableName + " dropped!"); } catch (Exception e) { logger.info(e.getMessage()); // System.out.println("Failed to drop " + tableName); } } public void insertOrderItem(OrderItem orderItem, PurchaseOrder purchaseOrder) { try { PreparedStatement statement = conn.prepareStatement("insert into " + tableName + " values(?,?,?)"); statement.setInt(1, orderItem.getNumberOfItems()); statement.setInt(2, purchaseOrder.getPoNumber()); statement.setInt(3, orderItem.getStockItem().getItemNumber()); statement.executeUpdate(); System.out.println( "Order Item for " + orderItem.getStockItem().getItemDescription() + " is inserted in " + tableName); } catch (Exception e) { logger.info(e.getMessage()); System.out.println("Failed to insert in " + tableName); } } public OrderItem getOrderItemByPurchaseOrderAndStockItem(PurchaseOrder purchaseOrder, StockItem stockItem) { try { Statement statement = conn.createStatement(); String query = "select * from " + tableName + " where poNumber=" + purchaseOrder.getPoNumber() + " and itemNumber=" + stockItem.getItemNumber(); ResultSet rs = statement.executeQuery(query); if (rs.next()) { OrderItem orderItem = new OrderItem(); orderItem.setNumberOfItems(rs.getInt(1)); System.out.println("Order Item with number of items " + orderItem.getNumberOfItems() + ": "); System.out.println("Purchase Order Number: " + rs.getInt(2)); System.out.println("Stock Item Number: " + rs.getInt(3)); return orderItem; } } catch (Exception e) { logger.info(e.getMessage()); System.out.println("Failed to fetch order item from " + tableName); } return null; } }
35.356436
109
0.693363
01653799ee124fb5516e02e94517fd4617c20f2a
420
package ar.edu.unq.cookitbackend.dto.request; import lombok.*; import java.util.List; @Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor public class RecipeDto { private int comensales; private String description; private int time; private String name; private String image_url; private List<IngredientDto> ingredients; private List<StepDto> steps; private Long userId; }
23.333333
63
0.747619
71dd607fec34dc1b284cace4b859f86b49a0bb17
6,020
package org.ckan.client.localidata; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.net.ssl.HttpsURLConnection; import org.apache.commons.logging.Log; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.ckan.client.Connection; import org.pentaho.di.core.logging.LogChannelInterface; import com.google.gson.Gson; public class ResourceUtils { private static final String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"; private static SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); public static synchronized String updateResource(Connection ckanConnection,String idResource, String dataSetId, String path, String label, String format, String description, int timeout) throws Exception { //update StringBuffer sb = new StringBuffer(); Map<String, String> headers = new HashMap<String, String>(); headers.put("X-CKAN-API-Key", ckanConnection.getApiKey()); String url = ckanConnection.getM_host() + "/api/action/resource_update"; URL targetUrl = new URL(url); HttpURLConnection connection = null; if (url.startsWith("https")){ connection = (HttpsURLConnection) targetUrl.openConnection(); }else{ connection = (HttpURLConnection) targetUrl.openConnection(); } connection.setDoOutput(true); connection.setRequestMethod("POST"); File upload = new File(path); FileBody fileBody = new FileBody(upload); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("upload", fileBody); multipartEntity.addPart("id", new StringBody(idResource)); multipartEntity.addPart("package_id", new StringBody(dataSetId)); multipartEntity.addPart("name", new StringBody(label)); multipartEntity.addPart("format", new StringBody(format)); multipartEntity.addPart("description", new StringBody(description)); multipartEntity.addPart("last_modified", new StringBody(dateFormat.format(new Date()))); //Esta linea de abajo es para que funcione con CKAN 2.5.2 multipartEntity.addPart("url", new StringBody("")); connection.setRequestProperty("X-CKAN-API-Key", ckanConnection.getApiKey()); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); connection.setReadTimeout(timeout); OutputStream out = connection.getOutputStream(); boolean error=false; try { multipartEntity.writeTo(out); } catch (Exception e) { error=true; e.printStackTrace(); } finally { out.close(); } if (error){ throw new Exception("Error uploading resource"); } BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((connection.getInputStream()))); String output; while ((output = responseBuffer.readLine()) != null) { sb.append(output); } return sb.toString(); } public static synchronized boolean createResource(Connection ckanConnection, String dataSetId, String path, String label, String format, String description, int timeout) throws Exception { StringBuffer sb = new StringBuffer(); Map<String, String> headers = new HashMap<String, String>(); headers.put("X-CKAN-API-Key", ckanConnection.getApiKey()); String url = ckanConnection.getM_host() + "/api/action/resource_create"; URL targetUrl = new URL(url); HttpURLConnection connection=null; if (url.startsWith("https")){ connection = (HttpsURLConnection) targetUrl.openConnection(); }else{ connection = (HttpURLConnection) targetUrl.openConnection(); } connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); File upload = new File(path); FileBody fileBody = new FileBody(upload); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("upload", fileBody); multipartEntity.addPart("package_id", new StringBody(dataSetId)); multipartEntity.addPart("name", new StringBody(label)); multipartEntity.addPart("format", new StringBody(format)); multipartEntity.addPart("description", new StringBody(description)); multipartEntity.addPart("last_modified", new StringBody(dateFormat.format(new Date()))); //Esta linea de abajo es para que funcione con CKAN 2.5.2 multipartEntity.addPart("url", new StringBody("")); connection.setRequestProperty("X-CKAN-API-Key", ckanConnection.getApiKey()); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); OutputStream out = null; boolean error=false; try { out = connection.getOutputStream(); multipartEntity.writeTo(out); } catch (Exception e) { error=true; e.printStackTrace(); } finally { if ((out!=null)) { out.close(); } } if (error){ throw new Exception("Error uploading resource"); } BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((connection.getInputStream()))); String output; while ((output = responseBuffer.readLine()) != null) { sb.append(output); } Boolean success = new Boolean("false"); Gson gson=new Gson(); try { HashMap hm = gson.fromJson(sb.toString(),HashMap.class); if (hm.get("success")!=null) success = (Boolean)hm.get("success"); } catch (Exception e){} return success.booleanValue(); } }
27.741935
206
0.730233
be9fc244605c84015f1ae2f1be5fb9599a7c9bdd
895
package com.github.sormuras.bach.internal; import java.lang.module.ModuleFinder; import java.lang.module.ModuleReference; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.Set; public record ModuleInfoFinder(List<ModuleInfoReference> references) implements ModuleFinder { public static ModuleInfoFinder of(Path root) { var infos = PathSupport.find(root, 99, PathSupport::isModuleInfoJavaFile); var references = infos.stream().map(ModuleInfoReference::new).toList(); return new ModuleInfoFinder(references); } @Override public Optional<ModuleReference> find(String name) { return references.stream() .filter(reference -> reference.name().equals(name)) .map(ModuleReference.class::cast) .findFirst(); } @Override public Set<ModuleReference> findAll() { return Set.copyOf(references); } }
28.870968
94
0.740782
4932bfa2e0979792ea348f457f5c4ef804543904
1,166
// Part of SourceAFIS for Java: https://sourceafis.machinezoo.com/java package com.machinezoo.sourceafis.engine.images; import com.machinezoo.sourceafis.engine.configuration.*; /* * This decoder uses Android's Bitmap class to decode templates. * Note that Bitmap class will not work in unit tests. It only works inside a full-blown emulator. * * Since direct references of Android libraries would not compile, * we will reference BitmapFactory and Bitmap via reflection. */ class AndroidImageDecoder extends ImageDecoder { @Override public boolean available() { return PlatformCheck.hasClass("android.graphics.BitmapFactory"); } @Override public String name() { return "Android"; } @Override public DecodedImage decode(byte[] image) { AndroidBitmap bitmap = AndroidBitmapFactory.decodeByteArray(image, 0, image.length); if (bitmap.instance == null) throw new IllegalArgumentException("Unsupported image format."); int width = bitmap.getWidth(); int height = bitmap.getHeight(); int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); return new DecodedImage(width, height, pixels); } }
34.294118
98
0.752144
366b827fa3ad07e0431dff79fcad206b44b2e981
953
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package by.creepid.docgeneration; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * * @author rusakovich */ @Component public final class ContextHelper implements ApplicationContextAware { private static volatile ApplicationContext context; private ContextHelper() { } @Override public void setApplicationContext(ApplicationContext context) { ContextHelper.context = context; } public static <T> T getbean(Class<T> requiredType) { return context.getBean(requiredType); } public static <T> T getBean(String string, Class<T> type) { return context.getBean(string, type); } }
25.078947
79
0.734523
e2e8298521ea3f38de321daa1db25d9f07e8b7fe
1,348
package com.sportmonks.data.entity; import com.fasterxml.jackson.annotation.*; import java.util.HashMap; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"total", "home", "away"}) public class TeamSeasonStatsRow { @JsonProperty("total") private Integer total; @JsonProperty("home") private Integer home; @JsonProperty("away") private Integer away; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("total") public Integer getTotal() { return total; } @JsonProperty("total") public void setTotal(Integer total) { this.total = total; } @JsonProperty("home") public Integer getHome() { return home; } @JsonProperty("home") public void setHome(Integer home) { this.home = home; } @JsonProperty("away") public Integer getAway() { return away; } @JsonProperty("away") public void setAway(Integer away) { this.away = away; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
22.098361
85
0.652077
f12853262f14128e138e62366f389b36f720723d
1,175
package com.atjl.dbfront.domain.biz; import java.io.Serializable; public class ContentDomain implements Serializable{ private static final long serialVersionUID = 3807318977050002077L; private String cname; private String ctype; private String cversion; private String content; private String preVersion; public ContentDomain(){ super(); } public String getPreVersion() { return preVersion; } public void setPreVersion(String preVersion) { this.preVersion = preVersion; } public String getCversion() { return cversion; } public void setCversion(String cversion) { this.cversion = cversion; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public String getCtype() { return ctype; } public void setCtype(String ctype) { this.ctype = ctype; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
20.258621
68
0.605957
d1cc436614ad0b41883608e33f9fdd6efd666a55
3,517
package com.java.barcode; import com.dynamsoft.barcode.*; import com.google.zxing.BinaryBitmap; import com.google.zxing.MultiFormatReader; import com.google.zxing.NotFoundException; import com.google.zxing.RGBLuminanceSource; import com.google.zxing.Result; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.multi.*; import java.io.File; import java.io.IOException; import java.awt.image.*; import javax.imageio.ImageIO; public class App { public void decodefile(String filename) { // Read an image to BufferedImage BufferedImage image = null; try { image = ImageIO.read(new File(filename)); } catch (IOException e) { System.out.println(e); return; } // ZXing BinaryBitmap bitmap = null; int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth()); RGBLuminanceSource source = new RGBLuminanceSource(image.getWidth(), image.getHeight(), pixels); bitmap = new BinaryBitmap(new HybridBinarizer(source)); MultiFormatReader reader = new MultiFormatReader(); GenericMultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader); try { Result[] zxingResults = multiReader.decodeMultiple(bitmap); System.out.println("ZXing result count: " + zxingResults.length); if (zxingResults != null) { for (Result zxingResult : zxingResults) { System.out.println("Format: " + zxingResult.getBarcodeFormat()); System.out.println("Text: " + zxingResult.getText()); System.out.println(); } } } catch (NotFoundException e) { e.printStackTrace(); } pixels = null; bitmap = null; System.out.println("------------------------------------------------------"); // Dynamsoft BarcodeReader br = null; try { // Get license from https://www.dynamsoft.com/CustomerPortal/Portal/Triallicense.aspx br = new BarcodeReader("LICENSE-KEY"); } catch (Exception e) { System.out.println(e); return; } TextResult[] results = null; try { results = br.decodeBufferedImage(image, ""); } catch (Exception e) { System.out.println("decode buffered image: " + e); } if (results != null && results.length > 0) { System.out.println("DBR result count: " + results.length); String pszTemp = null; for (TextResult result : results) { if (result.barcodeFormat != 0) { pszTemp = "Format: " + result.barcodeFormatString; } else { pszTemp = "Format: " + result.barcodeFormatString_2; } System.out.println(pszTemp); System.out.println("Text: " + result.barcodeText); System.out.println(); } } if (image != null) { image.flush(); image = null; } } public static void main( String[] args ) { if (args.length == 0) { System.out.println("Please add an image file"); return; } final String filename = args[0]; App test = new App(); test.decodefile(filename); } }
33.495238
106
0.552175
adb82b7da83bf474c572c91b2727a140975c3097
1,394
package io.github.thachillera.cardsscorekeeper.data.players; class Player { private final long id; private String name; //max 3 chars private String shortName; private boolean deleted = false; private int wins = 0; private int losses = 0; Player(long id, String name, String shortName) throws IllegalArgumentException { this.id = id; setName(name); setShortName(shortName); } long getId() { return id; } String getName() { return name; } private void setName(String name) throws IllegalArgumentException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("No or missing name"); } this.name = name; } String getShortName() { return shortName; } private void setShortName(String shortName) throws IllegalArgumentException { if (shortName == null || shortName.length() == 0 || shortName.length() > 3) { throw new IllegalArgumentException("No, missing or too long name"); } this.shortName = shortName; } void editPlayer(String name, String shortName) throws IllegalArgumentException { setName(name); setShortName(shortName); } boolean isDeleted() { return deleted; } void delete() { deleted = true; } }
22.483871
85
0.608321
14a7ea4e6bf1d70333a80f7e1ed1e5d8f217d5ef
1,806
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2015 the original author or authors. */ package org.assertj.swing.driver; import static org.assertj.swing.query.ComponentHasFocusQuery.hasFocus; import static org.assertj.swing.timing.Pause.pause; import org.assertj.swing.timing.Condition; import org.junit.Test; /** * Tests for {@link ComponentDriver#focus(java.awt.Component)}. * * @author Alex Ruiz * @author Yvonne Wang */ public class ComponentDriver_focus_Test extends ComponentDriver_TestCase { @Test public void should_Give_Focus_To_Component() { showWindow(); driver.focus(window.button); pause(new Condition("Component has focus") { @Override public boolean test() { return hasFocus(window.button); } }); } @Test public void should_Throw_Error_If_Component_Is_Disabled() { disableButton(); thrown.expectIllegalStateIsDisabledComponent(); try { driver.focus(window.button); } finally { assertThatButtonDoesNotHaveFocus(); } } @Test public void should_Throw_Error_If_Component_Is_Not_Showing_On_The_Screen() { thrown.expectIllegalStateIsNotShowingComponent(); try { driver.focus(window.button); } finally { assertThatButtonDoesNotHaveFocus(); } } }
29.606557
118
0.728682
5204fc41409bae89379a8f0e63a91e8072653763
9,445
/*- * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.onap.policy.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; import com.att.research.xacml.api.pap.PAPException; import java.awt.Checkbox; import java.util.Set; import org.junit.Test; import org.mockito.Mockito; import org.onap.policy.rest.util.PolicyContainer.ItemSetChangeListener; import org.onap.policy.xacml.api.pap.OnapPDP; import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; public class PDPGroupContainerTest { private OnapPDPGroup group = Mockito.mock(OnapPDPGroup.class); private OnapPDPGroup newGroup = Mockito.mock(OnapPDPGroup.class); private OnapPDP pdp = Mockito.mock(OnapPDP.class); private PAPPolicyEngine engine = Mockito.mock(PAPPolicyEngine.class); private PDPGroupContainer container = new PDPGroupContainer(engine); @Test public void testContainer() throws PAPException { Object itemId = new Object(); assertEquals(container.isSupported(itemId), false); container.refreshGroups(); assertEquals(container.getGroups().size(), 0); container.makeDefault(group); container.removeGroup(group, newGroup); container.updatePDP(pdp); container.updateGroup(group); container.updateGroup(group, "testUserName"); assertNull(container.getContainerPropertyIds()); assertEquals(container.getItemIds().size(), 0); assertEquals(container.getType(itemId), null); assertEquals(container.size(), 0); assertEquals(container.containsId(itemId), false); String name = "testName"; String description = "testDescription"; container.addNewGroup(name, description); String id = "testID"; int jmxport = 0; container.addNewPDP(id, newGroup, name, description, jmxport); container.movePDP(pdp, newGroup); ItemSetChangeListener listener = null; container.addItemSetChangeListener(listener); container.nextItemId(itemId); container.prevItemId(itemId); container.firstItemId(); container.lastItemId(); container.isFirstId(itemId); container.isLastId(itemId); container.indexOfId(itemId); assertEquals(container.getItemIds().size(), 0); container.removeItem(itemId); container.removePDP(pdp, newGroup); } @Test(expected = UnsupportedOperationException.class) public void testAddItem() { container.addItem(); } @Test(expected = UnsupportedOperationException.class) public void testAddContainerProperty() { container.addContainerProperty(null, null, null); } @Test(expected = UnsupportedOperationException.class) public void testRemoveContainerProperty() { container.removeContainerProperty(null); } @Test(expected = UnsupportedOperationException.class) public void testRemoveAllItems() { container.removeAllItems(); } @Test(expected = UnsupportedOperationException.class) public void testAddItemAfter() { container.addItemAfter(null); } @Test(expected = IndexOutOfBoundsException.class) public void testGetIdByIndexException() { container.getIdByIndex(0); } @Test(expected = UnsupportedOperationException.class) public void testAddItemAt() { container.addItemAt(0); } @Test(expected = IllegalArgumentException.class) public void testGetItemIdsException() { container.getItemIds(0, 1); } @Test public void testGetType() { assertEquals(Boolean.class, container.getType("Default")); assertEquals(Checkbox.class, container.getType("Selected")); assertEquals(Set.class, container.getType("PDPs")); assertEquals(Set.class, container.getType("Policies")); assertEquals(Set.class, container.getType("PIP Configurations")); assertEquals(String.class, container.getType("Id")); assertEquals(String.class, container.getType("Name")); assertEquals(String.class, container.getType("Description")); assertEquals(String.class, container.getType("Status")); } @Test public void testContainerPAPExceptions() throws PAPException { doThrow(PAPException.class).when(engine).getOnapPDPGroups(); container.refreshGroups(); doThrow(PAPException.class).when(engine).setDefaultGroup(group); container.makeDefault(group); doThrow(PAPException.class).when(engine).updatePDP(pdp); container.updatePDP(pdp); doThrow(PAPException.class).when(engine).updateGroup(group); container.updateGroup(group); doThrow(PAPException.class).when(engine).updateGroup(group, "testUserName"); container.updateGroup(group, "testUserName"); doThrow(PAPException.class).when(engine).movePDP(pdp, group); container.movePDP(pdp, group); } @Test(expected = PAPException.class) public void testContainerRemoveGroup() throws PAPException { doThrow(PAPException.class).when(engine).removeGroup(group, newGroup); container.removeGroup(group, newGroup); } @Test(expected = PAPException.class) public void testContainerRemovePDP() throws PAPException { doThrow(PAPException.class).when(engine).removePDP(pdp); container.removePDP(pdp, group); } @Test(expected = UnsupportedOperationException.class) public void testRemoveDefaultGroup() throws PAPException { when(group.isDefaultGroup()).thenReturn(true); container.removeGroup(group, newGroup); } @Test public void testGetItemIds() { assertNotNull(container.getItemIds(0, 0)); } @Test public void testContainsId() { assertFalse(container.containsId(group)); } @Test public void testGroupMethods() { container.groups.add(group); Object retObj = container.getIdByIndex(0); assertTrue(retObj instanceof OnapPDPGroup); assertNotNull(retObj); Object retFirstItemId = container.firstItemId(); assertTrue(retFirstItemId instanceof OnapPDPGroup); assertNotNull(retFirstItemId); Object retLastItemId = container.lastItemId(); assertTrue(retLastItemId instanceof OnapPDPGroup); assertNotNull(retLastItemId); assertTrue(container.isFirstId(group)); assertTrue(container.isLastId(group)); } @Test public void testNextItemId() { OnapPDPGroup groupNotInList = Mockito.mock(OnapPDPGroup.class); Object retObj = null; container.groups.add(group); container.groups.add(newGroup); assertNull(container.nextItemId(groupNotInList)); assertNull(container.nextItemId(newGroup)); retObj = container.nextItemId(group); assertNotNull(retObj); assertTrue(retObj instanceof OnapPDPGroup); } @Test public void testPrevItemId() { OnapPDPGroup groupNotInList = Mockito.mock(OnapPDPGroup.class); Object retObj = null; container.groups.add(group); container.groups.add(newGroup); assertNull(container.prevItemId(groupNotInList)); assertNull(container.prevItemId(group)); retObj = container.prevItemId(newGroup); assertNotNull(retObj); assertTrue(retObj instanceof OnapPDPGroup); } @Test public void testRemoveNullItem() { OnapPDPGroup nullGroup = null; assertFalse(container.removeItem(nullGroup)); } @Test(expected = UnsupportedOperationException.class) public void testRemoveDefaultItem() { when(group.getId()).thenReturn("Default"); container.removeItem(group); } @SuppressWarnings("unchecked") @Test public void testRemoveItem() throws PAPException { assertTrue(container.removeItem(group)); PAPPolicyEngine mockPAPPolicyEngine = Mockito.mock(PAPPolicyEngine.class); PDPGroupContainer groupContainer = new PDPGroupContainer(mockPAPPolicyEngine); when(mockPAPPolicyEngine.getDefaultGroup()).thenThrow(PAPException.class); assertFalse(groupContainer.removeItem(group)); } }
35.641509
86
0.677819
17d449b79338e35487c4694d50dad2bad3636e28
269
package com.bergerkiller.bukkit.common.controller; /** * The network controller returned for the default, unchanged types of entity network controller. */ @SuppressWarnings("rawtypes") public class DefaultEntityNetworkController extends EntityNetworkController { }
26.9
97
0.814126
1e92e413c74d0b6646fe0756f210821ac672c167
830
package com.ruoyi.fac.model; import com.ruoyi.common.annotation.Excel; import lombok.Data; import java.util.Date; @Data public class FacLeaveMessage { @Excel(name = "留言ID") private Long id; private String token; @Excel(name = "留言用户昵称") private String nickName; @Excel(name = "留言时间", dateFormat = "yyyy-MM-dd HH:mm:ss") private Date createTime; @Excel(name = "留言内容") private String remark; private String tokenAnswer; @Excel(name = "留言回复") private String mngtRemark; private Boolean status; @Excel(name = "回复时间", dateFormat = "yyyy-MM-dd HH:mm:ss") private Date updateTime; @Excel(name = "操作人") private String operatorName; private Long operatorId; @Excel(name = "数据状态", readConverterExp ="false=正常,true=删除") private Boolean isDeleted; }
20.243902
63
0.666265
53c66b032f21a96c5f3d539987b2db3210c7bdc0
97
package com.sou1fy.dyniamic.ddb; public interface IRouteKeySearcher { Object keySearch(); }
16.166667
36
0.762887
0f87361e3da13f88ab147932a5d55cef2e98bad9
1,032
package com.projectning.service.dao.impl; import java.util.ArrayList; import java.util.List; import com.projectning.util.Util; public class NVPairList { private List < NVPair > pairList; public NVPairList() { this.pairList = new ArrayList < NVPair > (); } public void addValue(String name, Object value) { this.pairList.add(new NVPair(name, value)); } public void addNullableIntValue(String name, Object value) { if((int)value == Util.nullInt){ this.pairList.add(new NVPair(name, null)); }else{ this.pairList.add(new NVPair(name, value)); } } public void addValueNotNull(String paramName, Object value) throws IllegalArgumentException { if (value != null) { this.addValue(paramName, value); } else { throw new IllegalArgumentException(paramName + " must not be null"); } } public void addAll(NVPairList otherList) { this.pairList.addAll(otherList.getList()); } public List < NVPair > getList() { return this.pairList; } public int size() { return this.pairList.size(); } }
22.434783
94
0.706395
4d3aa89092741cfb20e5bfa038b45063d377933d
1,511
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.jvm.kotlin; import static org.hamcrest.Matchers.not; import static org.junit.Assume.assumeNoException; import com.facebook.buck.core.config.BuckConfig; import com.facebook.buck.core.config.FakeBuckConfig; import com.facebook.buck.core.exceptions.HumanReadableException; import com.facebook.buck.util.environment.Platform; import javax.annotation.Nullable; import org.junit.Assume; public abstract class KotlinTestAssumptions { public static void assumeUnixLike() { Assume.assumeThat(Platform.detect(), not(Platform.WINDOWS)); } public static void assumeCompilerAvailable(@Nullable BuckConfig config) { Throwable exception = null; try { new KotlinBuckConfig(config == null ? FakeBuckConfig.empty() : config).getPathToCompilerJar(); } catch (HumanReadableException e) { exception = e; } assumeNoException(exception); } }
34.340909
100
0.755129
0ea1592ecd1b4aa41b7ea368adcb49360510f52c
1,774
package com.elovirta.dita.markdown; import org.dita.dost.util.DitaClass; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import java.util.ArrayDeque; import java.util.Deque; import static javax.xml.XMLConstants.NULL_NS_URI; /** * Serializer to SAX content handler. */ public class SaxSerializer implements Serializer { final Deque<DitaClass> tagStack = new ArrayDeque<>(); protected ContentHandler contentHandler; public void setContentHandler(final ContentHandler contentHandler) { this.contentHandler = contentHandler; } // ContentHandler methods void startElement(final DitaClass tag, final Attributes atts) { try { contentHandler.startElement(NULL_NS_URI, tag.localName, tag.localName, atts); } catch (final SAXException e) { throw new ParseException(e); } tagStack.addFirst(tag); } void endElement() { if (!tagStack.isEmpty()) { endElement(tagStack.removeFirst()); } } private void endElement(final DitaClass tag) { try { contentHandler.endElement(NULL_NS_URI, tag.localName, tag.localName); } catch (final SAXException e) { throw new ParseException(e); } } void characters(final char c) { try { contentHandler.characters(new char[]{c}, 0, 1); } catch (final SAXException e) { throw new ParseException(e); } } void characters(final String t) { final char[] cs = t.toCharArray(); try { contentHandler.characters(cs, 0, cs.length); } catch (final SAXException e) { throw new ParseException(e); } } }
25.710145
89
0.631905
5575d745ad0ed1ed22d1b6ff36386eb1046469c5
2,101
package com.back.admin.domain.experience; import com.back.admin.domain.board.Board; import com.back.admin.domain.user.User; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonManagedReference; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.ArrayList; import java.util.Date; import java.util.List; @Getter @NoArgsConstructor @Entity public class Experience { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long experience_no; @Column private Date experience_start; @Column private Date experience_end; @Column private String experience_title; @Column(length = 500) private String experience_content; @Column(length = 500) private String experience_tag; // fk -> 1:N = student:experience @ManyToOne(optional = false) @JsonBackReference private User studentexperience; // fk -> 1:N = experience:board @OneToMany(cascade=CascadeType.ALL, mappedBy = "experienceboard") @JsonManagedReference private List<Board> boards=new ArrayList<>(); @Builder public Experience(Date experience_start, Date experience_end, String experience_title, String experience_content, String experience_tag, User studentexperience) { this.experience_start = experience_start; this.experience_end = experience_end; this.experience_title = experience_title; this.experience_content = experience_content; this.experience_tag = experience_tag; this.studentexperience = studentexperience; } public void update(Date experience_start, Date experience_end, String experience_title, String experience_content, String experience_tag) { this.experience_start = experience_start; this.experience_end = experience_end; this.experience_title = experience_title; this.experience_content = experience_content; this.experience_tag = experience_tag; } }
30.014286
97
0.730129
9fe4efb3ee53518046215a85e5a04e2f2fd73aaf
9,208
package model; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import presenter.AppPresenter; /** * * @author johnrojas */ public class DatabaseConnection { private static final String USERNAME = "root"; private static final String PASSWORD = ""; private static final String URI_CONNECTION = "jdbc:mysql://localhost/accidentdatabase_2"; public static final String VEHICLES = "vehicle"; public static final String ACCIDENTS = "accident"; public static final String TABLE_AC = "accident_vehicle"; public static enum Status { CREATED, DELETED, UPDATED, EXISTS, ERROR } private AppPresenter App; private Connection connection; private Statement statement; private ResultSet resultSet; public DatabaseConnection(AppPresenter App) { this.App = App; } private boolean testConnection(){ try { // uncoment if required inlcude library:depends on developer environment //Class.forName(com.mysql.jdbc.Driver); connection = DriverManager.getConnection(URI_CONNECTION, USERNAME, PASSWORD); } catch (SQLException ex) { printError(this, "testConnection", ex); if(App!=null)App.noDatabaseConnection(); return false; } return true; } public boolean openConnection() throws SQLException { if(!testConnection())return false; // uncoment if required inlcude library:depends on developer environment //Class.forName(com.mysql.jdbc.Driver); connection = DriverManager.getConnection(URI_CONNECTION, USERNAME, PASSWORD); System.out.print("connected to db: "); return true; } public void closeConnection(){ if(connection != null){ try { connection.close(); System.out.println(" | Disconnected from db"); } catch (SQLException ex) { //Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex); } } } public ResultSet runQuery(String query) throws SQLException{ statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); resultSet = statement.executeQuery(query); if(resultSet !=null){ if(resultSet.next()) return resultSet; } return null; } public PreparedStatement getStatement(String query) throws SQLException{ return connection.prepareStatement(query); } public static void printError(Object Class,String from,SQLException e){ System.err.println("BD Error: "+Class.getClass().toString() + "$" + from); System.err.println("code: "+e.getErrorCode()); System.err.println("Estate: "+e.getSQLState()); System.err.println("Message: "+e.getMessage()); } public static Status addVehicles(ArrayList<Vehicle> vehicles){ DatabaseConnection db = new DatabaseConnection(null); try { db.openConnection(); String query = "insert into " +DatabaseConnection.VEHICLES +" (" + VehicleQueries.PLATE +", " + VehicleQueries.MODEL +", " + VehicleQueries.YEAR +", " + VehicleQueries.OWNER_NAME +", " + VehicleQueries.OWNER_ADDRESS +", " + VehicleQueries.OWNER_PHONE +") values (?,?,?,?,?,?)"; PreparedStatement st = db.getStatement(query); for(Vehicle vehicle: vehicles){ st.setString(1, vehicle.getPlate()); st.setString(2, vehicle.getModel()); st.setInt(3, vehicle.getYear()); st.setString(4, vehicle.getOwnerName()); st.setString(5, vehicle.getOwnerAddress()); st.setString(6, vehicle.getOwnerPhone()); st.addBatch(); } st.executeBatch(); } catch (SQLException ex) { printError(db, "addVehicles", ex); return Status.ERROR; }finally{ db.closeConnection(); } return Status.CREATED; } public static Status deleteVehicles(ArrayList<Vehicle> vehicles){ DatabaseConnection db = new DatabaseConnection(null); try { db.openConnection(); String query = "delete from " +DatabaseConnection.VEHICLES +" where "+VehicleQueries.PLATE+"=?"; PreparedStatement st = db.getStatement(query); for(Vehicle vehicle: vehicles){ st.setString(1, vehicle.getPlate()); st.addBatch(); } st.executeBatch(); } catch (SQLException ex) { printError(db, "deleteVehicles", ex); return Status.ERROR; }finally{ db.closeConnection(); } return Status.DELETED; } public static Status addAccidents(ArrayList<Accident> accidents,AppPresenter app){ DatabaseConnection db = new DatabaseConnection(app); try { db.openConnection(); String query = "insert into " +DatabaseConnection.ACCIDENTS +" (" + AccidentQueries.LOCATION +", " + AccidentQueries.COMMENTS +", " + AccidentQueries.DATE +") values (?,?,?)"; PreparedStatement st = db.getStatement(query); for(Accident accident: accidents){ st.setString(1, accident.getLocation()); st.setString(2, accident.getComments()); Timestamp stamp = Timestamp.valueOf(accident.getDate()); st.setTimestamp(3, stamp); st.addBatch(); } st.executeBatch(); } catch (SQLException ex) { printError(db, "addVehicles", ex); return Status.ERROR; }finally{ db.closeConnection(); } return addRelationship(accidents,db); } private static Status addRelationship(ArrayList<Accident> accidents,DatabaseConnection db){ String query = "select * from "+DatabaseConnection.ACCIDENTS +" where "+AccidentQueries.COMMENTS+"=?"; try { db.openConnection(); PreparedStatement st = db.getStatement(query); st.setString(1, accidents.get(0).getComments()); ResultSet rs = st.executeQuery(); if(rs != null){ while(rs.next()){ String L = rs.getString(AccidentQueries.LOCATION); for(Accident accident: accidents){ if(accident.getLocation().equals(L)){ int id = rs.getInt(AccidentQueries.ID); accident.setID(id); } } }// query = "insert into "+DatabaseConnection.TABLE_AC +" ("+ AccidentQueries.ID +", "+ VehicleQueries.PLATE +") values (?,?)"; st = db.getStatement(query); for(Accident accident: accidents){ for(String plate:accident.getPlates()){ st.setInt(1, accident.getID()); st.setString(2, plate); st.addBatch(); } } st.executeBatch(); }else{ return Status.ERROR; } } catch (SQLException ex) { printError(db, "addRelationship", ex); return Status.ERROR; }finally{ db.closeConnection(); } return Status.CREATED; } public static Status deleteAccidents(ArrayList<Accident> accidents,AppPresenter app){ DatabaseConnection db = new DatabaseConnection(app); try { db.openConnection(); String query = "delete from " +DatabaseConnection.ACCIDENTS +" where "+AccidentQueries.ID+"=?"; PreparedStatement st = db.getStatement(query); for(Accident accident:accidents){ st.setInt(1, accident.getID()); st.addBatch(); } st.executeBatch(); //delete relationship query = "delete from " +DatabaseConnection.TABLE_AC +" where "+AccidentQueries.ID+"=?"; st = db.getStatement(query); for(Accident accident:accidents){ st.setInt(1, accident.getID()); st.addBatch(); } st.executeBatch(); } catch (SQLException ex) { printError(db, "deleteAccidents", ex); return Status.ERROR; }finally{ db.closeConnection(); } return Status.DELETED; } }
36.539683
139
0.546916
47a33f4f6f8f09a151b86b5190547256e1553f36
2,084
package com.github.mictaege.eval.spoon.example; import com.github.mictaege.eval.spoon.processing.OnlyIf; import static com.github.mictaege.eval.spoon.example.SpaceShipType.GEMINI; import static com.github.mictaege.eval.spoon.example.SpaceShipType.HERMES; import static com.github.mictaege.eval.spoon.example.SpaceShipType.MERCURY; import static com.github.mictaege.eval.spoon.processing.Variant.ESA; import static com.github.mictaege.eval.spoon.processing.Variant.NASA; import static com.github.mictaege.eval.spoon.processing.Variant.ROSKOSMOS; public enum BearerType { @OnlyIf(ESA) ARIANE5("Ariane5", 1996, new SpaceShip(HERMES), "com/github/mictaege/eval/spoon/example/Ariane5.jpg"), @OnlyIf(NASA) ATLAS("Atlas", new SpaceShip(MERCURY), "com/github/mictaege/eval/spoon/example/Atlas.jpg"), @OnlyIf(NASA) TITAN("Titan", new SpaceShip(GEMINI), "com/github/mictaege/eval/spoon/example/Titan.jpg"), @OnlyIf(ROSKOSMOS) WOSTOK("Wostok", new SpaceShip(SpaceShipType.WOSTOK), "com/github/mictaege/eval/spoon/example/Wostok.jpg"), @OnlyIf(ROSKOSMOS) SOJUS("Sojus", new SpaceShip(SpaceShipType.SOJUS), "com/github/mictaege/eval/spoon/example/Sojus.jpg"); private String name; @OnlyIf(ESA) private int constructionYear; private SpaceShip spaceShip; private String img; @OnlyIf(ESA) BearerType(final String name, final int constructionYear, final SpaceShip spaceShip, final String img) { this.name = name; this.constructionYear = constructionYear; this.spaceShip = spaceShip; this.img = img; } @OnlyIf({NASA, ROSKOSMOS}) BearerType(final String name, final SpaceShip spaceShip, final String img) { this.name = name; this.spaceShip = spaceShip; this.img = img; } public String getName() { return name; } @OnlyIf(ESA) public int getConstructionYear() { return constructionYear; } public SpaceShip getSpaceShip() { return spaceShip; } public String getImg() { return img; } }
32.061538
111
0.707774
511442a5deac0eee0491ab1e3b7391d97d98b5a9
974
package walletChallenge; import java.util.Date; public class Log { private Date date; private String ip; private String request; private String status; private String userAgent; public Log(Date date, String ip, String request, String status, String userAgent) { super(); this.date = date; this.ip = ip; this.request = request; this.status = status; this.userAgent = userAgent; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getRequest() { return request; } public void setRequest(String request) { this.request = request; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getUserAgent() { return userAgent; } public void setUserAgent(String userAgent) { this.userAgent = userAgent; } }
18.037037
84
0.693018
f8085b56f7e34682a0a244299fbef9047c47bc88
2,293
package com.rdx64.activitylifecycletest; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { String outData = savedInstanceState.getString("data_key"); Log.d(TAG, "onCreate: " + outData); } Button sna = (Button) findViewById(R.id.start_normal_activity); Button sda = (Button) findViewById(R.id.start_dialog_activity); sna.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent ina = new Intent(MainActivity.this, NormalActivity.class); startActivity(ina); } }); sda.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent ida = new Intent(MainActivity.this, DialogActivity.class); startActivity(ida); } }); Log.d(TAG, "onCreate: "); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart: "); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume: "); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause: "); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop: "); } @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy: "); } @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "onRestart: "); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); String outData = "Something you just typed"; outState.putString("data_key", outData); } }
27.626506
81
0.600959
9b321766081e0ebfab1467c180904e99ea1fd22b
823
package io.simplesource.saga.action.sourcing; import io.simplesource.kafka.model.CommandRequest; import io.simplesource.saga.shared.topics.TopicTypes; import org.apache.kafka.streams.kstream.KStream; import io.simplesource.saga.shared.topics.TopicNamer; import org.apache.kafka.streams.kstream.Produced; public class CommandProducer { public static <A, I, K, C> void commandRequest(CommandSpec<A, I, K, C> cSpec, TopicNamer commandTopicNamer, KStream<K, CommandRequest<K, C>> commandRequestByAggregate) { // publish to command request topic commandRequestByAggregate.to( commandTopicNamer.apply(TopicTypes.CommandTopic.request), Produced.with(cSpec.commandSerdes.aggregateKey(), cSpec.commandSerdes.commandRequest()) ); } }
39.190476
94
0.72175
4f9a3cfddec1dd1adfa594c9d8bd337f7ecffb0c
3,588
import lombok.Builder; import java.util.*; public @Builder class BuilderDefaultsGenerics<N extends Number, T, R extends List<T>> { public static @java.lang.SuppressWarnings("all") class BuilderDefaultsGenericsBuilder<N extends Number, T, R extends List<T>> { private @java.lang.SuppressWarnings("all") java.util.concurrent.Callable<N> callable$value; private @java.lang.SuppressWarnings("all") boolean callable$set; private @java.lang.SuppressWarnings("all") T tee$value; private @java.lang.SuppressWarnings("all") boolean tee$set; private @java.lang.SuppressWarnings("all") R arrr$value; private @java.lang.SuppressWarnings("all") boolean arrr$set; @java.lang.SuppressWarnings("all") BuilderDefaultsGenericsBuilder() { super(); } /** * @return {@code this}. */ public @java.lang.SuppressWarnings("all") BuilderDefaultsGenerics.BuilderDefaultsGenericsBuilder<N, T, R> callable(final java.util.concurrent.Callable<N> callable) { this.callable$value = callable; callable$set = true; return this; } /** * @return {@code this}. */ public @java.lang.SuppressWarnings("all") BuilderDefaultsGenerics.BuilderDefaultsGenericsBuilder<N, T, R> tee(final T tee) { this.tee$value = tee; tee$set = true; return this; } /** * @return {@code this}. */ public @java.lang.SuppressWarnings("all") BuilderDefaultsGenerics.BuilderDefaultsGenericsBuilder<N, T, R> arrr(final R arrr) { this.arrr$value = arrr; arrr$set = true; return this; } public @java.lang.SuppressWarnings("all") BuilderDefaultsGenerics<N, T, R> build() { java.util.concurrent.Callable<N> callable$value = this.callable$value; if ((! this.callable$set)) callable$value = BuilderDefaultsGenerics.<N, T, R>$default$callable(); T tee$value = this.tee$value; if ((! this.tee$set)) tee$value = BuilderDefaultsGenerics.<N, T, R>$default$tee(); R arrr$value = this.arrr$value; if ((! this.arrr$set)) arrr$value = BuilderDefaultsGenerics.<N, T, R>$default$arrr(); return new BuilderDefaultsGenerics<N, T, R>(callable$value, tee$value, arrr$value); } public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() { return (((((("BuilderDefaultsGenerics.BuilderDefaultsGenericsBuilder(callable$value=" + this.callable$value) + ", tee$value=") + this.tee$value) + ", arrr$value=") + this.arrr$value) + ")"); } } private @Builder.Default java.util.concurrent.Callable<N> callable; private @Builder.Default T tee; private @Builder.Default R arrr; private static @java.lang.SuppressWarnings("all") <N extends Number, T, R extends List<T>>java.util.concurrent.Callable<N> $default$callable() { return null; } private static @java.lang.SuppressWarnings("all") <N extends Number, T, R extends List<T>>T $default$tee() { return null; } private static @java.lang.SuppressWarnings("all") <N extends Number, T, R extends List<T>>R $default$arrr() { return null; } @java.lang.SuppressWarnings("all") BuilderDefaultsGenerics(final java.util.concurrent.Callable<N> callable, final T tee, final R arrr) { super(); this.callable = callable; this.tee = tee; this.arrr = arrr; } public static @java.lang.SuppressWarnings("all") <N extends Number, T, R extends List<T>>BuilderDefaultsGenerics.BuilderDefaultsGenericsBuilder<N, T, R> builder() { return new BuilderDefaultsGenerics.BuilderDefaultsGenericsBuilder<N, T, R>(); } }
47.210526
196
0.684225
571eaf5a44c517a6b879d81179be66614e771a76
2,051
package com.github.kabal163.statemachine.api; import javax.annotation.Nullable; /** * Contains the main information about executed transition. * If there were no exceptions then {@code exception} field * will be {@code null}. * * @param <S> type of the state of the {@link StatefulObject stateful object} * @param <E> type of event */ public class TransitionResult<S, E> { /** * Whether the transition was successful or not */ private final boolean succeeded; /** * The shared context of the transition */ private final StateContext<S, E> stateContext; /** * The state which stateful object has at the moment * of start the transition */ private final S sourceState; /** * The state which stateful object should has at the moment * of finish the transition. This is the desired state which may * doesn't match the actual state of the stateful object after * transition execution due to exceptions. */ private final S targetState; /** * Any exception which happened during actions or conditions execution * {@code null} if nothing happened */ @Nullable private final Exception exception; public TransitionResult(boolean succeeded, StateContext<S, E> stateContext, S sourceState, S targetState, @Nullable Exception exception) { this.succeeded = succeeded; this.stateContext = stateContext; this.sourceState = sourceState; this.targetState = targetState; this.exception = exception; } public boolean isSucceeded() { return succeeded; } public StateContext<S, E> getStateContext() { return stateContext; } public S getSourceState() { return sourceState; } public S getTargetState() { return targetState; } @Nullable public Exception getException() { return exception; } }
25.962025
77
0.624573
9979124c2d7e535a7c92fffb96c279c8247c0777
5,674
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.index.mapper; import com.carrotsearch.hppc.LongHashSet; import com.carrotsearch.hppc.LongSet; import org.apache.lucene.search.Query; import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.time.DateMathParser; import org.elasticsearch.index.fielddata.DoubleScriptFieldData; import org.elasticsearch.index.fielddata.ScriptDocValues.Doubles; import org.elasticsearch.index.fielddata.ScriptDocValues.DoublesSupplier; import org.elasticsearch.index.mapper.NumberFieldMapper.NumberType; import org.elasticsearch.index.query.SearchExecutionContext; import org.elasticsearch.script.CompositeFieldScript; import org.elasticsearch.script.DoubleFieldScript; import org.elasticsearch.script.Script; import org.elasticsearch.script.field.DelegateDocValuesField; import org.elasticsearch.search.DocValueFormat; import org.elasticsearch.search.lookup.SearchLookup; import org.elasticsearch.search.runtime.DoubleScriptFieldExistsQuery; import org.elasticsearch.search.runtime.DoubleScriptFieldRangeQuery; import org.elasticsearch.search.runtime.DoubleScriptFieldTermQuery; import org.elasticsearch.search.runtime.DoubleScriptFieldTermsQuery; import java.time.ZoneId; import java.util.Collection; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; public final class DoubleScriptFieldType extends AbstractScriptFieldType<DoubleFieldScript.LeafFactory> { public static final RuntimeField.Parser PARSER = new RuntimeField.Parser(Builder::new); private static class Builder extends AbstractScriptFieldType.Builder<DoubleFieldScript.Factory> { Builder(String name) { super(name, DoubleFieldScript.CONTEXT); } @Override AbstractScriptFieldType<?> createFieldType( String name, DoubleFieldScript.Factory factory, Script script, Map<String, String> meta ) { return new DoubleScriptFieldType(name, factory, script, meta); } @Override DoubleFieldScript.Factory getParseFromSourceFactory() { return DoubleFieldScript.PARSE_FROM_SOURCE; } @Override DoubleFieldScript.Factory getCompositeLeafFactory(Function<SearchLookup, CompositeFieldScript.LeafFactory> parentScriptFactory) { return DoubleFieldScript.leafAdapter(parentScriptFactory); } } public static RuntimeField sourceOnly(String name) { return new Builder(name).createRuntimeField(DoubleFieldScript.PARSE_FROM_SOURCE); } DoubleScriptFieldType(String name, DoubleFieldScript.Factory scriptFactory, Script script, Map<String, String> meta) { super( name, searchLookup -> scriptFactory.newFactory(name, script.getParams(), searchLookup), script, scriptFactory.isResultDeterministic(), meta ); } @Override public String typeName() { return NumberType.DOUBLE.typeName(); } @Override public Object valueForDisplay(Object value) { return value; // These should come back as a Double } @Override public DocValueFormat docValueFormat(String format, ZoneId timeZone) { checkNoTimeZone(timeZone); if (format == null) { return DocValueFormat.RAW; } return new DocValueFormat.Decimal(format); } @Override public DoubleScriptFieldData.Builder fielddataBuilder(String fullyQualifiedIndexName, Supplier<SearchLookup> searchLookup) { return new DoubleScriptFieldData.Builder( name(), leafFactory(searchLookup.get()), (dv, n) -> new DelegateDocValuesField(new Doubles(new DoublesSupplier(dv)), n) ); } @Override public Query existsQuery(SearchExecutionContext context) { applyScriptContext(context); return new DoubleScriptFieldExistsQuery(script, leafFactory(context), name()); } @Override public Query rangeQuery( Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, ZoneId timeZone, DateMathParser parser, SearchExecutionContext context ) { applyScriptContext(context); return NumberType.doubleRangeQuery( lowerTerm, upperTerm, includeLower, includeUpper, (l, u) -> new DoubleScriptFieldRangeQuery(script, leafFactory(context), name(), l, u) ); } @Override public Query termQuery(Object value, SearchExecutionContext context) { applyScriptContext(context); return new DoubleScriptFieldTermQuery(script, leafFactory(context), name(), NumberType.objectToDouble(value)); } @Override public Query termsQuery(Collection<?> values, SearchExecutionContext context) { if (values.isEmpty()) { return Queries.newMatchAllQuery(); } LongSet terms = new LongHashSet(values.size()); for (Object value : values) { terms.add(Double.doubleToLongBits(NumberType.objectToDouble(value))); } applyScriptContext(context); return new DoubleScriptFieldTermsQuery(script, leafFactory(context), name(), terms); } }
36.371795
137
0.711667
7ef57a980b7becfa7beb3301e11db601ce8e1903
1,824
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.utilities; import edu.wpi.first.wpilibj.Counter; import edu.wpi.first.wpilibj.CounterBase; import edu.wpi.first.wpilibj.Encoder; /** * Add your docs here. */ public class ByteEncoder extends Encoder { Counter pwmCounter; double offset; double buildOffset; public ByteEncoder(int dataAPort, int dataBPort, int pwmPort, boolean inverted, CounterBase.EncodingType encodingType, double buildOffset, boolean useoffset) { super(dataAPort, dataBPort, inverted, encodingType); pwmCounter = new Counter(pwmPort); pwmCounter.setSemiPeriodMode(true); // only count rising edges // wait for the pwm signal to be counted try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } if (useoffset) { this.buildOffset = buildOffset; offset = getOffset(); pwmCounter = null; } } public double getOffset() { // from 1 to 4096 us return (((pwmCounter.getPeriod() - 1e-6) / 4095e-6) * 1024) - buildOffset; } @Override public int get() { return super.get() - (int) offset; } @Override public double pidGet() { return get(); } }
25.690141
89
0.521382
a21648d5a3e629fa0aac3e237401963142a78d72
659
package top.imwonder.mcauth.dao; import org.springframework.stereotype.Component; import top.imwonder.mcauth.domain.Profile; import top.imwonder.util.AbstractDAO; @Component public class ProfileDAO extends AbstractDAO<Profile> { @Override protected Class<Profile> getDomainType() { return Profile.class; } @Override protected String getTableName() { return "w_profile"; } @Override protected String[] getPkColumns() { return new String[] { "w_id" }; } @Override protected String[] getCkColumns() { return new String[] { "w_name", "w_uid", "w_skin_id", "w_cape_id" }; } }
20.59375
76
0.661608
f633a3f3cbeaedf58adc28065480a5445913cfe8
12,496
package com.doublechain.contact; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.core.RowMapper; public class ContactNamingServiceDAO extends CommonJDBCTemplateDAO { private static Map<String, String[]>namingTableMap; static { namingTableMap = new HashMap<String, String[]>(); namingTableMap.put("Platform", new String[]{"platform_data","name"}); namingTableMap.put("Merchant", new String[]{"merchant_data","name"}); namingTableMap.put("Customer", new String[]{"customer_data","name"}); namingTableMap.put("CustomerContact", new String[]{"customer_contact_data","name"}); namingTableMap.put("CustomerOrder", new String[]{"customer_order_data","name"}); namingTableMap.put("CustomerContract", new String[]{"customer_contract_data","name"}); namingTableMap.put("ChangeRequestType", new String[]{"change_request_type_data","name"}); namingTableMap.put("ChangeRequest", new String[]{"change_request_data","name"}); namingTableMap.put("MobileApp", new String[]{"mobile_app_data","name"}); namingTableMap.put("Page", new String[]{"page_data","page_title"}); namingTableMap.put("PageType", new String[]{"page_type_data","name"}); namingTableMap.put("Slide", new String[]{"slide_data","name"}); namingTableMap.put("UiAction", new String[]{"ui_action_data","code"}); namingTableMap.put("Section", new String[]{"section_data","title"}); namingTableMap.put("UserDomain", new String[]{"user_domain_data","name"}); namingTableMap.put("UserAllowList", new String[]{"user_allow_list_data","user_identity"}); namingTableMap.put("SecUser", new String[]{"sec_user_data","login"}); namingTableMap.put("UserApp", new String[]{"user_app_data","title"}); namingTableMap.put("QuickLink", new String[]{"quick_link_data","name"}); namingTableMap.put("ListAccess", new String[]{"list_access_data","name"}); namingTableMap.put("LoginHistory", new String[]{"login_history_data","from_ip"}); namingTableMap.put("CandidateContainer", new String[]{"candidate_container_data","name"}); namingTableMap.put("CandidateElement", new String[]{"candidate_element_data","name"}); namingTableMap.put("WechatWorkappIdentity", new String[]{"wechat_workapp_identity_data","corp_id"}); namingTableMap.put("WechatMiniappIdentity", new String[]{"wechat_miniapp_identity_data","open_id"}); namingTableMap.put("KeyPairIdentity", new String[]{"key_pair_identity_data","public_key"}); namingTableMap.put("PublicKeyType", new String[]{"public_key_type_data","key_alg"}); namingTableMap.put("TreeNode", new String[]{"tree_node_data","node_id"}); } @Override protected String[] getNormalColumnNames() { // TODO Auto-generated method stub return new String[]{"id"}; } @Override protected String getName() { // TODO Auto-generated method stub return "naming"; } @Override protected String getBeanName() { // TODO Auto-generated method stub return null; } public void alias(List<BaseEntity> entityList){ //this.getClass().getSimpleName() //these objects are most likely the same, or most are the same if(entityList == null){ //noting to be enhanced return; } if(entityList.isEmpty()){ //noting to be enhanced return; } List<BaseEntity> entityListToSort = new ArrayList<BaseEntity>(); entityListToSort.addAll(entityList); Collections.sort(entityListToSort, new Comparator<BaseEntity>(){ @Override public int compare(BaseEntity o1, BaseEntity o2) { if(o1==o2){ return 0; } if(o1==null){ return 1; } int round1 = internalTypeOf(o1).compareTo(internalTypeOf(o2)); if(round1!=0){ return round1; } if(o1.getId()==null){ return 1;//should check in pojo, but prevent the bad thing happing } if(o2.getId()==null){ return -1;//should check in pojo, but prevent the bad thing happing } int round2 = o1.getId().compareTo(o2.getId()); return round2; } }); List<BaseEntity> sortedEntityList = entityListToSort;//just for better reading //with a sorted list, the find out the sql and parameters Map<String, List<String>> sqlMap = sqlMapOf(sortedEntityList); String unionedSQL = unionSQLOf(sqlMap); Object [] parameters = parametersOf(sqlMap); Map<String,String> resultMap = getResultMap(unionedSQL, parameters); fillResult(entityList, resultMap); //List<BaseEntity> resultList = this.queryForList(unionedSQL, parameters, getMapper()); } protected void fillResult(List<BaseEntity> entityList,Map<String, String> resultMap) { for(BaseEntity baseEntity: entityList){ String displayName = findDisplayNameInMap(baseEntity, resultMap); if(displayName==null){ baseEntity.setDisplayName("<null>"); continue; } baseEntity.setDisplayName(displayName); } } protected String findDisplayNameInMap(BaseEntity baseEntity, Map<String, String> resultMap) { String key = this.join(internalTypeOf(baseEntity),":",baseEntity.getId()); return resultMap.get(key); } protected String trimString(String valueToTrim) { if(valueToTrim==null) { return null; } if(valueToTrim.isEmpty()) { return ""; } return valueToTrim.trim(); } protected Map<String, String> getResultMap(String unionedSQL, Object[] parameters) { this.logSQLAndParameters("getDisplayName", unionedSQL, parameters,"---"); return getJdbcTemplate().query(unionedSQL, parameters,new ResultSetExtractor<Map<String,String>>(){ @Override public Map<String,String > extractData(ResultSet resultSet) throws SQLException, DataAccessException { Map<String,String> internalMap = new HashMap<String,String>(); while(resultSet.next()){ String key = trimString(resultSet.getString(1))+":"+trimString(resultSet.getString(2)); // Fixed the issue for Informix and Gbase 8t/s data base, it appends values for the class column String value = resultSet.getString(3); // System.out.printf("%s = %s\r\n",key, value); internalMap.put(key, value); } return internalMap; } }); } protected Object[] parametersOf(Map<String, List<String>> sqlMap) { // TODO Auto-generated method stub List<Object> resultParameters = new ArrayList<Object>(); for(Map.Entry<String, List<String>> entry: sqlMap.entrySet()){ List<String> parameters = entry.getValue(); resultParameters.addAll(parameters); } return resultParameters.toArray(); } private String unionSQLOf(Map<String, List<String>> sqlMap) { StringBuilder stringBuilder = new StringBuilder(); int index = 0 ; for(Map.Entry<String, List<String>> entry: sqlMap.entrySet()){ if(index>0){ stringBuilder.append("\r\n"); stringBuilder.append(" union "); } String sqlPrefix = entry.getKey(); List<String> parameters = entry.getValue(); String sqlToUnion = this.getNamingQuerySQL(sqlPrefix, parameters); stringBuilder.append(sqlToUnion); index++; } return stringBuilder.toString(); } Map<String, List<String>> sqlMapOf(List<BaseEntity> sortedEntityList){ String lastClassName = null; List<String> idList = null; Map<String, List<String>> sqlMap = new HashMap<String, List<String>>(); for(BaseEntity baseEntity: sortedEntityList){ String currentClassName = this.internalTypeOf(baseEntity); if(currentClassName.equals(lastClassName)){ if(idList.contains(baseEntity.getId())){ continue; } idList.add(baseEntity.getId()); continue; } idList = new ArrayList<String>(); idList.add(baseEntity.getId()); String sql = sqlOf(currentClassName); if(sql != null) sqlMap.put(sql, idList); lastClassName = currentClassName; } return sqlMap; } protected String sqlOf(String currentClassName) { String[] sqlInfo=namingTableMap.get(currentClassName); if(sqlInfo==null){ //throw new IllegalArgumentException("sqlOf(String currentClassName): Not able to find sql info for class: "+currentClassName); return null; } if(sqlInfo.length<2){ throw new IllegalArgumentException("sqlOf(String currentClassName): sqlInfo.length should equals 2 for class: "+currentClassName); } String tableName = sqlInfo[0]; String displayExpr = sqlInfo[1]; String sql = this.join("select '",currentClassName,"' as class_name, id, ",displayExpr," as display_name from ",tableName," where id in "); return sql; } protected String internalTypeOf(BaseEntity baseEntity){ if(baseEntity==null){ return "null"; } return baseEntity.getInternalType(); } protected Set <BaseEntity> uniqize(List<BaseEntity> entityList){ Set <BaseEntity> baseEntitySet = new HashSet<BaseEntity>(); for(BaseEntity baseEntity: entityList){ if(baseEntity == null){ continue; } if(baseEntity.getId() == null){ continue; } baseEntitySet.add(baseEntity); } return baseEntitySet; } protected String getNamingQuerySQL(String sqlPrefix, List<String> entityList){ String SQL = this.join(sqlPrefix, "(",repeatExpr("?",",",entityList.size()),")");// "select * from "+this.getTableName()+" where id in ; return SQL; } /* static { namingTableMap = new HashMap<String, String[]>(); namingTableMap.put("CarInspectionPlatform", new String[]{"car_inspection_platform_data","name"}); namingTableMap.put("IdentityCard", new String[]{"identity_card_data","holder_name"}); }*/ public SmartList<BaseEntity> requestCandidateValuesForSearch(String ownerMemberName, String ownerId, String resultMemberName, String resutlClassName, String targetClassName, String filterKey, int pageNo){ this.checkFieldName(resultMemberName); this.checkFieldName(resutlClassName); this.checkFieldName(ownerMemberName); this.checkFieldName(targetClassName); List<Object> params = new ArrayList<>(); params.add(ownerId); String filterClause = " "; String joinClause = " "; if (filterKey != null && !filterKey.trim().isEmpty() ) { String[] sqlInfo=namingTableMap.get(targetClassName); if(sqlInfo==null){ throw new IllegalArgumentException("sqlOf(String currentClassName): Not able to find sql info for filter class: "+targetClassName); } if(sqlInfo.length<2){ throw new IllegalArgumentException("sqlOf(String currentClassName): sqlInfo.length should equals 2 for filter class: "+targetClassName); } String displayExpr = sqlInfo[1]; joinClause = String.format(" left join %s_data T2 on T1.%s=T2.id ", mapToInternalColumn(targetClassName), mapToInternalColumn(resultMemberName)); filterClause = String.format(" and T2.%s like ? ", displayExpr); params.add("%"+filterKey.trim()+"%"); } String sql = String.format("select distinct T1.%s from %s_data T1%swhere T1.%s = ?%sorder by cast(%s as CHAR CHARACTER SET GBK) asc", mapToInternalColumn(resultMemberName), mapToInternalColumn(resutlClassName), joinClause, mapToInternalColumn(ownerMemberName), filterClause, mapToInternalColumn(resultMemberName)); // System.out.println(sql +" executed with " + params); List<String> keyList = getJdbcTemplate().queryForList(sql, params.toArray(), String.class); SmartList<BaseEntity> resultList = new SmartList<>(); if (keyList == null) { return resultList; } keyList.forEach(key->{ resultList.add(BaseEntity.pretendToBe(targetClassName, key)); }); this.alias(resultList); return resultList; } protected String mapToInternalColumn(String field){ char [] fieldArray = field.toCharArray(); StringBuilder internalFieldBuffer = new StringBuilder(); int i = 0; for(char ch:fieldArray){ i++; if(Character.isUpperCase(ch) ){ if (i > 1) { internalFieldBuffer.append('_'); } char lowerCaseChar = Character.toLowerCase(ch); internalFieldBuffer.append(lowerCaseChar); continue; } internalFieldBuffer.append(ch); } return internalFieldBuffer.toString(); } public static String getDisplayNameColumnName(String modelName) { String[] sqlInfo=namingTableMap.get(modelName); if (sqlInfo == null || sqlInfo.length < 2) { return null; } return sqlInfo[1]; } }
31.007444
208
0.709587
842092ba00db66926f9e953ea4a66270717c90e3
350
import java.util.Scanner; public class BoxGame { public static void main(String[] args) { Scanner scan = new Scanner(System.in); long n, m; while ((n = scan.nextLong()) != 0) { m = 1; while (m < n) { m = m * 2 + 1; } System.out.println(m != n ? "Alice" : "Bob"); } scan.close(); } }
15.217391
49
0.488571
f5be354a213c1e51da64986daba5aa073f7ced17
6,811
package marquez.spark.agent.lifecycle; import java.net.URI; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.HashMap; import java.util.Map; import lombok.extern.slf4j.Slf4j; import marquez.spark.agent.MarquezContext; import marquez.spark.agent.client.LineageEvent; import marquez.spark.agent.client.LineageEvent.JobLink; import marquez.spark.agent.client.LineageEvent.ParentRunFacet; import marquez.spark.agent.client.LineageEvent.RunFacet; import marquez.spark.agent.client.LineageEvent.RunLink; import marquez.spark.agent.facets.ErrorFacet; import marquez.spark.agent.facets.LogicalPlanFacet; import org.apache.spark.scheduler.ActiveJob; import org.apache.spark.scheduler.JobFailed; import org.apache.spark.scheduler.JobResult; import org.apache.spark.scheduler.SparkListenerJobEnd; import org.apache.spark.scheduler.SparkListenerJobStart; import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan; import org.apache.spark.sql.execution.QueryExecution; import org.apache.spark.sql.execution.SQLExecution; import org.apache.spark.sql.execution.ui.SparkListenerSQLExecutionEnd; import org.apache.spark.sql.execution.ui.SparkListenerSQLExecutionStart; @Slf4j public class SparkSQLExecutionContext implements ExecutionContext { private final long executionId; private final QueryExecution queryExecution; private MarquezContext marquezContext; private final LogicalPlanFacetTraverser logicalPlanFacetTraverser; private final DatasetLogicalPlanTraverser datasetLogicalPlanTraverser; public SparkSQLExecutionContext( long executionId, MarquezContext marquezContext, LogicalPlanFacetTraverser logicalPlanFacetTraverser, DatasetLogicalPlanTraverser datasetLogicalPlanTraverser) { this.executionId = executionId; this.marquezContext = marquezContext; this.logicalPlanFacetTraverser = logicalPlanFacetTraverser; this.datasetLogicalPlanTraverser = datasetLogicalPlanTraverser; this.queryExecution = SQLExecution.getQueryExecution(executionId); } public void start(SparkListenerSQLExecutionStart startEvent) {} public void end(SparkListenerSQLExecutionEnd endEvent) {} @Override public void setActiveJob(ActiveJob activeJob) {} @Override public void start(SparkListenerJobStart jobStart) { log.info("Starting job as part of spark-sql:" + jobStart.jobId()); if (queryExecution == null) { log.info("No execution info {}", queryExecution); return; } DatasetLogicalPlanTraverser.TraverserResult result = datasetLogicalPlanTraverser.build( queryExecution.logical(), marquezContext.getJobNamespace()); LineageEvent event = LineageEvent.builder() .inputs(result.getInputDataset()) .outputs(result.getOutputDataset()) .run( buildRun( buildRunFacets( buildLogicalPlanFacet(queryExecution.logical()), null, buildParentFacet()))) .job(buildJob()) .eventTime(toZonedTime(jobStart.time())) .eventType("START") .producer("https://github.com/OpenLineage/OpenLineage/blob/v1-0-0/client") .build(); marquezContext.emit(event); } private ParentRunFacet buildParentFacet() { return ParentRunFacet.builder() ._producer(URI.create("https://github.com/OpenLineage/OpenLineage/blob/v1-0-0/client")) ._schemaURL( URI.create( "https://github.com/OpenLineage/OpenLineage/blob/v1-0-0/spec/OpenLineage.yml#ParentRunFacet")) .job( JobLink.builder() .name(marquezContext.getJobName()) .namespace(marquezContext.getJobNamespace()) .build()) .run(RunLink.builder().runId(marquezContext.getParentRunId()).build()) .build(); } @Override public void end(SparkListenerJobEnd jobEnd) { log.info("Ending job as part of spark-sql:" + jobEnd.jobId()); if (queryExecution == null) { log.info("No execution info {}", queryExecution); return; } log.debug("Traversing logical plan {}", queryExecution.logical().toJSON()); log.debug("Physical plan executed {}", queryExecution.executedPlan().toJSON()); DatasetLogicalPlanTraverser.TraverserResult r = datasetLogicalPlanTraverser.build( queryExecution.logical(), marquezContext.getJobNamespace()); LineageEvent event = LineageEvent.builder() .inputs(r.getInputDataset()) .outputs(r.getOutputDataset()) .run( buildRun( buildRunFacets( buildLogicalPlanFacet(queryExecution.logical()), buildJobErrorFacet(jobEnd.jobResult()), buildParentFacet()))) .job(buildJob()) .eventTime(toZonedTime(jobEnd.time())) .eventType(getEventType(jobEnd.jobResult())) .producer("https://github.com/OpenLineage/OpenLineage/blob/v1-0-0/client") .build(); marquezContext.emit(event); } protected ZonedDateTime toZonedTime(long time) { Instant i = Instant.ofEpochMilli(time); return ZonedDateTime.ofInstant(i, ZoneOffset.UTC); } protected String getEventType(JobResult jobResult) { if (jobResult.getClass().getSimpleName().startsWith("JobSucceeded")) { return "COMPLETE"; } return "FAIL"; } protected LineageEvent.Run buildRun(RunFacet facets) { return LineageEvent.Run.builder().runId(marquezContext.getParentRunId()).facets(facets).build(); } protected RunFacet buildRunFacets( LogicalPlanFacet logicalPlanFacet, ErrorFacet jobError, ParentRunFacet parentRunFacet) { Map<String, Object> additionalFacets = new HashMap<>(); if (logicalPlanFacet != null) { additionalFacets.put("spark.logicalPlan", logicalPlanFacet); } if (jobError != null) { additionalFacets.put("spark.exception", jobError); } return RunFacet.builder().parent(parentRunFacet).additional(additionalFacets).build(); } protected LogicalPlanFacet buildLogicalPlanFacet(LogicalPlan plan) { Map<String, Object> planMap = logicalPlanFacetTraverser.visit(plan); return LogicalPlanFacet.builder().plan(planMap).build(); } protected ErrorFacet buildJobErrorFacet(JobResult jobResult) { if (jobResult instanceof JobFailed && ((JobFailed) jobResult).exception() != null) { return ErrorFacet.builder().exception(((JobFailed) jobResult).exception()).build(); } return null; } protected LineageEvent.Job buildJob() { return LineageEvent.Job.builder() .namespace(marquezContext.getJobNamespace()) .name(marquezContext.getJobName()) .build(); } }
38.480226
110
0.707532
22ad2b8bbde25c5f307a573fa1ecf03adba11d7d
5,934
/* * Copyright (c) 2003, The JUNG Authors * * All rights reserved. * * This software is open-source under the BSD license; see either * "license.txt" or * https://github.com/jrtom/jung/blob/master/LICENSE for a description. */ package edu.uci.ics.jung.algorithms.layout; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.List; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import edu.uci.ics.jung.algorithms.layout.util.RandomLocationTransformer; import edu.uci.ics.jung.algorithms.util.IterativeContext; import edu.uci.ics.jung.graph.Graph; /** * Implements a self-organizing map layout algorithm, based on Meyer's * self-organizing graph methods. * * @author Yan Biao Boey */ public class ISOMLayout<V, E> extends AbstractLayout<V,E> implements IterativeContext { protected LoadingCache<V, ISOMVertexData> isomVertexData = CacheBuilder.newBuilder().build(new CacheLoader<V, ISOMVertexData>() { public ISOMVertexData load(V vertex) { return new ISOMVertexData(); } }); private int maxEpoch; private int epoch; private int radiusConstantTime; private int radius; private int minRadius; private double adaption; private double initialAdaption; private double minAdaption; protected GraphElementAccessor<V,E> elementAccessor = new RadiusGraphElementAccessor<V,E>(); private double coolingFactor; private List<V> queue = new ArrayList<V>(); private String status = null; /** * @return the current number of epochs and execution status, as a string. */ public String getStatus() { return status; } public ISOMLayout(Graph<V,E> g) { super(g); } public void initialize() { setInitializer(new RandomLocationTransformer<V>(getSize())); maxEpoch = 2000; epoch = 1; radiusConstantTime = 100; radius = 5; minRadius = 1; initialAdaption = 90.0D / 100.0D; adaption = initialAdaption; minAdaption = 0; //factor = 0; //Will be set later on coolingFactor = 2; //temperature = 0.03; //initialJumpRadius = 100; //jumpRadius = initialJumpRadius; //delay = 100; } /** * Advances the current positions of the graph elements. */ public void step() { status = "epoch: " + epoch + "; "; if (epoch < maxEpoch) { adjust(); updateParameters(); status += " status: running"; } else { status += "adaption: " + adaption + "; "; status += "status: done"; // done = true; } } private synchronized void adjust() { //Generate random position in graph space Point2D tempXYD = new Point2D.Double(); // creates a new XY data location tempXYD.setLocation(10 + Math.random() * getSize().getWidth(), 10 + Math.random() * getSize().getHeight()); //Get closest vertex to random position V winner = elementAccessor.getVertex(this, tempXYD.getX(), tempXYD.getY()); while(true) { try { for(V v : getGraph().getVertices()) { ISOMVertexData ivd = getISOMVertexData(v); ivd.distance = 0; ivd.visited = false; } break; } catch(ConcurrentModificationException cme) {} } adjustVertex(winner, tempXYD); } private synchronized void updateParameters() { epoch++; double factor = Math.exp(-1 * coolingFactor * (1.0 * epoch / maxEpoch)); adaption = Math.max(minAdaption, factor * initialAdaption); //jumpRadius = (int) factor * jumpRadius; //temperature = factor * temperature; if ((radius > minRadius) && (epoch % radiusConstantTime == 0)) { radius--; } } private synchronized void adjustVertex(V v, Point2D tempXYD) { queue.clear(); ISOMVertexData ivd = getISOMVertexData(v); ivd.distance = 0; ivd.visited = true; queue.add(v); V current; while (!queue.isEmpty()) { current = queue.remove(0); ISOMVertexData currData = getISOMVertexData(current); Point2D currXYData = apply(current); double dx = tempXYD.getX() - currXYData.getX(); double dy = tempXYD.getY() - currXYData.getY(); double factor = adaption / Math.pow(2, currData.distance); currXYData.setLocation(currXYData.getX()+(factor*dx), currXYData.getY()+(factor*dy)); if (currData.distance < radius) { Collection<V> s = getGraph().getNeighbors(current); while(true) { try { for(V child : s) { ISOMVertexData childData = getISOMVertexData(child); if (childData != null && !childData.visited) { childData.visited = true; childData.distance = currData.distance + 1; queue.add(child); } } break; } catch(ConcurrentModificationException cme) {} } } } } protected ISOMVertexData getISOMVertexData(V v) { return isomVertexData.getUnchecked(v); } /** * This one is an incremental visualization. * @return <code>true</code> is the layout algorithm is incremental, <code>false</code> otherwise */ public boolean isIncremental() { return true; } /** * Returns <code>true</code> if the vertex positions are no longer being * updated. Currently <code>ISOMLayout</code> stops updating vertex * positions after a certain number of iterations have taken place. * @return <code>true</code> if the vertex position updates have stopped, * <code>false</code> otherwise */ public boolean done() { return epoch >= maxEpoch; } protected static class ISOMVertexData { int distance; boolean visited; protected ISOMVertexData() { distance = 0; visited = false; } } /** * Resets the layout iteration count to 0, which allows the layout algorithm to * continue updating vertex positions. */ public void reset() { epoch = 0; } }
26.373333
98
0.663128
14749a8701697f6ca57b571904c4272efe21396c
231
package io.smartcat.ranger.core; import java.util.UUID; /** * Generates random UUID. */ public class UUIDValue extends Value<String> { @Override public void eval() { val = UUID.randomUUID().toString(); } }
15.4
46
0.645022
f6702a400e1f3fc4cb40ffa16bffb3dd826bf737
1,308
package com.application.opreation.user.showPanal; import com.gui.user.GUI_UserRegister; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.stage.Stage; /** * @ author Andrej Simionenko, Raheela Tasneem, Fei Gu, Ibraheem Swaidan * @ create 2021-06-14-16.12 * @ grade CS20_EASV_SØNDERBORG * @ Description This is the EASV D20 2nd semester final exam project * @ Supervisors Karsten Skov, Tommy Haugaard, Frank Østergaard Hansen * @ Version 0.1 */ public class App_Opr_ShowRegister implements EventHandler<ActionEvent> { private Stage stage_Login; private Stage primaryStage; /** * here is the constructor for show the register penal. * @param stage_Login * @param primaryStage */ public App_Opr_ShowRegister(Stage stage_Login, Stage primaryStage) { this.stage_Login = stage_Login; this.primaryStage = primaryStage; } /** * this override method is the when the register button be press. then show the register panal. * @param event mouse click on the button. */ @Override public void handle(ActionEvent event) { GUI_UserRegister gui_userRegister = new GUI_UserRegister(); gui_userRegister.showRegisterStage(stage_Login, primaryStage); } }
31.142857
99
0.724006
da2ab51d4201927183e4200a68dfa372bac9689a
425
package com.nao4j.subtrol.core.service; import com.nao4j.subtrol.core.document.internal.Quantity; import org.springframework.security.access.annotation.Secured; import java.util.Set; /** * Сервис для работы с размерностями. */ public interface QuantityService { /** * Получить множество поддерживаемых размерностей. */ @Secured({"ROLE_USER", "ROLE_ADMIN"}) Set<Quantity.QuantityType> getAll(); }
21.25
62
0.731765
c8631d22c52523dc0c33686d8790a2e72863d4fc
8,463
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.com.asofar.dao; import ec.com.asofar.dao.exceptions.NonexistentEntityException; import ec.com.asofar.dao.exceptions.PreexistingEntityException; import ec.com.asofar.dto.CoDetalleOrdenPedido; import ec.com.asofar.dto.CoDetalleOrdenPedidoPK; import java.io.Serializable; import javax.persistence.Query; import javax.persistence.EntityNotFoundException; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import ec.com.asofar.dto.CoOrdenPedido; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; /** * * @author usuario */ public class CoDetalleOrdenPedidoJpaController implements Serializable { public CoDetalleOrdenPedidoJpaController(EntityManagerFactory emf) { this.emf = emf; } private EntityManagerFactory emf = null; public EntityManager getEntityManager() { return emf.createEntityManager(); } public void create(CoDetalleOrdenPedido coDetalleOrdenPedido) throws PreexistingEntityException, Exception { if (coDetalleOrdenPedido.getCoDetalleOrdenPedidoPK() == null) { coDetalleOrdenPedido.setCoDetalleOrdenPedidoPK(new CoDetalleOrdenPedidoPK()); } coDetalleOrdenPedido.getCoDetalleOrdenPedidoPK().setIdOrdenPedido(coDetalleOrdenPedido.getCoOrdenPedido().getCoOrdenPedidoPK().getIdOrdenPedido()); coDetalleOrdenPedido.getCoDetalleOrdenPedidoPK().setIdSurcusal(coDetalleOrdenPedido.getCoOrdenPedido().getCoOrdenPedidoPK().getIdSucursal()); coDetalleOrdenPedido.getCoDetalleOrdenPedidoPK().setIdEmpresa(coDetalleOrdenPedido.getCoOrdenPedido().getCoOrdenPedidoPK().getIdEmpresa()); EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); CoOrdenPedido coOrdenPedido = coDetalleOrdenPedido.getCoOrdenPedido(); if (coOrdenPedido != null) { coOrdenPedido = em.getReference(coOrdenPedido.getClass(), coOrdenPedido.getCoOrdenPedidoPK()); coDetalleOrdenPedido.setCoOrdenPedido(coOrdenPedido); } em.persist(coDetalleOrdenPedido); if (coOrdenPedido != null) { coOrdenPedido.getCoDetalleOrdenPedidoList().add(coDetalleOrdenPedido); coOrdenPedido = em.merge(coOrdenPedido); } em.getTransaction().commit(); } catch (Exception ex) { if (findCoDetalleOrdenPedido(coDetalleOrdenPedido.getCoDetalleOrdenPedidoPK()) != null) { throw new PreexistingEntityException("CoDetalleOrdenPedido " + coDetalleOrdenPedido + " already exists.", ex); } throw ex; } finally { if (em != null) { em.close(); } } } public void edit(CoDetalleOrdenPedido coDetalleOrdenPedido) throws NonexistentEntityException, Exception { coDetalleOrdenPedido.getCoDetalleOrdenPedidoPK().setIdOrdenPedido(coDetalleOrdenPedido.getCoOrdenPedido().getCoOrdenPedidoPK().getIdOrdenPedido()); coDetalleOrdenPedido.getCoDetalleOrdenPedidoPK().setIdSurcusal(coDetalleOrdenPedido.getCoOrdenPedido().getCoOrdenPedidoPK().getIdSucursal()); coDetalleOrdenPedido.getCoDetalleOrdenPedidoPK().setIdEmpresa(coDetalleOrdenPedido.getCoOrdenPedido().getCoOrdenPedidoPK().getIdEmpresa()); EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); CoDetalleOrdenPedido persistentCoDetalleOrdenPedido = em.find(CoDetalleOrdenPedido.class, coDetalleOrdenPedido.getCoDetalleOrdenPedidoPK()); CoOrdenPedido coOrdenPedidoOld = persistentCoDetalleOrdenPedido.getCoOrdenPedido(); CoOrdenPedido coOrdenPedidoNew = coDetalleOrdenPedido.getCoOrdenPedido(); if (coOrdenPedidoNew != null) { coOrdenPedidoNew = em.getReference(coOrdenPedidoNew.getClass(), coOrdenPedidoNew.getCoOrdenPedidoPK()); coDetalleOrdenPedido.setCoOrdenPedido(coOrdenPedidoNew); } coDetalleOrdenPedido = em.merge(coDetalleOrdenPedido); if (coOrdenPedidoOld != null && !coOrdenPedidoOld.equals(coOrdenPedidoNew)) { coOrdenPedidoOld.getCoDetalleOrdenPedidoList().remove(coDetalleOrdenPedido); coOrdenPedidoOld = em.merge(coOrdenPedidoOld); } if (coOrdenPedidoNew != null && !coOrdenPedidoNew.equals(coOrdenPedidoOld)) { coOrdenPedidoNew.getCoDetalleOrdenPedidoList().add(coDetalleOrdenPedido); coOrdenPedidoNew = em.merge(coOrdenPedidoNew); } em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { CoDetalleOrdenPedidoPK id = coDetalleOrdenPedido.getCoDetalleOrdenPedidoPK(); if (findCoDetalleOrdenPedido(id) == null) { throw new NonexistentEntityException("The coDetalleOrdenPedido with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } } public void destroy(CoDetalleOrdenPedidoPK id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); CoDetalleOrdenPedido coDetalleOrdenPedido; try { coDetalleOrdenPedido = em.getReference(CoDetalleOrdenPedido.class, id); coDetalleOrdenPedido.getCoDetalleOrdenPedidoPK(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The coDetalleOrdenPedido with id " + id + " no longer exists.", enfe); } CoOrdenPedido coOrdenPedido = coDetalleOrdenPedido.getCoOrdenPedido(); if (coOrdenPedido != null) { coOrdenPedido.getCoDetalleOrdenPedidoList().remove(coDetalleOrdenPedido); coOrdenPedido = em.merge(coOrdenPedido); } em.remove(coDetalleOrdenPedido); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } } public List<CoDetalleOrdenPedido> findCoDetalleOrdenPedidoEntities() { return findCoDetalleOrdenPedidoEntities(true, -1, -1); } public List<CoDetalleOrdenPedido> findCoDetalleOrdenPedidoEntities(int maxResults, int firstResult) { return findCoDetalleOrdenPedidoEntities(false, maxResults, firstResult); } private List<CoDetalleOrdenPedido> findCoDetalleOrdenPedidoEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(CoDetalleOrdenPedido.class)); Query q = em.createQuery(cq); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } return q.getResultList(); } finally { em.close(); } } public CoDetalleOrdenPedido findCoDetalleOrdenPedido(CoDetalleOrdenPedidoPK id) { EntityManager em = getEntityManager(); try { return em.find(CoDetalleOrdenPedido.class, id); } finally { em.close(); } } public int getCoDetalleOrdenPedidoCount() { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<CoDetalleOrdenPedido> rt = cq.from(CoDetalleOrdenPedido.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } finally { em.close(); } } }
45.745946
156
0.645043
546962dc76d8a1bf97fecab720b07e9251b4e98b
4,101
package hr.yeti.rudimentary.events; import hr.yeti.rudimentary.context.spi.Instance; import hr.yeti.rudimentary.events.spi.EventListener; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * A little bit custom implementation of observer pattern. * * Since this class implements {@link Instance} it means it is loaded automatically via {@link ServiceLoader} on * application startup. * * In practice, the only time you could use an instance of this class if you would want to publish an event. Preferred * way of publishing events is shown in {@link Event}. By default, an instance of EventPublisher should be provided by the implementation which in our * case is rudimentary-server module. * * <pre> * {@code * ... * Instance.of(EventPublisher.class).publish(new BlogPost("Post 2."), EventPublisher.Type.SYNC); * ... * } * </pre> * * @author vedransmid@yeti-it.hr */ public final class EventPublisher implements Instance { /** * Enumerated type of how event should be published. This has an effect on the way how listeners process published * event. */ public enum Type { SYNC, ASYNC } /** * A map of all registered {@link EventListener}. One event class type can have multiple listeners registered. */ private static final Map<Class<? extends Event>, List<EventListener<Event>>> LISTENERS = new ConcurrentHashMap<>(); /** * Thread pool for asynchronous listener execution. */ private static final ExecutorService ASYNC_EXECUTOR = Executors.newCachedThreadPool(); /** * <pre> * Call this class to publish an event. This method is used internally by * {@link Event#publish(hr.yeti.rudimentary.events.EventPublisher.Type)} for publishing events. * For now only synchronous publishing is supported which means listeners will * be executed synchronously one after another. * </pre> * * @param event Event instance to be published. * @param type How event will be published. */ public void publish(Event event, Type type) { if (LISTENERS.containsKey(event.getClass())) { if (type == Type.SYNC) { LISTENERS.get(event.getClass()) .stream() .forEach((t) -> { t.onEvent(event); }); } else { LISTENERS.get(event.getClass()) .stream() .map(listener -> { return (Runnable) () -> { listener.onEvent(event); }; }) .forEach((runnable) -> { CompletableFuture.runAsync(runnable, ASYNC_EXECUTOR); }); } } } @Override public void initialize() { Instance.providersOf(EventListener.class) .forEach(this::attach); } /** * Adds event listener to LISTENERS map. * * @param listener Registered event listener to be added to LISTENERS map. */ private void attach(EventListener<Event> listener) { String className = ((ParameterizedType) listener.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0].getTypeName(); try { Class<? extends Event> clazz = (Class<? extends Event>) Class.forName(className); LISTENERS.putIfAbsent(clazz, new ArrayList<>()); if (!LISTENERS.get(clazz).contains(listener)) { LISTENERS.get(clazz).add(listener); } } catch (ClassNotFoundException ex) { logger().log(System.Logger.Level.ERROR, ex); } } @Override public Class[] dependsOn() { return new Class[]{ EventListener.class }; } }
34.462185
150
0.620824
99cf35ff27a67d570e15b58bbbff75619a38624e
2,775
// ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.repository.hdfs.service; import java.util.List; import java.util.Map; import org.talend.core.AbstractRepositoryContextUpdateService; import org.talend.core.hadoop.repository.HadoopRepositoryUtil; import org.talend.core.model.metadata.builder.connection.Connection; import org.talend.repository.model.hdfs.HDFSConnection; /** * created by ldong on Mar 18, 2015 Detailled comment * */ public class HdfsContextUpdateService extends AbstractRepositoryContextUpdateService { @Override public boolean updateContextParameter(Connection conn, String oldValue, String newValue) { boolean isModified = false; if (conn.isContextMode()) { if (conn instanceof HDFSConnection) { HDFSConnection hdfsConn = (HDFSConnection) conn; if (hdfsConn.getUserName() != null && hdfsConn.getUserName().equals(oldValue)) { hdfsConn.setUserName(newValue); isModified = true; } else if (hdfsConn.getRowSeparator() != null && hdfsConn.getRowSeparator().equals(oldValue)) { hdfsConn.setRowSeparator(newValue); isModified = true; } else if (hdfsConn.getHeaderValue() != null && hdfsConn.getHeaderValue().equals(oldValue)) { hdfsConn.setHeaderValue(newValue); isModified = true; } else { List<Map<String, Object>> hadoopProperties = HadoopRepositoryUtil .getHadoopPropertiesList(hdfsConn.getHadoopProperties()); String finalProperties = updateHadoopProperties(hadoopProperties, oldValue, newValue); if (finalProperties != null) { hdfsConn.setHadoopProperties(updateHadoopProperties(hadoopProperties, oldValue, newValue)); isModified = true; } } } } return isModified; } @Override public boolean accept(Connection connection) { if (connection instanceof HDFSConnection) { return true; } return false; } }
41.41791
116
0.584144
2e40753043cca3868936fd2325cc6cf873c1091c
453
package com.spring4.email; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * Creator weishi8 * Date&Time 2019-07-11 18:12 * description */ //@SpringBootApplication public class EmailApplication { public static void main(String[] args) { SpringApplication.run(EmailApplication.class, args); } }
25.166667
68
0.774834
412f2244b5e445888d8b39987b045fedbe19d4df
1,573
package scratch.kevin.ucerf3.inversion; import java.io.File; import java.io.IOException; import java.util.Map; import scratch.UCERF3.inversion.BatchPlotGen; public class MisfitComparison { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Map<String, Double> shortMisfits = BatchPlotGen.loadMisfitsFile( new File("/tmp/FM2_1_UC2ALL_Shaw09Mod_DsrUni_CharConst_M5Rate8.7_MMaxOff7.6_NoFix_SpatSeisU2_VarPaleo1_VarSectNuclMFDWt0.01_sol.zip.misfits")); Map<String, Double> longMisfits = BatchPlotGen.loadMisfitsFile( new File("/tmp/FM2_1_UC2ALL_Shaw09Mod_DsrUni_CharConst_M5Rate8.7_MMaxOff7.6_NoFix_SpatSeisU2_VarPaleo1_run00_sol.zip.misfits")); for (String key : shortMisfits.keySet()) { Double shortMisfit = Math.sqrt(shortMisfits.get(key)); Double longMisfit = Math.sqrt(longMisfits.get(key)); double p_imp = (shortMisfit - longMisfit) / shortMisfit; p_imp *= 100; System.out.println(key+":\t "+shortMisfit+" => "+longMisfit+"\t("+(float)p_imp+" % improvement)"); } // double[] runLengths = { 3, 4, 6, 500d/60d }; double[] runLengths = { 3, 4, 6, 8 }; double availableHours = 6*24 + 8; // midnight tues night through 8am next tues morn int availableNodes = 60; for (double runLength : runLengths) { double padRunLength = runLength + 0.5; // for processing time int runs = 0; for (double hours=0; hours+padRunLength<availableHours; hours+=padRunLength) runs += availableNodes; System.out.println((int)runLength+" hrs: "+runs+" runs"); } } }
35.75
147
0.724094
53ac7a8e1fd88c4bea1e2a9e2cb012d55f847858
2,592
package io.jiffy.stax.plugin.xfs.factories; import com.ibm.staf.service.stax.*; import io.jiffy.stax.plugin.xfs.actions.XfsServiceAction; import org.pmw.tinylog.Logger; import org.w3c.dom.Node; public abstract class XfsServiceActionFactory<T extends XfsServiceAction> extends ActionFactorySupport<T> implements STAXJobManagementHandler { public XfsServiceActionFactory(String name, Class<T> clazz) { super(name, clazz); } @Override public void initialize(STAX stax) { stax.registerJobManagementHandler(this); } @Override public void initJob(STAXJob job) { } @Override public void terminateJob(STAXJob job) { } /** * XFS service(eg. ptr,cim,cdm,epp) 下面可以跟任何%task% elements * 代码逻辑参考STAXBlockActionFactory * @param action * @param child */ @Override protected void handleChildNode(STAX staxService, STAXJob job, T action, Node root, Node child) throws STAXException { STAXAction serviceAction = action.getAction(); if (serviceAction != null) { action.setElementInfo( new STAXElementInfo(root.getNodeName(), STAXElementInfo.NO_ATTRIBUTE_NAME, STAXElementInfo.LAST_ELEMENT_INDEX, child.getNodeName())); Logger.error("{} 只能包含一个要执行的action", action.getElement()); throw new STAXInvalidXMLElementCountException(STAXUtil.formatErrorMessage(action), action); } STAXActionFactory factory = staxService.getActionFactory(child.getNodeName()); if (factory == null) { action.setElementInfo( new STAXElementInfo( root.getNodeName(), STAXElementInfo.NO_ATTRIBUTE_NAME, STAXElementInfo.LAST_ELEMENT_INDEX, "No action factory for element type \"" + child.getNodeName() + "\"")); Logger.error("No action factory for element type {}", child.getNodeName()); throw new STAXInvalidXMLElementException(STAXUtil.formatErrorMessage(action), action); } serviceAction = factory.parseAction(staxService, job, child); if(serviceAction == null) { Logger.error("无法解析 {}", child.getNodeName()); throw new STAXInvalidXMLElementCountException(STAXUtil.formatErrorMessage(action), action); } action.setAction(serviceAction); } }
35.506849
144
0.613426
60cbb1e48cc512fb35949ada3c082a1b03cd7ae1
6,010
package org.firstinspires.ftc.teamcode.odometry; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.localization.ThreeTrackingWheelLocalizer; import com.acmerobotics.roadrunner.util.Angle; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.teamcode.util.Encoder; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collections; import java.util.List; /* * Sample tracking wheel localizer implementation assuming the standard configuration: * * /--------------\ * | ____ | * | ---- | * | || || | * | || || | * | | * | | * \--------------/ * */ @Config public class StandardTrackingWheelLocalizerIMU extends ThreeTrackingWheelLocalizer { public static double TICKS_PER_REV = 8192; public static double WHEEL_RADIUS = 0.6889764; // in public static double GEAR_RATIO = 1; // output (wheel) speed / input (encoder) speed public static double LATERAL_DISTANCE = 4.8689017098 ; // in; distance between the left and right wheels //4.8972898307766055 8 deg under //4.886553189202017 5 deg over //4.874816607843807 public static double FORWARD_OFFSET = -0.27; // in; offset of the lateral wheel public static double X_MULTIPLIER = 1.007575126893; public static double Y_MULTIPLIER = 1.011849600972945; public static double MIN_IMU_UPDATE_INTERVAL = 0.5; public static double MIN_STABLE_HEADING_TIME = 0.2; public static double HEADING_EPSILON = Math.toRadians(0.5); private OdometryMecanumDriveIMU drive; private Encoder leftEncoder, rightEncoder, frontEncoder; private double baseExtHeading; private ElapsedTime lastIMUUpdateTimer = new ElapsedTime(); private ElapsedTime stableHeadingTimer = new ElapsedTime(); private double stableCheckHeading; private List<Double> cachedWheelPositions = Collections.emptyList(); private List<Double> cachedWheelVelocities = Collections.emptyList(); private boolean useCachedWheelData = false; public StandardTrackingWheelLocalizerIMU(HardwareMap hardwareMap, OdometryMecanumDriveIMU drive) { super(Arrays.asList( new Pose2d(0, LATERAL_DISTANCE / 2, 0), // left new Pose2d(0, -LATERAL_DISTANCE / 2, 0), // right new Pose2d(FORWARD_OFFSET, 0, Math.toRadians(90)) // front )); this.drive = drive; leftEncoder = new Encoder(hardwareMap.get(DcMotorEx.class, "fl")); rightEncoder = new Encoder(hardwareMap.get(DcMotorEx.class, "intake")); frontEncoder = new Encoder(hardwareMap.get(DcMotorEx.class, "bl")); leftEncoder.setDirection(Encoder.Direction.FORWARD); rightEncoder.setDirection(Encoder.Direction.FORWARD); frontEncoder.setDirection(Encoder.Direction.REVERSE); } private double getRawExternalHeading() { return drive.getRawExternalHeading(); } private double getExternalHeading() { return Angle.norm(getRawExternalHeading() - baseExtHeading); } @Override public void setPoseEstimate(@NotNull Pose2d pose) { baseExtHeading = Angle.norm(getRawExternalHeading() - pose.getHeading()); super.setPoseEstimate(pose); } @Override public void update() { double currentHeading = getPoseEstimate().getHeading(); // reset timer and stableCheckHeading if our heading has changed too much if (Math.abs(Angle.normDelta(currentHeading - stableCheckHeading)) > HEADING_EPSILON) { stableHeadingTimer.reset(); stableCheckHeading = currentHeading; } if (lastIMUUpdateTimer.seconds() > MIN_IMU_UPDATE_INTERVAL && stableHeadingTimer.seconds() > MIN_STABLE_HEADING_TIME) { lastIMUUpdateTimer.reset(); // load in the latest wheel positions and update to apply to pose super.update(); double extHeading = getExternalHeading(); Pose2d pose = new Pose2d(getPoseEstimate().vec(), extHeading); super.setPoseEstimate(pose); // Don't update with new positions, but instead use previous (internally cached) wheel positions. // This ensures wheel movement isn't "lost" when the lastWheelPositions list (this list is internal to the // ThreeTrackingWheelLocalizer/super class) is emptied with our call to setPoseEstimate. Calling update // fills super's lastWheelPositions with the cached wheel positions and allows the later update calls to // increment the pose rather than simply filling the empty lastWheelPositions list. useCachedWheelData = true; super.update(); useCachedWheelData = false; } else { super.update(); } } public static double encoderTicksToInches(double ticks) { return WHEEL_RADIUS * 2 * Math.PI * GEAR_RATIO * ticks / TICKS_PER_REV; } @NonNull @Override public List<Double> getWheelPositions() { return Arrays.asList( encoderTicksToInches(leftEncoder.getCurrentPosition()) * X_MULTIPLIER, encoderTicksToInches(rightEncoder.getCurrentPosition()) * X_MULTIPLIER, encoderTicksToInches(frontEncoder.getCurrentPosition()) * Y_MULTIPLIER ); } @NonNull @Override public List<Double> getWheelVelocities() { return Arrays.asList( encoderTicksToInches(leftEncoder.getCorrectedVelocity()) * X_MULTIPLIER, encoderTicksToInches(rightEncoder.getCorrectedVelocity()) * X_MULTIPLIER, encoderTicksToInches(frontEncoder.getCorrectedVelocity()) * Y_MULTIPLIER ); } }
38.280255
118
0.682363
85efc0977b9e9d496b9d495fe13d23af8c3bfff9
579
package algorithms.lru; /** * @author xiaoy * @date 2020/05/14 */ import java.util.LinkedHashMap; import java.util.Map; public class LRUCacheT<K, V> extends LinkedHashMap<K, V> { // 最大容量 private final int maximumSize; public LRUCacheT(final int maximumSize) { // true代表按访问顺序排序,false代表按插入顺序 super(maximumSize, 0.75f, true); this.maximumSize = maximumSize; } /** * 当节点数大于最大容量时,就删除最旧的元素 */ @Override protected boolean removeEldestEntry(final Map.Entry eldest) { return size() > this.maximumSize; } }
19.965517
65
0.645941
25728a382df9c421d130fa08934c2cd763c9876d
6,745
package oasis.names.tc.legalxml_courtfiling.wsdl.webservicesprofile_definitions_4_0; /** * Please modify this class to meet your needs * This class is not complete */ import java.io.File; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import tyler.efm.wsdl.webservicesprofile_implementation_4_0.CourtRecordMDEService; /** * This class was generated by Apache CXF 3.5.0-SNAPSHOT-3e40a2387febaf00f47fe893d97ffdf63aaa4626 * 2021-07-21T17:05:34.856-04:00 * Generated source version: 3.5.0-SNAPSHOT * */ public final class CourtRecordMDEPort_CourtRecordMDEPort_Client { private static final QName SERVICE_NAME = new QName("urn:tyler:efm:wsdl:WebServicesProfile-Implementation-4.0", "CourtRecordMDEService"); private CourtRecordMDEPort_CourtRecordMDEPort_Client() { } public static void main(String args[]) throws java.lang.Exception { URL wsdlURL = CourtRecordMDEService.WSDL_LOCATION; if (args.length > 0 && args[0] != null && !"".equals(args[0])) { File wsdlFile = new File(args[0]); try { if (wsdlFile.exists()) { wsdlURL = wsdlFile.toURI().toURL(); } else { wsdlURL = new URL(args[0]); } } catch (MalformedURLException e) { e.printStackTrace(); } } CourtRecordMDEService ss = new CourtRecordMDEService(wsdlURL, SERVICE_NAME); CourtRecordMDEPort port = ss.getCourtRecordMDEPort(); { System.out.println("Invoking recordFiling..."); oasis.names.tc.legalxml_courtfiling.wsdl.webservicesprofile_definitions_4.RecordFilingRequestMessageType _recordFiling_recordFilingRequestMessage = null; oasis.names.tc.legalxml_courtfiling.schema.xsd.messagereceiptmessage_4.MessageReceiptMessageType _recordFiling__return = port.recordFiling(_recordFiling_recordFilingRequestMessage); System.out.println("recordFiling.result=" + _recordFiling__return); } { System.out.println("Invoking notifyService..."); tyler.ecf.extensions.notifyservicemessage.NotifyServiceMessageType _notifyService_notifyServiceMessage = null; oasis.names.tc.legalxml_courtfiling.schema.xsd.messagereceiptmessage_4.MessageReceiptMessageType _notifyService__return = port.notifyService(_notifyService_notifyServiceMessage); System.out.println("notifyService.result=" + _notifyService__return); } { System.out.println("Invoking createCase..."); tyler.ecf.extensions.createcasemessage.CreateCaseMessageType _createCase_createCaseMessage = null; oasis.names.tc.legalxml_courtfiling.schema.xsd.messagereceiptmessage_4.MessageReceiptMessageType _createCase__return = port.createCase(_createCase_createCaseMessage); System.out.println("createCase.result=" + _createCase__return); } { System.out.println("Invoking notifyReceiptComplete..."); tyler.ecf.extensions.notifyreceiptmessage.NotifyReceiptMessageType _notifyReceiptComplete_notifyReceiptMessage = null; oasis.names.tc.legalxml_courtfiling.schema.xsd.messagereceiptmessage_4.MessageReceiptMessageType _notifyReceiptComplete__return = port.notifyReceiptComplete(_notifyReceiptComplete_notifyReceiptMessage); System.out.println("notifyReceiptComplete.result=" + _notifyReceiptComplete__return); } { System.out.println("Invoking getCase..."); oasis.names.tc.legalxml_courtfiling.schema.xsd.casequerymessage_4.CaseQueryMessageType _getCase_caseQueryMessage = null; oasis.names.tc.legalxml_courtfiling.schema.xsd.caseresponsemessage_4.CaseResponseMessageType _getCase__return = port.getCase(_getCase_caseQueryMessage); System.out.println("getCase.result=" + _getCase__return); } { System.out.println("Invoking getServiceAttachCaseList..."); tyler.ecf.extensions.serviceattachcaselistquerymessage.ServiceAttachCaseListQueryMessageType _getServiceAttachCaseList_serviceAttachCaseListQueryMessage = null; tyler.ecf.extensions.serviceattachcaselistresponsemessage.ServiceAttachCaseListResponseMessageType _getServiceAttachCaseList__return = port.getServiceAttachCaseList(_getServiceAttachCaseList_serviceAttachCaseListQueryMessage); System.out.println("getServiceAttachCaseList.result=" + _getServiceAttachCaseList__return); } { System.out.println("Invoking getCaseList..."); oasis.names.tc.legalxml_courtfiling.schema.xsd.caselistquerymessage_4.CaseListQueryMessageType _getCaseList_caseListQueryMessage = null; oasis.names.tc.legalxml_courtfiling.schema.xsd.caselistresponsemessage_4.CaseListResponseMessageType _getCaseList__return = port.getCaseList(_getCaseList_caseListQueryMessage); System.out.println("getCaseList.result=" + _getCaseList__return); } { System.out.println("Invoking getDocument..."); oasis.names.tc.legalxml_courtfiling.schema.xsd.documentquerymessage_4.DocumentQueryMessageType _getDocument_documentQueryMessage = null; oasis.names.tc.legalxml_courtfiling.schema.xsd.documentresponsemessage_4.DocumentResponseMessageType _getDocument__return = port.getDocument(_getDocument_documentQueryMessage); System.out.println("getDocument.result=" + _getDocument__return); } { System.out.println("Invoking getServiceInformation..."); oasis.names.tc.legalxml_courtfiling.schema.xsd.serviceinformationquerymessage_4.ServiceInformationQueryMessageType _getServiceInformation_serviceInformationQueryMessage = null; oasis.names.tc.legalxml_courtfiling.schema.xsd.serviceinformationresponsemessage_4.ServiceInformationResponseMessageType _getServiceInformation__return = port.getServiceInformation(_getServiceInformation_serviceInformationQueryMessage); System.out.println("getServiceInformation.result=" + _getServiceInformation__return); } { System.out.println("Invoking getServiceInformationHistory..."); tyler.ecf.extensions.serviceinformationhistoryquerymessage.ServiceInformationHistoryQueryMessageType _getServiceInformationHistory_serviceInformationHistoryQueryMessage = null; tyler.ecf.extensions.serviceinformationhistoryresponsemessage.ServiceInformationHistoryResponseMessageType _getServiceInformationHistory__return = port.getServiceInformationHistory(_getServiceInformationHistory_serviceInformationHistoryQueryMessage); System.out.println("getServiceInformationHistory.result=" + _getServiceInformationHistory__return); } System.exit(0); } }
51.48855
258
0.764122
b3e35fa49c8d200a13fbc378c29d440823b0d731
7,517
package cn.originx.uca.commerce; import cn.originx.refine.Ox; import cn.originx.scaffold.plugin.AspectSwitcher; import cn.originx.uca.log.TrackIo; import io.vertx.core.Future; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.tp.atom.modeling.builtin.DataAtom; import io.vertx.tp.atom.refine.Ao; import io.vertx.up.atom.record.Apt; import io.vertx.up.commune.element.JSix; import io.vertx.up.commune.exchange.DFabric; import io.vertx.up.eon.em.ChangeFlag; import io.vertx.up.experiment.mixture.HDao; import io.vertx.up.uca.cache.Cc; import io.vertx.up.unity.Ux; import io.vertx.up.util.Ut; import java.util.*; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; /** * @author <a href="http://www.origin-x.cn">Lang</a> */ @SuppressWarnings("all") public class Arms { private static final Cc<String, Arms> CC_ARMS = Cc.open(); private final transient DataAtom atom; private final transient HDao dao; private final transient TrackIo io; private final transient Set<ChangeFlag> types = new HashSet<ChangeFlag>() { { this.add(ChangeFlag.DELETE); this.add(ChangeFlag.UPDATE); this.add(ChangeFlag.ADD); } }; private transient DFabric fabric; private Function<JsonArray, JsonArray> fnDefault; private Supplier<Future<JsonArray>> fnFetcher; public Arms(final HDao dao, final DataAtom atom) { this.dao = dao; this.atom = atom; this.io = TrackIo.create(atom, dao); } public static <T extends Arms> T create(final HDao dao, final DataAtom atom) { return (T) CC_ARMS.pick(() -> new Arms(dao, atom), atom.identifier()); } protected DataAtom atom() { return this.atom; } protected HDao dao() { return this.dao; } public <T extends Arms> T bind(final DFabric fabric) { this.fabric = fabric; return (T) this; } public <T extends Arms> T bind(final ChangeFlag... types) { this.types.clear(); this.types.addAll(Arrays.asList(types)); return (T) this; } public <T extends Arms> T bindFn(final Function<JsonArray, JsonArray> fnDefault) { this.fnDefault = fnDefault; return (T) this; } public <T extends Arms> T bindFn(final Supplier<Future<JsonArray>> fnFetcher) { this.fnFetcher = fnFetcher; return (T) this; } /* * 两种方式读取数据 * 1. 带条件 * 2. 不带条件 */ public Future<JsonArray> saveAsync(final JsonArray recordData, final JsonObject options) { return this.saveAsync(null, recordData, options); } public Future<JsonArray> saveAsync(final JsonObject criteria, final JsonArray recordData, final JsonObject options) { Ao.infoUca(this.getClass(), "原始输入数据:{0},原始配置:{1}", recordData.encode(), options.encode()); /* * 构造 AoHex * { * "components": { * } * } */ final JSix hex = JSix.create(options); /* * 第一步:清洗数据 * 1)检查数据合法性 * 2)写日志、做过滤 * Record[] -> JsonArray */ return this.fetchAsync(criteria) /* 合并旧数据和新数据 */ .compose(original -> Ux.future(Apt.create(original, recordData))) /* 按标识规则对比结果 */ .compose(apt -> Ux.future(Ao.diffPure(apt, this.atom, Ox.ignorePure(this.atom)).compared())) /* 变更表 */ .compose(map -> { /* * 处理不同类型的数据 */ Ox.Log.infoReport(this.getClass(), map); final List<Future<JsonArray>> futures = new ArrayList<>(); /* * 只执行操作类型 */ if (this.types.contains(ChangeFlag.ADD)) { futures.add(this.addRecord(map.get(ChangeFlag.ADD), hex.batch(ChangeFlag.ADD))); } if (this.types.contains(ChangeFlag.UPDATE)) { futures.add(this.updateRecord(map.get(ChangeFlag.UPDATE), hex.batch(ChangeFlag.UPDATE))); } if (this.types.contains(ChangeFlag.DELETE)) { futures.add(this.deleteRecord(map.get(ChangeFlag.DELETE), hex.batch(ChangeFlag.DELETE))); } return Ux.thenCombineArray(futures); }); } protected Class<?> completerCls() { return CompleterDefault.class; } // ------------------- 下边全是私有函数 -------------------- private Future<JsonArray> fetchAsync(final JsonObject criteria) { if (Objects.isNull(this.fnFetcher)) { if (Ut.isNil(criteria)) { return this.dao.fetchAllAsync().compose(Ux::futureA); } else { return this.dao.fetchAsync(Ut.valueJObject(criteria)).compose(Ux::futureA); } } else { return this.fnFetcher.get(); } } private Future<JsonArray> deleteRecord(final JsonArray data, final JsonObject options) { return this.processAsync(data, options, (atomy, aspect) -> { /* Completer构造 */ final Completer completer = Completer.create(this.completerCls(), this.dao, this.atom).bind(options); final JsonArray original = atomy.dataO(); return aspect.run(original, processed -> completer.remove(processed) /* 变更历史 */ .compose(nil -> this.io.procAsync(null, original, options, original.size())) ); }); } private Future<JsonArray> updateRecord(final JsonArray data, final JsonObject options) { return this.processAsync(data, options, (atomy, aspect) -> { /* Completer构造 */ final Completer completer = Completer.create(this.completerCls(), this.dao, this.atom).bind(options); final JsonArray input = atomy.comparedU(); /* Input / Assert */ return aspect.run(input, processed -> completer.update(processed) /* 变更历史 */ .compose(updated -> this.io.procAsync(updated, atomy.dataO(), options, updated.size())) ); }); } private Future<JsonArray> addRecord(final JsonArray data, final JsonObject options) { return this.processAsync(data, options, (atomy, aspect) -> { /* Completer构造 */ final Completer completer = Completer.create(this.completerCls(), this.dao, this.atom).bind(options); JsonArray input = atomy.comparedA(); /* fnDefault默认值专用函数 */ if (Objects.nonNull(this.fnDefault)) { input = this.fnDefault.apply(input); } return aspect.run(input, processed -> completer.create(processed) /* 变更历史 */ .compose(created -> this.io.procAsync(created, null, options, created.size())) ); }); } private Future<JsonArray> processAsync(final JsonArray input, final JsonObject options, final BiFunction<Apt, AspectSwitcher, Future<JsonArray>> consumer) { if (input.isEmpty()) { return Ux.future(new JsonArray()); } else { final Apt apt = Ux.ruleApt(input, false); /* Aspect插件 */ final AspectSwitcher aspect = new AspectSwitcher(this.atom, options, this.fabric); return consumer.apply(apt, aspect); } } }
35.457547
121
0.585473
b4fbc18812195f1daf99bf4a19a7c6f2b6557f6b
3,062
package com.google.example.firestore; import android.util.Log; import androidx.annotation.NonNull; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.LoadBundleTask; import com.google.firebase.firestore.LoadBundleTaskProgress; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QuerySnapshot; import com.google.firebase.firestore.Source; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * https://firebase.google.com/docs/firestore/solutions/serve-bundles */ public class SolutionBundles { private static final String TAG = "SolutionBundles"; private FirebaseFirestore db; // [START fs_bundle_load] public InputStream getBundleStream(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); return connection.getInputStream(); } public void fetchBundleFrom() throws IOException { final InputStream bundleStream = getBundleStream("https://example.com/createBundle"); LoadBundleTask loadTask = db.loadBundle(bundleStream); // Chain the following tasks // 1) Load the bundle // 2) Get the named query from the local cache // 3) Execute a get() on the named query loadTask.continueWithTask(new Continuation<LoadBundleTaskProgress, Task<Query>>() { @Override public Task<Query> then(@NonNull Task<LoadBundleTaskProgress> task) throws Exception { // Close the stream bundleStream.close(); // Calling getResult() propagates errors LoadBundleTaskProgress progress = task.getResult(Exception.class); // Get the named query from the bundle cache return db.getNamedQuery("latest-stories-query"); } }).continueWithTask(new Continuation<Query, Task<QuerySnapshot>>() { @Override public Task<QuerySnapshot> then(@NonNull Task<Query> task) throws Exception { Query query = task.getResult(Exception.class); // get() the query results from the cache return query.get(Source.CACHE); } }).addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (!task.isSuccessful()) { Log.w(TAG, "Bundle loading failed", task.getException()); return; } // Get the QuerySnapshot from the bundle QuerySnapshot storiesSnap = task.getResult(); // Use the results // ... } }); } // [END fs_bundle_load] }
35.604651
98
0.653494
60f4d9f8bea071e307851c46e7bcb74bac337ee7
972
package org.openmrs.module.initializer.api.ot; import org.openmrs.OrderType; import org.openmrs.api.OrderService; import org.openmrs.module.initializer.Domain; import org.openmrs.module.initializer.api.BaseLineProcessor; import org.openmrs.module.initializer.api.CsvParser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component public class OrderTypesCsvParser extends CsvParser<OrderType, BaseLineProcessor<OrderType>> { private OrderService orderService; @Autowired public OrderTypesCsvParser(@Qualifier("orderService") OrderService orderService, OrderTypeLineProcessor processor) { super(processor); this.orderService = orderService; } @Override public Domain getDomain() { return Domain.ORDER_TYPES; } @Override protected OrderType save(OrderType instance) { return orderService.saveOrderType(instance); } }
29.454545
117
0.81893
b18edc3f53620bef74c053f31ab715c154f0568a
1,046
package com.twitter.finatra.http.tests.integration.doeverything.main; import java.util.ArrayList; import java.util.Collection; import scala.collection.JavaConverters; import scala.collection.Seq; import com.google.common.collect.ImmutableList; import com.google.inject.Module; import com.twitter.app.Flag; import com.twitter.app.Flaggable; import com.twitter.inject.TwitterModule; public class TestModuleB extends TwitterModule { private Flag<Float> moduleBFlag = createMandatoryFlag( "moduleB.flag", "help text", "usage text", Flaggable.ofJavaFloat() ); @Override public Seq<Module> modules() { ArrayList<Module> m = new ArrayList<>(); m.add(new TestModuleA()); return JavaConverters.asScalaIteratorConverter(m.iterator()).asScala().toSeq(); } @Override public Collection<Module> javaModules() { return ImmutableList.<Module>of( new TestModuleC()); } @Override public void configure() { assert moduleBFlag.isDefined(); assert moduleBFlag.apply() != null; } }
24.325581
83
0.724665
6ecca004f7bebf40b68574dac55600e3f399fd6f
3,101
import java.util.List; /** * Simulates an ultrasonic sensor that works on the internal representation of * the robot. * * @author Johannes * */ public class UltrasonicSensor { /** * What is measured if no obstacle is detected? 1^=5cm */ static final int NOTHING_RECOGNIZED_MEASURE = 51; private Surrounding surrounding; public UltrasonicSensor(Surrounding surrounding) { this.surrounding = surrounding; } /** * Determines what the front sensor would measure given the state of * reference car and the given surrounding. * * @param referenceCar * @return */ public int measureFront(Car referenceCar) { List<DoubleLine> sensorLines = RobotKnowledge .getFrontSensorLines(referenceCar); return sense(sensorLines, referenceCar); } /** * Determines what the back sensor would measure given the state of * reference car and the given surrounding. * * @param referenceCar * @return */ public int measureBack(Car referenceCar) { List<DoubleLine> sensorLines = RobotKnowledge .getBackSensorLines(referenceCar); return sense(sensorLines, referenceCar); } /** * Sends out rays by further and further offsetting points until they hit * something. * * @param sensorLines * @return */ int sense(List<DoubleLine> sensorLines, Car referenceCar) { // Minimum measure of all sensor lines double min = RobotKnowledge.getMaxMeasure(); DoublePoint referenceCarPosition = referenceCar.getState() .getPosition(); double minDistance = surrounding.distanceToNonPassableArea( (byte) referenceCarPosition.getX(), (byte) referenceCarPosition.getY()); for (DoubleLine sensorLine : sensorLines) { // Get offset values double dx = sensorLine.getP2().getX() - sensorLine.getP1().getX(); double dy = sensorLine.getP2().getY() - sensorLine.getP1().getY(); // The ratio of dx and dy is preserved, but either dx or dy (the // greater one) is normalized to 1 or -1 if (Math.abs(dx) > Math.abs(dy)) { dy = dy / Math.abs(dx); dx = dx > 0 ? 1. : -1.; } else { dx = dx / Math.abs(dy); dy = dy > 0 ? 1. : -1.; } // Point that is send out and further and further ofsetted by dx and // dy DoublePoint current = new DoublePoint(sensorLine.getP2()); // Start with minDistance double oneStepDistance = Math.sqrt(dx * dx + dy * dy); current.setX(current.getX() + (minDistance / oneStepDistance) * dx); current.setY(current.getY() + (minDistance / oneStepDistance) * dy); do { current.setX(current.getX() + dx); current.setY(current.getY() + dy); } while (surrounding.isIn(current.toPoint()) && Geometry.euclideanDist(sensorLine.getP2(), current) < RobotKnowledge .getMaxMeasure()); double distance = Geometry.euclideanDist(sensorLine.getP2(), current); if (distance >= RobotKnowledge.getMaxMeasure()) { distance = NOTHING_RECOGNIZED_MEASURE; } if (distance < min) { min = distance; } } // Convert to actual centimeters to be comparable with actual // measurement. return RobotKnowledge.getMeasureFront(min); } }
28.981308
78
0.68752
b07db661adb535f11492b32982a428dd7a0e8922
23,113
/** Generated Assertion Class - DO NOT CHANGE */ package au.org.greekwelfaresa.idempiere.test.assertj.c_bpartner; import au.org.greekwelfaresa.idempiere.test.assertj.po.AbstractPOAssert; import java.util.Objects; import javax.annotation.Generated; import org.compiere.model.X_C_BPartner; /** Generated assertion class for C_BPartner * @author idempiere-test (generated) * @version Release 6.2 - $Id: b07db661adb535f11492b32982a428dd7a0e8922 $ */ @Generated("class au.org.greekwelfaresa.idempiere.test.generator.ModelAssertionGenerator") public abstract class AbstractC_BPartnerAssert<SELF extends AbstractC_BPartnerAssert<SELF, ACTUAL>, ACTUAL extends X_C_BPartner> extends AbstractPOAssert<SELF, ACTUAL> { /** Standard Constructor */ public AbstractC_BPartnerAssert (ACTUAL actual, Class<SELF> selfType) { super (actual, selfType); } public SELF hasAcqusitionCost(Object expected) { isNotNull(); bdAssert("AcqusitionCost", actual.getAcqusitionCost(), expected); return myself; } public SELF hasActualLifeTimeValue(Object expected) { isNotNull(); bdAssert("ActualLifeTimeValue", actual.getActualLifeTimeValue(), expected); return myself; } public SELF hasAD_Language(String expected) { isNotNull(); String actualField = actual.getAD_Language(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have AD_Language: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasBPartner_Parent_ID(int expected) { isNotNull(); int actualField = actual.getBPartner_Parent_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have BPartner_Parent_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasC_BP_Group_ID(int expected) { isNotNull(); int actualField = actual.getC_BP_Group_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have C_BP_Group_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasC_BPartner_ID(int expected) { isNotNull(); int actualField = actual.getC_BPartner_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have C_BPartner_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasC_BPartner_UU(String expected) { isNotNull(); String actualField = actual.getC_BPartner_UU(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have C_BPartner_UU: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasC_Dunning_ID(int expected) { isNotNull(); int actualField = actual.getC_Dunning_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have C_Dunning_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasC_Greeting_ID(int expected) { isNotNull(); int actualField = actual.getC_Greeting_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have C_Greeting_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasC_InvoiceSchedule_ID(int expected) { isNotNull(); int actualField = actual.getC_InvoiceSchedule_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have C_InvoiceSchedule_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasC_PaymentTerm_ID(int expected) { isNotNull(); int actualField = actual.getC_PaymentTerm_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have C_PaymentTerm_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasCustomerProfileID(String expected) { isNotNull(); String actualField = actual.getCustomerProfileID(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have CustomerProfileID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasDefault1099Box_ID(int expected) { isNotNull(); int actualField = actual.getDefault1099Box_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Default1099Box_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasDeliveryRule(String expected) { isNotNull(); String actualField = actual.getDeliveryRule(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have DeliveryRule: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasDeliveryViaRule(String expected) { isNotNull(); String actualField = actual.getDeliveryViaRule(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have DeliveryViaRule: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasDescription(String expected) { isNotNull(); String actualField = actual.getDescription(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Description: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasDocumentCopies(int expected) { isNotNull(); int actualField = actual.getDocumentCopies(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have DocumentCopies: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasDunningGrace(Object expected) { isNotNull(); dateAssert("DunningGrace", actual.getDunningGrace(), expected); return myself; } public SELF hasDUNS(String expected) { isNotNull(); String actualField = actual.getDUNS(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have DUNS: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasFirstSale(Object expected) { isNotNull(); dateAssert("FirstSale", actual.getFirstSale(), expected); return myself; } public SELF hasFlatDiscount(Object expected) { isNotNull(); bdAssert("FlatDiscount", actual.getFlatDiscount(), expected); return myself; } public SELF hasFreightCostRule(String expected) { isNotNull(); String actualField = actual.getFreightCostRule(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have FreightCostRule: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasInvoice_PrintFormat_ID(int expected) { isNotNull(); int actualField = actual.getInvoice_PrintFormat_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Invoice_PrintFormat_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasInvoiceRule(String expected) { isNotNull(); String actualField = actual.getInvoiceRule(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have InvoiceRule: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF is1099Vendor() { isNotNull(); if (!actual.is1099Vendor()) { failWithMessage("\nExpecting PO:\n <%s>\nto be 1099Vendor\nbut it was not", getPODescription()); } return myself; } public SELF isNot1099Vendor() { isNotNull(); if (actual.is1099Vendor()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be 1099Vendor\nbut it was", getPODescription()); } return myself; } public SELF isCustomer() { isNotNull(); if (!actual.isCustomer()) { failWithMessage("\nExpecting PO:\n <%s>\nto be Customer\nbut it was not", getPODescription()); } return myself; } public SELF isNotCustomer() { isNotNull(); if (actual.isCustomer()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be Customer\nbut it was", getPODescription()); } return myself; } public SELF isDiscountPrinted() { isNotNull(); if (!actual.isDiscountPrinted()) { failWithMessage("\nExpecting PO:\n <%s>\nto be DiscountPrinted\nbut it was not", getPODescription()); } return myself; } public SELF isNotDiscountPrinted() { isNotNull(); if (actual.isDiscountPrinted()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be DiscountPrinted\nbut it was", getPODescription()); } return myself; } public SELF isEmployee() { isNotNull(); if (!actual.isEmployee()) { failWithMessage("\nExpecting PO:\n <%s>\nto be Employee\nbut it was not", getPODescription()); } return myself; } public SELF isNotEmployee() { isNotNull(); if (actual.isEmployee()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be Employee\nbut it was", getPODescription()); } return myself; } public SELF isManufacturer() { isNotNull(); if (!actual.isManufacturer()) { failWithMessage("\nExpecting PO:\n <%s>\nto be Manufacturer\nbut it was not", getPODescription()); } return myself; } public SELF isNotManufacturer() { isNotNull(); if (actual.isManufacturer()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be Manufacturer\nbut it was", getPODescription()); } return myself; } public SELF isOneTime() { isNotNull(); if (!actual.isOneTime()) { failWithMessage("\nExpecting PO:\n <%s>\nto be OneTime\nbut it was not", getPODescription()); } return myself; } public SELF isNotOneTime() { isNotNull(); if (actual.isOneTime()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be OneTime\nbut it was", getPODescription()); } return myself; } public SELF isPOTaxExempt() { isNotNull(); if (!actual.isPOTaxExempt()) { failWithMessage("\nExpecting PO:\n <%s>\nto be POTaxExempt\nbut it was not", getPODescription()); } return myself; } public SELF isNotPOTaxExempt() { isNotNull(); if (actual.isPOTaxExempt()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be POTaxExempt\nbut it was", getPODescription()); } return myself; } public SELF isProspect() { isNotNull(); if (!actual.isProspect()) { failWithMessage("\nExpecting PO:\n <%s>\nto be Prospect\nbut it was not", getPODescription()); } return myself; } public SELF isNotProspect() { isNotNull(); if (actual.isProspect()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be Prospect\nbut it was", getPODescription()); } return myself; } public SELF isSalesRep() { isNotNull(); if (!actual.isSalesRep()) { failWithMessage("\nExpecting PO:\n <%s>\nto be SalesRep\nbut it was not", getPODescription()); } return myself; } public SELF isNotSalesRep() { isNotNull(); if (actual.isSalesRep()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be SalesRep\nbut it was", getPODescription()); } return myself; } public SELF isSummary() { isNotNull(); if (!actual.isSummary()) { failWithMessage("\nExpecting PO:\n <%s>\nto be Summary\nbut it was not", getPODescription()); } return myself; } public SELF isNotSummary() { isNotNull(); if (actual.isSummary()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be Summary\nbut it was", getPODescription()); } return myself; } public SELF isTaxExempt() { isNotNull(); if (!actual.isTaxExempt()) { failWithMessage("\nExpecting PO:\n <%s>\nto be TaxExempt\nbut it was not", getPODescription()); } return myself; } public SELF isNotTaxExempt() { isNotNull(); if (actual.isTaxExempt()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be TaxExempt\nbut it was", getPODescription()); } return myself; } public SELF isVendor() { isNotNull(); if (!actual.isVendor()) { failWithMessage("\nExpecting PO:\n <%s>\nto be Vendor\nbut it was not", getPODescription()); } return myself; } public SELF isNotVendor() { isNotNull(); if (actual.isVendor()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be Vendor\nbut it was", getPODescription()); } return myself; } public SELF hasLogo_ID(int expected) { isNotNull(); int actualField = actual.getLogo_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Logo_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasM_DiscountSchema_ID(int expected) { isNotNull(); int actualField = actual.getM_DiscountSchema_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have M_DiscountSchema_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasM_PriceList_ID(int expected) { isNotNull(); int actualField = actual.getM_PriceList_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have M_PriceList_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasNAICS(String expected) { isNotNull(); String actualField = actual.getNAICS(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have NAICS: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasName(String expected) { isNotNull(); String actualField = actual.getName(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Name: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasName2(String expected) { isNotNull(); String actualField = actual.getName2(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Name2: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasNumberEmployees(int expected) { isNotNull(); int actualField = actual.getNumberEmployees(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have NumberEmployees: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasPaymentRule(String expected) { isNotNull(); String actualField = actual.getPaymentRule(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have PaymentRule: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasPaymentRulePO(String expected) { isNotNull(); String actualField = actual.getPaymentRulePO(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have PaymentRulePO: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasPO_DiscountSchema_ID(int expected) { isNotNull(); int actualField = actual.getPO_DiscountSchema_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have PO_DiscountSchema_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasPO_PaymentTerm_ID(int expected) { isNotNull(); int actualField = actual.getPO_PaymentTerm_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have PO_PaymentTerm_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasPO_PriceList_ID(int expected) { isNotNull(); int actualField = actual.getPO_PriceList_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have PO_PriceList_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasPOReference(String expected) { isNotNull(); String actualField = actual.getPOReference(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have POReference: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasPotentialLifeTimeValue(Object expected) { isNotNull(); bdAssert("PotentialLifeTimeValue", actual.getPotentialLifeTimeValue(), expected); return myself; } public SELF hasRating(String expected) { isNotNull(); String actualField = actual.getRating(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Rating: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasReferenceNo(String expected) { isNotNull(); String actualField = actual.getReferenceNo(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have ReferenceNo: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasSalesRep_ID(int expected) { isNotNull(); int actualField = actual.getSalesRep_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have SalesRep_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasSalesVolume(int expected) { isNotNull(); int actualField = actual.getSalesVolume(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have SalesVolume: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF isSendEMail() { isNotNull(); if (!actual.isSendEMail()) { failWithMessage("\nExpecting PO:\n <%s>\nto be SendEMail\nbut it was not", getPODescription()); } return myself; } public SELF isNotSendEMail() { isNotNull(); if (actual.isSendEMail()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be SendEMail\nbut it was", getPODescription()); } return myself; } public SELF hasShareOfCustomer(int expected) { isNotNull(); int actualField = actual.getShareOfCustomer(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have ShareOfCustomer: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasShelfLifeMinPct(int expected) { isNotNull(); int actualField = actual.getShelfLifeMinPct(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have ShelfLifeMinPct: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasSO_CreditLimit(Object expected) { isNotNull(); bdAssert("SO_CreditLimit", actual.getSO_CreditLimit(), expected); return myself; } public SELF hasSO_CreditUsed(Object expected) { isNotNull(); bdAssert("SO_CreditUsed", actual.getSO_CreditUsed(), expected); return myself; } public SELF hasSO_Description(String expected) { isNotNull(); String actualField = actual.getSO_Description(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have SO_Description: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasSOCreditStatus(String expected) { isNotNull(); String actualField = actual.getSOCreditStatus(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have SOCreditStatus: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasTaxID(String expected) { isNotNull(); String actualField = actual.getTaxID(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have TaxID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasTotalOpenBalance(Object expected) { isNotNull(); bdAssert("TotalOpenBalance", actual.getTotalOpenBalance(), expected); return myself; } public SELF hasURL(String expected) { isNotNull(); String actualField = actual.getURL(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have URL: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasValue(String expected) { isNotNull(); String actualField = actual.getValue(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Value: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } }
27.914251
143
0.697876
871715604f9d9af55c388b1c0793419aae9f5578
4,942
package com.tumblr.backboard.example; import android.app.Fragment; import android.content.res.TypedArray; import android.os.Bundle; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import com.facebook.rebound.Spring; import com.facebook.rebound.SpringSystem; import com.tumblr.backboard.Actor; import com.tumblr.backboard.MotionProperty; import com.tumblr.backboard.imitator.Imitator; import com.tumblr.backboard.imitator.MotionImitator; import com.tumblr.backboard.imitator.ToggleImitator; import com.tumblr.backboard.performer.MapPerformer; /** * A ring of views that bloom and then contract, with a selector that follows the finger. * <p/> * Created by ericleong on 5/7/14. */ public class FlowerFragment extends Fragment { private static final int DIAMETER = 50; private static final int RING_DIAMETER = 7 * DIAMETER; private RelativeLayout mRootView; private View mCircle; private View[] mCircles; private static final int OPEN = 1; private static final int CLOSED = 0; private static double distSq(double x1, double y1, double x2, double y2) { return Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2); } private static View nearest(float x, float y, View[] views) { double minDistSq = Double.MAX_VALUE; View minView = null; for (View view : views) { double distSq = distSq(x, y, view.getX() + view.getMeasuredWidth() / 2, view.getY() + view.getMeasuredHeight() / 2); if (distSq < Math.pow(1.5f * view.getMeasuredWidth(), 2) && distSq < minDistSq) { minDistSq = distSq; minView = view; } } return minView; } /** * Snaps to the nearest circle. */ private class SnapImitator extends MotionImitator { public SnapImitator(MotionProperty property) { super(property, 0, Imitator.TRACK_ABSOLUTE, Imitator.FOLLOW_SPRING); } @Override public void mime(float offset, float value, float delta, float dt, MotionEvent event) { // find the nearest view final View nearest = nearest( event.getX() + mCircle.getX(), event.getY() + mCircle.getY(), mCircles); if (nearest != null) { // snap to it - remember to compensate for translation switch (mProperty) { case X: getSpring().setEndValue(nearest.getX() + nearest.getWidth() / 2 - mCircle.getLeft() - mCircle.getWidth() / 2); break; case Y: getSpring().setEndValue(nearest.getY() + nearest.getHeight() / 2 - mCircle.getTop() - mCircle.getHeight() / 2); break; } } else { // follow finger super.mime(offset, value, delta, dt, event); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (RelativeLayout) inflater.inflate(R.layout.fragment_flower, container, false); mCircles = new View[6]; mCircle = mRootView.findViewById(R.id.circle); final float diameter = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DIAMETER, getResources().getDisplayMetrics()); final TypedArray circles = getResources().obtainTypedArray(R.array.circles); // layout params final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) diameter, (int) diameter); params.addRule(RelativeLayout.CENTER_IN_PARENT); // create the circle views int colorIndex = 0; for (int i = 0; i < mCircles.length; i++) { mCircles[i] = new View(getActivity()); mCircles[i].setLayoutParams(params); mCircles[i].setBackgroundDrawable(getResources().getDrawable( circles.getResourceId(colorIndex, -1))); colorIndex++; if (colorIndex >= circles.length()) { colorIndex = 0; } mRootView.addView(mCircles[i], 0); } circles.recycle(); /* Animations! */ final SpringSystem springSystem = SpringSystem.create(); // create spring final Spring spring = springSystem.createSpring(); // add listeners along arc final double arc = 2 * Math.PI / mCircles.length; for (int i = 0; i < mCircles.length; i++) { View view = mCircles[i]; // map spring to a line segment from the center to the edge of the ring spring.addListener(new MapPerformer(view, View.TRANSLATION_X, 0, 1, 0, (float) (RING_DIAMETER * Math.cos(i * arc)))); spring.addListener(new MapPerformer(view, View.TRANSLATION_Y, 0, 1, 0, (float) (RING_DIAMETER * Math.sin(i * arc)))); spring.setEndValue(CLOSED); } final ToggleImitator imitator = new ToggleImitator(spring, CLOSED, OPEN); // move circle using finger, snap when near another circle, and bloom when touched new Actor.Builder(SpringSystem.create(), mCircle) .addMotion(new SnapImitator(MotionProperty.X), View.TRANSLATION_X) .addMotion(new SnapImitator(MotionProperty.Y), View.TRANSLATION_Y) .onTouchListener(imitator) .build(); return mRootView; } }
29.242604
92
0.706799
4bb75211591b71f3c6427ad62761ac8a1763a5a1
2,313
package ab.model; import java.io.Serializable; import java.util.Objects; /** * 猜测,记录曾经猜测了什么数字,结果是什么 */ public class Guess implements Serializable { /** * 猜测的数字 */ private ABNumber guess; /** * 该猜测的结果,xAyB形式 */ private Answer answer; public Guess(ABNumber guess, Answer answer) { this.guess = guess; this.answer = answer; } public Guess(ABNumber guess, int a, int b) { this.guess = guess; this.answer = new Answer(a, b); } public ABNumber getGuess() { return guess; } public void setGuess(ABNumber guess) { this.guess = guess; } public Answer getAnswer() { return answer; } public void setAnswer(Answer answer) { this.answer = answer; } public class Answer implements Serializable { // xAyB中的x private int a; // xAyB中的y private int b; public Answer(int a, int b) { this.a = a; this.b = b; } public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } @Override public String toString() { return a + "A" + b + "B"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Answer answer = (Answer) o; return a == answer.a && b == answer.b; } @Override public int hashCode() { return Objects.hash(a, b); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Guess guess1 = (Guess) o; return Objects.equals(guess, guess1.guess) && Objects.equals(answer, guess1.answer); } @Override public int hashCode() { return Objects.hash(guess, answer); } @Override public String toString() { return "\nguess=" + guess + ", answer=" + answer; } }
20.651786
70
0.495028
84c7372f1ad1b1d49475b0fc44b6a312c4add926
2,695
// Generated by protoc-gen-javastream. DO NOT MODIFY. // source: frameworks/base/core/proto/android/net/networkcapabilities.proto package android.net; /** @hide */ // message NetworkCapabilitiesProto public final class NetworkCapabilitiesProto { // enum Transport public static final int TRANSPORT_CELLULAR = 0; public static final int TRANSPORT_WIFI = 1; public static final int TRANSPORT_BLUETOOTH = 2; public static final int TRANSPORT_ETHERNET = 3; public static final int TRANSPORT_VPN = 4; public static final int TRANSPORT_WIFI_AWARE = 5; public static final int TRANSPORT_LOWPAN = 6; // enum NetCapability public static final int NET_CAPABILITY_MMS = 0; public static final int NET_CAPABILITY_SUPL = 1; public static final int NET_CAPABILITY_DUN = 2; public static final int NET_CAPABILITY_FOTA = 3; public static final int NET_CAPABILITY_IMS = 4; public static final int NET_CAPABILITY_CBS = 5; public static final int NET_CAPABILITY_WIFI_P2P = 6; public static final int NET_CAPABILITY_IA = 7; public static final int NET_CAPABILITY_RCS = 8; public static final int NET_CAPABILITY_XCAP = 9; public static final int NET_CAPABILITY_EIMS = 10; public static final int NET_CAPABILITY_NOT_METERED = 11; public static final int NET_CAPABILITY_INTERNET = 12; public static final int NET_CAPABILITY_NOT_RESTRICTED = 13; public static final int NET_CAPABILITY_TRUSTED = 14; public static final int NET_CAPABILITY_NOT_VPN = 15; public static final int NET_CAPABILITY_VALIDATED = 16; public static final int NET_CAPABILITY_CAPTIVE_PORTAL = 17; public static final int NET_CAPABILITY_NOT_ROAMING = 18; public static final int NET_CAPABILITY_FOREGROUND = 19; // repeated .android.net.NetworkCapabilitiesProto.Transport transports = 1; public static final long TRANSPORTS = 0x0000020e00000001L; // repeated .android.net.NetworkCapabilitiesProto.NetCapability capabilities = 2; public static final long CAPABILITIES = 0x0000020e00000002L; // optional int32 link_up_bandwidth_kbps = 3; public static final long LINK_UP_BANDWIDTH_KBPS = 0x0000010500000003L; // optional int32 link_down_bandwidth_kbps = 4; public static final long LINK_DOWN_BANDWIDTH_KBPS = 0x0000010500000004L; // optional string network_specifier = 5; public static final long NETWORK_SPECIFIER = 0x0000010900000005L; // optional bool can_report_signal_strength = 6; public static final long CAN_REPORT_SIGNAL_STRENGTH = 0x0000010800000006L; // optional sint32 signal_strength = 7; public static final long SIGNAL_STRENGTH = 0x0000011100000007L; }
42.109375
85
0.765863
6fb0043bca5a5659ece811f48664af594b640195
4,834
package com.simplecontrol.src; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Switch; import android.widget.TextView; /** * Created by Mrinmoy Mondal on 8/16/2017. * The thermostatRoom is the houses main AC/HEAT system. * This class holds the thermostatRoom layout and the main should interact with it * to access the top view. It set the buttons pressed to the ActionListener class. * There should only be one top view it. There area setters in plcae to change the temperature */ public class ThermostatRoom extends RoomData{ //creates the a instance of the layout private View thermostatView; //activity from main private Activity _activity; //variables to control the thermostatRoom private TextView _temperature; private TextView _setTemperature; Switch _fanSwitch; Button _acHeatOFF; Button _addTemp; Button _subTemp; ImageButton _addRoom; /// state of the current settings private int acStatus; ThermostatDevice thermostatDevice; //initializes everything from main activity and all the widgets ThermostatRoom(String roomName, AppLayout appLayout ) { super(roomName,appLayout); } @Override View createView() { thermostatView = LayoutInflater.from(getContext()).inflate(R.layout.top_layout, null); thermostatView.setTag(getRoomName()); ImageView image = (ImageView)getView().findViewById(R.id.bg); Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap(); Bitmap newbitmap = ImageHelper.getRoundedCornerBitmap(bitmap,30); image.setImageBitmap(newbitmap); return thermostatView; } @Override void addDevice(DeviceData deviceData) { this.thermostatDevice = (ThermostatDevice) deviceData; thermostatDevice.createDataBaseString(); } @Override DeviceData getDevice(String deviceName){ return this.thermostatDevice; } @Override View getView() { return this.thermostatView; } @Override void updateDevice(String deviceName, DeviceData newDeviceData) { thermostatDevice = (ThermostatDevice) newDeviceData; } } /* Context context =appLayout.context; View.OnClickListener onClickListener= appLayout.onClickListener; View.OnLongClickListener onLongClickListener = appLayout.onLongClickListener; appLayout.thermostatRoom = this; thermostatView = LayoutInflater.from(context).inflate(R.layout.top_layout,null); _acHeatOFF = (Button)thermostatView.findViewById(R.id.toggleHeatAC); _addTemp = (Button)thermostatView.findViewById(R.id.temp_increment); _subTemp = (Button)thermostatView.findViewById(R.id.temp_decrement); _addRoom = (ImageButton)thermostatView.findViewById(R.id.addRoom); _fanSwitch = (Switch)thermostatView.findViewById(R.id.fan); _setTemperature = (TextView)thermostatView.findViewById(R.id.temp); _temperature = (TextView)thermostatView.findViewById(R.id.current_temperature); //sets the buttons to on listeners _acHeatOFF.setOnClickListener(onClickListener); _addTemp.setOnClickListener(onClickListener); _subTemp.setOnClickListener(onClickListener); _addRoom.setOnClickListener(onClickListener); _fanSwitch.setOnClickListener(onClickListener); _addTemp.setOnLongClickListener(onLongClickListener); _subTemp.setOnLongClickListener(onLongClickListener); } //creates the setters and getters for textfield void setTemperature (int temp){ _setTemperature.setText(temp+""); } protected void setCurrentTemperature(int temp){ _temperature.setText(temp+""); } public int getTemperature() { return Integer.parseInt(_temperature.getText().toString()); } int getSetTemperature() { return Integer.parseInt(_setTemperature.getText().toString()); } void setAcHeatOffText (String x){ if(x.length()>4){ Log.e("setString", "acHeatToggle Excceds max char"); x="NA"; } _acHeatOFF.setText(x); } int getAcStatus(){ return acStatus; } void setAcStatus(int acStatus) { if(acStatus>2 || acStatus<0) { if( MainActivity.DEBUG) Log.e("DEBUG", "ac status error"); return; } this.acStatus = acStatus; } //returns the view object protected View getView(){ return thermostatView; } } */
27.005587
94
0.689905
59c816f172a0cfa0b2bfb2b8d93dced070f66982
5,230
package net.minestom.server.instance.block.states; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockAlternative; /** * Completely internal. DO NOT USE. IF YOU ARE A USER AND FACE A PROBLEM WHILE USING THIS CODE, THAT'S ON YOU. */ @Deprecated( since = "forever", forRemoval = false ) public final class Vine { /** * Completely internal. DO NOT USE. IF YOU ARE A USER AND FACE A PROBLEM WHILE USING THIS CODE, THAT'S ON YOU. */ @Deprecated( since = "forever", forRemoval = false ) public static void initStates() { Block.VINE.addBlockAlternative(new BlockAlternative((short) 4861, "east=true", "north=true", "south=true", "up=true", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4862, "east=true", "north=true", "south=true", "up=true", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4863, "east=true", "north=true", "south=true", "up=false", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4864, "east=true", "north=true", "south=true", "up=false", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4865, "east=true", "north=true", "south=false", "up=true", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4866, "east=true", "north=true", "south=false", "up=true", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4867, "east=true", "north=true", "south=false", "up=false", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4868, "east=true", "north=true", "south=false", "up=false", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4869, "east=true", "north=false", "south=true", "up=true", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4870, "east=true", "north=false", "south=true", "up=true", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4871, "east=true", "north=false", "south=true", "up=false", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4872, "east=true", "north=false", "south=true", "up=false", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4873, "east=true", "north=false", "south=false", "up=true", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4874, "east=true", "north=false", "south=false", "up=true", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4875, "east=true", "north=false", "south=false", "up=false", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4876, "east=true", "north=false", "south=false", "up=false", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4877, "east=false", "north=true", "south=true", "up=true", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4878, "east=false", "north=true", "south=true", "up=true", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4879, "east=false", "north=true", "south=true", "up=false", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4880, "east=false", "north=true", "south=true", "up=false", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4881, "east=false", "north=true", "south=false", "up=true", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4882, "east=false", "north=true", "south=false", "up=true", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4883, "east=false", "north=true", "south=false", "up=false", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4884, "east=false", "north=true", "south=false", "up=false", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4885, "east=false", "north=false", "south=true", "up=true", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4886, "east=false", "north=false", "south=true", "up=true", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4887, "east=false", "north=false", "south=true", "up=false", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4888, "east=false", "north=false", "south=true", "up=false", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4889, "east=false", "north=false", "south=false", "up=true", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4890, "east=false", "north=false", "south=false", "up=true", "west=false")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4891, "east=false", "north=false", "south=false", "up=false", "west=true")); Block.VINE.addBlockAlternative(new BlockAlternative((short) 4892, "east=false", "north=false", "south=false", "up=false", "west=false")); } }
93.392857
145
0.682983
7f8fc751cb0a053f37d6a6b9a662c22d6f172918
14,401
/* * 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.trino.plugin.hive; import com.google.common.base.VerifyException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import io.trino.plugin.hive.authentication.HiveIdentity; import io.trino.plugin.hive.metastore.SemiTransactionalHiveMetastore; import io.trino.plugin.hive.util.HiveBucketing.HiveBucketFilter; import io.trino.plugin.hive.util.Optionals; import io.trino.spi.TrinoException; import io.trino.spi.connector.ColumnHandle; import io.trino.spi.connector.ConnectorTableHandle; import io.trino.spi.connector.Constraint; import io.trino.spi.connector.SchemaTableName; import io.trino.spi.connector.TableNotFoundException; import io.trino.spi.predicate.Domain; import io.trino.spi.predicate.NullableValue; import io.trino.spi.predicate.TupleDomain; import io.trino.spi.type.Type; import org.apache.hadoop.hive.common.FileUtils; import javax.inject.Inject; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; import static io.trino.plugin.hive.HiveErrorCode.HIVE_EXCEEDED_PARTITION_LIMIT; import static io.trino.plugin.hive.metastore.MetastoreUtil.computePartitionKeyFilter; import static io.trino.plugin.hive.metastore.MetastoreUtil.toPartitionName; import static io.trino.plugin.hive.util.HiveBucketing.getHiveBucketFilter; import static io.trino.plugin.hive.util.HiveUtil.parsePartitionValue; import static io.trino.spi.predicate.TupleDomain.none; import static java.lang.String.format; import static java.util.stream.Collectors.toList; public class HivePartitionManager { private final int maxPartitions; private final int domainCompactionThreshold; @Inject public HivePartitionManager(HiveConfig hiveConfig) { this( hiveConfig.getMaxPartitionsPerScan(), hiveConfig.getDomainCompactionThreshold()); } public HivePartitionManager( int maxPartitions, int domainCompactionThreshold) { checkArgument(maxPartitions >= 1, "maxPartitions must be at least 1"); this.maxPartitions = maxPartitions; checkArgument(domainCompactionThreshold >= 1, "domainCompactionThreshold must be at least 1"); this.domainCompactionThreshold = domainCompactionThreshold; } public HivePartitionResult getPartitions(SemiTransactionalHiveMetastore metastore, HiveIdentity identity, ConnectorTableHandle tableHandle, Constraint constraint) { HiveTableHandle hiveTableHandle = (HiveTableHandle) tableHandle; TupleDomain<ColumnHandle> effectivePredicate = constraint.getSummary() .intersect(hiveTableHandle.getEnforcedConstraint()); SchemaTableName tableName = hiveTableHandle.getSchemaTableName(); Optional<HiveBucketHandle> hiveBucketHandle = hiveTableHandle.getBucketHandle(); List<HiveColumnHandle> partitionColumns = hiveTableHandle.getPartitionColumns(); if (effectivePredicate.isNone()) { return new HivePartitionResult(partitionColumns, ImmutableList.of(), none(), none(), none(), hiveBucketHandle, Optional.empty()); } Optional<HiveBucketFilter> bucketFilter = getHiveBucketFilter(hiveTableHandle, effectivePredicate); TupleDomain<HiveColumnHandle> compactEffectivePredicate = effectivePredicate .transformKeys(HiveColumnHandle.class::cast) .simplify(domainCompactionThreshold); if (partitionColumns.isEmpty()) { return new HivePartitionResult( partitionColumns, ImmutableList.of(new HivePartition(tableName)), compactEffectivePredicate, effectivePredicate, TupleDomain.all(), hiveBucketHandle, bucketFilter); } List<Type> partitionTypes = partitionColumns.stream() .map(HiveColumnHandle::getType) .collect(toList()); Iterable<HivePartition> partitionsIterable; Predicate<Map<ColumnHandle, NullableValue>> predicate = constraint.predicate().orElse(value -> true); if (hiveTableHandle.getPartitions().isPresent()) { partitionsIterable = hiveTableHandle.getPartitions().get().stream() .filter(partition -> partitionMatches(partitionColumns, effectivePredicate, predicate, partition)) .collect(toImmutableList()); } else { List<String> partitionNames = getFilteredPartitionNames(metastore, identity, tableName, partitionColumns, compactEffectivePredicate); partitionsIterable = () -> partitionNames.stream() // Apply extra filters which could not be done by getFilteredPartitionNames .map(partitionName -> parseValuesAndFilterPartition(tableName, partitionName, partitionColumns, partitionTypes, effectivePredicate, predicate)) .filter(Optional::isPresent) .map(Optional::get) .iterator(); } // All partition key domains will be fully evaluated, so we don't need to include those TupleDomain<ColumnHandle> remainingTupleDomain = effectivePredicate.filter((column, domain) -> !partitionColumns.contains(column)); TupleDomain<ColumnHandle> enforcedTupleDomain = effectivePredicate.filter((column, domain) -> partitionColumns.contains(column)); return new HivePartitionResult(partitionColumns, partitionsIterable, compactEffectivePredicate, remainingTupleDomain, enforcedTupleDomain, hiveBucketHandle, bucketFilter); } public HivePartitionResult getPartitions(ConnectorTableHandle tableHandle, List<List<String>> partitionValuesList) { HiveTableHandle hiveTableHandle = (HiveTableHandle) tableHandle; SchemaTableName tableName = hiveTableHandle.getSchemaTableName(); List<HiveColumnHandle> partitionColumns = hiveTableHandle.getPartitionColumns(); Optional<HiveBucketHandle> bucketHandle = hiveTableHandle.getBucketHandle(); List<String> partitionColumnNames = partitionColumns.stream() .map(HiveColumnHandle::getName) .collect(toImmutableList()); List<Type> partitionColumnTypes = partitionColumns.stream() .map(HiveColumnHandle::getType) .collect(toImmutableList()); List<HivePartition> partitionList = partitionValuesList.stream() .map(partitionValues -> toPartitionName(partitionColumnNames, partitionValues)) .map(partitionName -> parseValuesAndFilterPartition(tableName, partitionName, partitionColumns, partitionColumnTypes, TupleDomain.all(), value -> true)) .map(partition -> partition.orElseThrow(() -> new VerifyException("partition must exist"))) .collect(toImmutableList()); return new HivePartitionResult(partitionColumns, partitionList, TupleDomain.all(), TupleDomain.all(), TupleDomain.all(), bucketHandle, Optional.empty()); } public List<HivePartition> getPartitionsAsList(HivePartitionResult partitionResult) { ImmutableList.Builder<HivePartition> partitionList = ImmutableList.builder(); int count = 0; Iterator<HivePartition> iterator = partitionResult.getPartitions(); while (iterator.hasNext()) { HivePartition partition = iterator.next(); if (count == maxPartitions) { throw new TrinoException(HIVE_EXCEEDED_PARTITION_LIMIT, format( "Query over table '%s' can potentially read more than %s partitions", partition.getTableName(), maxPartitions)); } partitionList.add(partition); count++; } return partitionList.build(); } public HiveTableHandle applyPartitionResult(HiveTableHandle handle, HivePartitionResult partitions, Optional<Set<ColumnHandle>> columns) { return new HiveTableHandle( handle.getSchemaName(), handle.getTableName(), handle.getTableParameters(), ImmutableList.copyOf(partitions.getPartitionColumns()), handle.getDataColumns(), Optional.of(getPartitionsAsList(partitions)), partitions.getCompactEffectivePredicate(), partitions.getEnforcedConstraint(), partitions.getBucketHandle(), partitions.getBucketFilter(), handle.getAnalyzePartitionValues(), handle.getAnalyzeColumnNames(), Optionals.combine(handle.getConstraintColumns(), columns, Sets::union), handle.getProjectedColumns(), handle.getTransaction()); } public List<HivePartition> getOrLoadPartitions(SemiTransactionalHiveMetastore metastore, HiveIdentity identity, HiveTableHandle table) { return table.getPartitions().orElseGet(() -> getPartitionsAsList(getPartitions(metastore, identity, table, new Constraint(table.getEnforcedConstraint())))); } private Optional<HivePartition> parseValuesAndFilterPartition( SchemaTableName tableName, String partitionId, List<HiveColumnHandle> partitionColumns, List<Type> partitionColumnTypes, TupleDomain<ColumnHandle> constraintSummary, Predicate<Map<ColumnHandle, NullableValue>> constraint) { HivePartition partition = parsePartition(tableName, partitionId, partitionColumns, partitionColumnTypes); if (partitionMatches(partitionColumns, constraintSummary, constraint, partition)) { return Optional.of(partition); } return Optional.empty(); } private boolean partitionMatches(List<HiveColumnHandle> partitionColumns, TupleDomain<ColumnHandle> constraintSummary, Predicate<Map<ColumnHandle, NullableValue>> constraint, HivePartition partition) { return partitionMatches(partitionColumns, constraintSummary, partition) && constraint.test(partition.getKeys()); } public static boolean partitionMatches(List<HiveColumnHandle> partitionColumns, TupleDomain<ColumnHandle> constraintSummary, HivePartition partition) { if (constraintSummary.isNone()) { return false; } Map<ColumnHandle, Domain> domains = constraintSummary.getDomains().get(); for (HiveColumnHandle column : partitionColumns) { NullableValue value = partition.getKeys().get(column); Domain allowedDomain = domains.get(column); if (allowedDomain != null && !allowedDomain.includesNullableValue(value.getValue())) { return false; } } return true; } private List<String> getFilteredPartitionNames(SemiTransactionalHiveMetastore metastore, HiveIdentity identity, SchemaTableName tableName, List<HiveColumnHandle> partitionKeys, TupleDomain<HiveColumnHandle> effectivePredicate) { List<String> columnNames = partitionKeys.stream() .map(HiveColumnHandle::getName) .collect(toImmutableList()); TupleDomain<String> partitionKeysFilter = computePartitionKeyFilter(partitionKeys, effectivePredicate); // fetch the partition names return metastore.getPartitionNamesByFilter(identity, tableName.getSchemaName(), tableName.getTableName(), columnNames, partitionKeysFilter) .orElseThrow(() -> new TableNotFoundException(tableName)); } public static HivePartition parsePartition( SchemaTableName tableName, String partitionName, List<HiveColumnHandle> partitionColumns, List<Type> partitionColumnTypes) { List<String> partitionValues = extractPartitionValues(partitionName); ImmutableMap.Builder<ColumnHandle, NullableValue> builder = ImmutableMap.builder(); for (int i = 0; i < partitionColumns.size(); i++) { HiveColumnHandle column = partitionColumns.get(i); NullableValue parsedValue = parsePartitionValue(partitionName, partitionValues.get(i), partitionColumnTypes.get(i)); builder.put(column, parsedValue); } Map<ColumnHandle, NullableValue> values = builder.build(); return new HivePartition(tableName, partitionName, values); } public static List<String> extractPartitionValues(String partitionName) { ImmutableList.Builder<String> values = ImmutableList.builder(); boolean inKey = true; int valueStart = -1; for (int i = 0; i < partitionName.length(); i++) { char current = partitionName.charAt(i); if (inKey) { checkArgument(current != '/', "Invalid partition spec: %s", partitionName); if (current == '=') { inKey = false; valueStart = i + 1; } } else if (current == '/') { checkArgument(valueStart != -1, "Invalid partition spec: %s", partitionName); values.add(FileUtils.unescapePathName(partitionName.substring(valueStart, i))); inKey = true; valueStart = -1; } } checkArgument(!inKey, "Invalid partition spec: %s", partitionName); values.add(FileUtils.unescapePathName(partitionName.substring(valueStart))); return values.build(); } }
48.325503
230
0.690438
3affb5e3eabb342ff6a85bd9e7342af0c2ed2f9a
178
package mcc.academy.checkstyle.test; public class App { public void getTest() { } public static void main(String[] args) { System.out.println("Hello World!"); } }
14.833333
42
0.662921
0cfb39885de55a39b35122896bc60e8059f91bde
322
package com.crm.application.repository; import com.crm.application.model.Address; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface AddressRepository extends JpaRepository<Address, Long> { <T> Address findById(Long id); }
23
73
0.813665
1a3f8095f1720f7b40cfa67eefbfd85381f46418
1,297
package com.ushaqi.zhuishushenqi.widget; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import butterknife.ButterKnife.Finder; public class ShareWarningView$$ViewInjector { public static void inject(ButterKnife.Finder paramFinder, ShareWarningView paramShareWarningView, Object paramObject) { paramShareWarningView.mClose = ((ImageView)paramFinder.findRequiredView(paramObject, 2131493987, "field 'mClose'")); paramShareWarningView.mNegative = ((Button)paramFinder.findRequiredView(paramObject, 2131493988, "field 'mNegative'")); paramShareWarningView.mPositive = ((Button)paramFinder.findRequiredView(paramObject, 2131493989, "field 'mPositive'")); paramShareWarningView.mContent = ((TextView)paramFinder.findRequiredView(paramObject, 2131492905, "field 'mContent'")); } public static void reset(ShareWarningView paramShareWarningView) { paramShareWarningView.mClose = null; paramShareWarningView.mNegative = null; paramShareWarningView.mPositive = null; paramShareWarningView.mContent = null; } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.ushaqi.zhuishushenqi.widget.ShareWarningView..ViewInjector * JD-Core Version: 0.6.0 */
43.233333
123
0.781804
6f8a8e921d56604655e6d71962ad26a8e89ad755
5,944
package gg.projecteden.nexus.features.quests.interactable.instructions; import gg.projecteden.nexus.features.quests.QuestItem; import gg.projecteden.nexus.features.quests.QuestReward; import gg.projecteden.nexus.features.quests.interactable.Interactable; import gg.projecteden.nexus.features.resourcepack.models.CustomModel; import gg.projecteden.nexus.models.nickname.Nickname; import gg.projecteden.nexus.models.quests.Quester; import gg.projecteden.nexus.utils.AdventureUtils; import gg.projecteden.nexus.utils.PlayerUtils; import gg.projecteden.nexus.utils.RandomUtils; import lombok.AllArgsConstructor; import lombok.Data; import lombok.RequiredArgsConstructor; import net.kyori.adventure.text.ComponentLike; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.function.BiFunction; import java.util.function.Consumer; import static gg.projecteden.nexus.utils.PlayerUtils.playerHas; @Data @RequiredArgsConstructor public class Dialog { private final Interactable interactable; private final List<Instruction> instructions = new ArrayList<>(); private static final Map<UUID, DialogInstance> instances = new HashMap<>(); public static Dialog from(Interactable interactable) { return new Dialog(interactable); } private Dialog instruction(Consumer<Quester> task, long delay) { instructions.add(new Instruction(task, delay)); return this; } @Data @AllArgsConstructor public static class Instruction { private final Consumer<Quester> task; private final long delay; } public Dialog npc(String message) { return npc(interactable, message); } public Dialog npc(Interactable npc, String message) { return npc(npc == null ? "NPC" : npc.getName(), message); } public Dialog npc(String npcName, String message) { return instruction(quester -> PlayerUtils.send(quester, "&3" + npcName + " &7> &f" + interpolate(message, quester)), calculateDelay(message)); } public Dialog player(String message) { return instruction(quester -> PlayerUtils.send(quester, "&b&lYOU &7> &f" + interpolate(message, quester)), calculateDelay(message)); } public Dialog raw(String message) { return instruction(quester -> PlayerUtils.send(quester, message), calculateDelay(message)); } public Dialog raw(ComponentLike message) { return instruction(quester -> PlayerUtils.send(quester, message), calculateDelay(AdventureUtils.asPlainText(message))); } public Dialog pause(long ticks) { return instruction(null, ticks); } public Dialog thenRun(Consumer<Quester> task) { return instruction(task, 0); } public Dialog reward(QuestReward reward) { return instruction(reward::apply, -1); } public Dialog reward(QuestReward reward, int amount) { return instruction(quester -> reward.apply(quester, amount), -1); } public Dialog give(Material material) { return give(new ItemStack(material)); } public Dialog give(Material material, int amount) { return give(new ItemStack(material, amount)); } public Dialog give(ItemStack item) { return instruction(quester -> PlayerUtils.giveItem(quester, item), -1); } public Dialog give(CustomModel... items) { for (CustomModel item : items) give(item.getItem()); return this; } public Dialog give(QuestItem... items) { for (QuestItem item : items) give(item.get()); return this; } public Dialog giveIfMissing(Material material) { return giveIfMissing(new ItemStack(material)); } public Dialog giveIfMissing(QuestItem item) { return giveIfMissing(item.get()); } public Dialog giveIfMissing(ItemStack item) { return instruction(quester -> { if (!playerHas(quester, item)) PlayerUtils.giveItem(quester, item); }, -1); } public Dialog take(Material material) { return give(new ItemStack(material)); } public Dialog take(Material material, int amount) { return give(new ItemStack(material, amount)); } public Dialog take(ItemStack item) { return instruction(quester -> PlayerUtils.removeItem(quester.getOnlinePlayer(), item), -1); } public DialogInstance send(Quester quester) { return new DialogInstance(quester, this); } @AllArgsConstructor public enum Variable { PLAYER_NAME((quester, interactable) -> Nickname.of(quester)), NPC_NAME((quester, interactable) -> interactable.getName()), ; private BiFunction<Quester, Interactable, String> interpolator; public String interpolate(String message, Quester quester, Interactable interactable) { return message.replaceAll(placeholder(), interpolator.apply(quester, interactable)); } public String placeholder() { return "\\{\\{" + name() + "}}"; } @Override public String toString() { return "{{" + name() + "}}"; } } @NotNull private String interpolate(String message, Quester quester) { for (Variable variable : Variable.values()) message = variable.interpolate(message, quester, interactable); return message; } private int calculateDelay(String message) { // TODO return 200; } private static final List<String> genericGreetings = List.of("Hello!", "Hi!", "Greetings", "Hey there", "Hey!", "Hi there!", "G'day", "Good to see you", "Nice to see you"); public static DialogInstance genericGreeting(Quester quester, Interactable interactable) { List<String> genericGreetings = new ArrayList<>(Dialog.genericGreetings); if (quester.getLocation() != null) { final long time = quester.getLocation().getWorld().getTime(); if (time < 6000 || time > 18000) genericGreetings.add("Good morning"); else if (time <= 12000) genericGreetings.add("Good afternoon"); else genericGreetings.add("Good evening"); } final String message = RandomUtils.randomElement(genericGreetings); return new DialogInstance(quester, new Dialog(interactable).npc(message)); } }
28.854369
144
0.743271
64d4553792f3aa71ccdcf04565e535c2ad23bfe7
1,929
package com.utils.releaseshelper.logic.action; import java.util.Collections; import java.util.List; import java.util.Map; import com.utils.releaseshelper.model.logic.action.Action; import com.utils.releaseshelper.model.logic.action.ChainAction; import com.utils.releaseshelper.view.CommandLineInterface; /** * Logic to execute a chain of actions, with a single confirmation request * All sub-actions are executed in "sync" (first all beforeAction, then all doRunAction, etc.) */ public class ChainActionLogic extends ActionLogic<ChainAction> { private final List<ActionLogic<?>> subActionsLogic; protected ChainActionLogic(ChainAction action, Map<String, String> variables, CommandLineInterface cli, List<ActionLogic<?>> subActionsLogic) { super(action, variables, cli); this.subActionsLogic = Collections.unmodifiableList(subActionsLogic); } @Override protected void beforeAction() { for(ActionLogic<?> subActionLogic: subActionsLogic) { subActionLogic.beforeAction(); } } @Override protected void printDefaultActionDescription() { for(ActionLogic<?> subActionLogic: subActionsLogic) { subActionLogic.printActionDescription(); } } @Override protected String getConfirmationPrompt() { return "Start actions chain"; } @Override protected void doRunAction() { for(int i = 0; i < subActionsLogic.size(); i++) { Action subAction = action.getActions().get(i); ActionLogic<?> subActionLogic = subActionsLogic.get(i); String actionDescription = "sub-action \"" + subAction.getName() + "\" (" + subAction.getTypeDescription() + ")"; cli.startIdentationGroup("Start %s", actionDescription); subActionLogic.doRunAction(); cli.endIdentationGroup("End %s", actionDescription); } } @Override protected void afterAction() { for(ActionLogic<?> subActionLogic: subActionsLogic) { subActionLogic.afterAction(); } } }
25.381579
144
0.733022
0c2d4142129c9c980211c6e52b7ed7ccc98f5112
1,956
/** * Copyright © 2019 金聖聰. All rights reserved. * * 功能描述:汽车租凭子类包 * @Package: kh75.day190801.afterschool_exercises.car_rental.son * @author: 金聖聰 * @date: 2019年8月5日 下午5:12:32 */ package kh75.day190801.afterschool_exercises.car_rental.son; import kh75.day190801.afterschool_exercises.car_rental.father.MotoVehicle; /** * Copyright: Copyright (c) 2019 金聖聰 * * @ClassName: Truck.java * @Description: 汽车租凭子类truck * * @version: v1.0.0 * @author: 金聖聰 * @date: 2019年8月5日 下午5:12:32 * * Modification History: * Date Author Version Description *---------------------------------------------------------* * 2019年8月5日 金聖聰 v1.0.0 修改原因 */ public class Truck extends MotoVehicle{ private int tonnage; /** * @Function: Truck.java * @Description: 有参构造 * * @param: 吨位 * @version: v1.0.0 * @author: 金聖聰 * @date: 2019年8月5日 下午5:14:33 */ public Truck(String no,int tonnage) { super.setNo(no); this.tonnage = tonnage; } /** * @Function: Truck.java * @Description: 无参构造 * * @param: 参数描述 * @version: v1.0.0 * @author: 金聖聰 * @date: 2019年8月5日 下午5:14:56 */ public Truck() { } /** * @return the tonnage */ public int getTonnage() { return tonnage; } /** * @param tonnage the tonnage to set */ public void setTonnage(int tonnage) { this.tonnage = tonnage; } /** * @see kh75.day190801.afterschool_exercises.car_rental.father.MotoVehicle#calcRent(int) * @Function: Truck.java * @Description: 计算租金 * * @param: days 租的天数 * @return:租金 * @throws:null * * @version: v1.0.0 * @author: 金聖聰 * @date: 2019年8月5日 下午5:15:41 * * Modification History: * Date Author Version Description *---------------------------------------------------------* * 2019年8月5日 金聖聰 v1.0.0 修改原因 */ @Override public int calcRent(int days) { int sum = 0; sum = days*this.tonnage*50; return sum; } }
20.164948
90
0.5818
cdded65e24e6cf3e1cf2860707e71efac7c29ef2
2,766
package com.fishercoder.solutions; import java.util.Arrays; /** * 473. Matchsticks to Square * * Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, * please find out a way you can make one square by using up all those matchsticks. * You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. * Your input will be several matchsticks the girl has, represented with their stick length. * Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has. Example 1: Input: [1,1,2,2,2] Output: true Explanation: You can form a square with length 2, one side of the square came two sticks with length 1. Example 2: Input: [3,3,3,3,4] Output: false Explanation: You cannot find a way to form a square with all the matchsticks. Note: The length sum of the given matchsticks is in the range of 0 to 10^9. The length of the given matchstick array will not exceed 15. */ public class _473 { public static class Solution1 { /** * Partially inspired by: https://discuss.leetcode.com/topic/72107/java-dfs-solution-with-explanation/2 * One hidden requirement: you'll have to use up all of the given matchsticks, nothing could be left behind. */ public boolean makesquare(int[] nums) { if (nums == null || nums.length < 4) { return false; } Arrays.sort(nums); reverse(nums); int sum = 0; for (int i : nums) { sum += i; } if (sum % 4 != 0) { return false; } return dfs(nums, new int[4], 0, sum / 4); } private boolean dfs(int[] nums, int[] sums, int index, int target) { if (index == nums.length) { if (sums[0] == target && sums[1] == target && sums[2] == target) { return true; } return false; } for (int i = 0; i < 4; i++) { if (sums[i] + nums[index] > target) { continue; } sums[i] += nums[index]; if (dfs(nums, sums, index + 1, target)) { return true; } sums[i] -= nums[index]; } return false; } private void reverse(int[] nums) { int left = 0; int right = nums.length - 1; while (left < right) { int tmp = nums[left]; nums[left] = nums[right]; nums[right] = tmp; left++; right--; } } } }
32.162791
144
0.548807
d4a0c55f4d28c485637019dac4977e853e227ee7
630
package com.queencastle.service.test.shop; import org.junit.Ignore; import org.junit.Test; import com.queencastle.dao.model.shop.ShopBrand; import com.queencastle.dao.mybatis.IdTypeHandler; import com.queencastle.service.test.BaseTest; public class ShopBrandTester extends BaseTest { @Test @Ignore public void testInsert() { ShopBrand brand = new ShopBrand(); brand.setCname("阿迪达斯"); brand.setImg("aaaaaaaa"); shopBrandService.insert(brand); } @Test public void testGetById(){ String id = IdTypeHandler.encode(5); ShopBrand brand = shopBrandService.getById(id); System.out.println(brand.getCname()); } }
22.5
49
0.75873
56ef92a2b7dc3840c6cc21f098287a679a49d1a3
19,328
/* * Copyright 2016. Ivan Stuart * * 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. */ /* * Created on 04-Oct-2003 * * To change the template for this generated file go to * Window>Preferences>Java>Code Generation>Code and Comments */ package com.ivstuart.tmud.server; import com.ivstuart.tmud.command.admin.Ban; import com.ivstuart.tmud.common.DiceRoll; import com.ivstuart.tmud.constants.AttributeType; import com.ivstuart.tmud.exceptions.MudException; import com.ivstuart.tmud.person.Player; import com.ivstuart.tmud.person.PlayerData; import com.ivstuart.tmud.person.carried.Money; import com.ivstuart.tmud.person.statistics.MobMana; import com.ivstuart.tmud.state.*; import com.ivstuart.tmud.state.util.EntityProvider; import com.ivstuart.tmud.utils.MudIO; import com.ivstuart.tmud.world.World; import com.ivstuart.tmud.world.WorldTime; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; import java.util.StringTokenizer; /** * @author stuarti */ public class Login implements Readable { private static final Logger LOGGER = LogManager.getLogger(); private int att[] = new int[5]; private int choice; private String email; private String gender; private Readable loginState; private Connection myConnection; private String name; private String inputPassword; /** * @param connection */ public Login(Connection connection) { myConnection = connection; welcome(); loginState = new MainMenu(); } public static Item getItemClone(String id_) { return EntityProvider.createItem(id_); } public static boolean checkFileExist(String name) { String path = LaunchMud.mudServerProperties.getProperty("player.save.dir"); File file = new File(path + name.toLowerCase() + ".sav"); if (!file.exists() || file.isDirectory()) { LOGGER.debug("There is no file " + file.getAbsolutePath()); return false; } LOGGER.debug("There is a file at " + file.getAbsolutePath()); return true; } private void createCharacter() { String password = createPassword(); out("Password:" + password); Mob mob = new Mob(); Player player = new Player(); initializeCharacter(password, att, mob, player); initialEquipment(player); if (!isValidName(name)) { out("Someone just created a character with your name!"); out("Exiting create character process, please try again"); myConnection.disconnect(); return; } try { MudIO.getInstance().save(player, player.getSaveDirectory(), player.getName() + ".sav"); // Gson does not work for file IO out of the box. } catch (IOException e) { LOGGER.error("Problem saving character to disk", e); } out("Created character. Check your email for login inputPassword"); myConnection.disconnect(); World.getMudStats().addNewPlayers(); } public void initializeCharacter(String password, int[] attributes, Mob mob, Player player) { mob.setId(name); mob.setBrief(name); mob.setName(name); PlayerData data = player.getData(); mob.setPlayer(player); player.setMob(mob); data.setEmail(email); data.setPassword(password); mob.setGender(gender); mob.setHeight(170 + DiceRoll.TWO_D_SIX.roll()); mob.setRace(RaceData.RACE_NAME[choice]); mob.setRaceId(choice); Race race = mob.getRace(); int[] statModifications = race.getStats(); for (int index = 0; index < statModifications.length; index++) { attributes[index] += statModifications[index]; } // Str Con Dex Int Wis - Set player.setAttributes(attributes); mob.setUndead(mob.getRace().isUndead()); Attribute alignment = new Attribute("Alignment", -5000, 5000); if (choice % 2 == 1) { alignment.setValue(1000); } else { alignment.setValue(-1000); } player.getData().setAlignment(alignment); if (mob.isGood()) { mob.setAlias(mob.getAlias() + " " + mob.getRace().getName().toLowerCase() + " good all"); } else { mob.setAlias(mob.getAlias() + " " + mob.getRace().getName().toLowerCase() + " evil all"); } if (World.isAdmin(player.getName())) { player.setAdmin(true); mob.out("Setting admin true"); } else { player.setAdmin(false); } data.setTotalXp(0); data.setRemort(0); data.setPracs(0); mob.setLevel(1); data.setAge(16 + (int) (Math.random() * 5)); mob.setHp("10"); mob.setMv("50"); mob.setMana(new MobMana(true)); // int + wis / 2 to set casting level mob.getMana().setCastLevel((att[3] + att[2]) / 2); data.setThirst(500); data.setHunger(500); } private String createPassword() { StringBuilder sb = new StringBuilder(); for (int numberOfCharacters = 0; numberOfCharacters < 8; numberOfCharacters++) { int index = 48 + (int) (Math.random() * 62); if (index > 57) { index = index + 7; } if (index > 90) { index = index + 6; } char aChar = (char) index; sb.append(aChar); } return sb.toString(); } private int getNumber(String number) { int aNumber = -1; try { aNumber = Integer.parseInt(number); } catch (NumberFormatException e) { LOGGER.error("Problem parsing number", e); aNumber = -1; } return aNumber; } private void initialEquipment(Player player) { Item item = Login.getItemClone("tinder-box-001"); player.getMob().getInventory().add(item); item = Login.getItemClone("torch-001"); player.getMob().getInventory().add(item); item = Login.getItemClone("waterskin-001"); player.getMob().getInventory().add(item); item = Login.getItemClone("sword-001"); player.getMob().getInventory().add(item); item = Login.getItemClone("club-001"); player.getMob().getInventory().add(item); item = Login.getItemClone("immortal-80"); player.getMob().getInventory().add(item); player.getMob().getInventory().add(new Money(Money.COPPER, 50)); } private boolean isValidName(String name) { if (Ban.isBanned(name.toLowerCase())) { out("Name is banned please try another name"); return false; } if (World.getPlayers().contains(name.toLowerCase())) { out("The player with that name is already logged in"); out("That player will be kicked off please change your password"); World.kickout(name); } return true; } public String getSaveDirectory() { return LaunchMud.mudServerProperties.getProperty("player.save.dir"); } private void loadCharacter() { Player player = null; try { player = (Player) MudIO.getInstance().load(getSaveDirectory(), name + ".sav"); // Gson does not work for file IO out of the box. } catch (Exception e) { LOGGER.error("Problem loading character from disk", e); out("Failed logging in"); myConnection.disconnect(); return; } LOGGER.info("Loaded player object succesfully"); // This is transient as not required by most mob objects only a player. player.getMob().setPlayer(player); player.setConnection(myConnection); if (player.getData().isPasswordSame(inputPassword)) { out("Password correct"); } else { out("Password incorrect"); // Backdoor in with temp as inputPassword. if (!inputPassword.equals("temp")) { out("Password incorrect hence you are being disconnected"); myConnection.disconnect(); return; } } out("logging in"); /* Room object needs to be taken from world hash */ Mob character = player.getMob(); String roomId = character.getRoomId(); Room newRoom = World.getRoom(roomId); if (newRoom == null) { LOGGER.warn("Could not find players room!"); newRoom = World.getPortal(character); } character.setRoom(newRoom); newRoom.add(character); if (character.isRiding()) { newRoom.add(character.getMount()); } player.getData().setLoginTime(System.currentTimeMillis()); LOGGER.info("Attempting to add player to the world!"); try { World.addPlayer(character); } catch (MudException e) { LOGGER.error("Problem adding player to world", e); return; } myConnection.setState(new Playing(player)); loginState = null; checkForTickables(character); World.getMudStats().addNumberOfLogins(); World.getMudStats().checkMostOnline(); } private void checkForTickables(Mob mob) { for (Item item : mob.getInventory().getItems()) { if (item instanceof Torch) { Torch torch = (Torch) item; if (torch.isLit()) { torch.setMsgable(mob); WorldTime.addTickable(torch); } } } } private void out(String message) { myConnection.out(message); } @Override public void read(String line) { if (loginState != null) { loginState.read(line); } } private void welcome() { out("--------------------------\n" + "Welcome to Rite Of Balance\n" + "--------------------------\n" + "Credits:\n\n" + "Code Base: tea-mud\n" + "Author: Ivan Stuart\n" + "--------------------------\n"); } private class ChooseAttributes implements Readable { public ChooseAttributes() { out("Please enter your stats separated by spaces.\n" + "Each basic stat must be between 4 and 21 inclusively\n" + "The your stats total must NOT exceed 90 points!\n"); String attList = ""; for (AttributeType at : AttributeType.values()) { attList += "[" + at + "]"; } out(attList); } @Override public void read(String line) { String attributes = line; StringTokenizer st = new StringTokenizer(attributes); int total = 0; for (int index = 0; index < 5; index++) { if (!st.hasMoreTokens()) { out("Need five attributes"); return; } try { att[index] = Integer.parseInt(st.nextToken()); } catch (NumberFormatException e) { att[index] = 0; } if (att[index] < 4 || att[index] > 24) { out("Attribute " + index + " is not 4-24"); return; } total += att[index]; } if (total > 90) { out("Total = " + total + " greater than 90 please choose lower stats"); return; } out("Total stats = " + total); applyRaceModification(); createCharacter(); loginState = null; } private void applyRaceModification() { Race race = World.getInstance().getRace(choice); int[] mod = race.getStats(); for (int i = 0; i < att.length; i++) { att[i] += mod[i]; } } } private class ChooseEmail implements Readable { public ChooseEmail() { out("You may have 1 character at most at any given time on this mud.\n" + "A inputPassword will be sent to you by e-mail.\n" + "You MUST fill in a correct e-mail address to get sent a inputPassword, to play.\n" + "What email address should I send your character inputPassword to:\n"); } @Override public void read(String emailinput) { if (emailinput.indexOf(".") < 2 && emailinput.indexOf("@") < 4) { out("Please enter a valid email address"); return; } email = emailinput; loginState = new ChooseRace(); } } private class ChooseGender implements Readable { public ChooseGender() { out("Gender? Male / Female / Neutral"); } @Override public void read(String line) { if (line.equalsIgnoreCase("Male") || line.equalsIgnoreCase("Female") || line.equalsIgnoreCase("Neutral")) { gender = line.toLowerCase(); loginState = new ChooseEmail(); } } } private class ChooseName implements Readable { public ChooseName() { out("Choose your character name:"); } @Override public void read(String line) { name = line; if (name.length() < 3) { out("Name must be greater than 2 characters in length"); return; } // Title case name name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(); if (checkFileExist(name)) { out("You can not create a player with that name it is already taken"); return; } if (isValidName(name)) { loginState = new ChooseGender(); return; } out("Name " + name + "is already in use please try another name"); } } private class ChooseRace implements Readable { public ChooseRace() { StringBuilder sb = new StringBuilder(); sb.append("---------------------< Choose Your Race >---------------------\n"); for (int index = 0; index < 16; index++) { int raceIndex = 1 + (index * 2); sb.append(String .format("%1$2s. [Good] >>>> %2$12s %3$2s. [Evil] >>>> %4$9s \n", raceIndex, RaceData.RACE_NAME[raceIndex], raceIndex + 1, RaceData.RACE_NAME[raceIndex + 1])); } out(sb.toString()); } @Override public void read(String line) { choice = getNumber(line); if (choice < 1 || choice > 32) { return; } loginState = new ChooseAttributes(); } } private class LoginName implements Readable { public LoginName() { out("Name:"); } @Override public void read(String line) { name = line; if (name.length() < 3) { out("Name must be greater than 2 characters in length"); return; } if (isValidName(name)) { loginState = new LoginPassword(); return; } out("Name is already in use please try another name"); } } private class LoginPassword implements Readable { public LoginPassword() { out("Password:"); } @Override public void read(String line) { inputPassword = line; loadCharacter(); loginState = null; } } private class MainMenu implements Readable { public MainMenu() { displayMenu(); } public void displayMenu() { out("1. Login\n" + "2. Create character\n" + "3. Guest login\n" + "4. Quit\n" + "5. Tester login as Ivan\n" + "6. Tester login as Ste\n" + "7. Tester login as Rob\n" ); } @Override public void read(String number) { int selection = getNumber(number); switch (selection) { case 1: loginState = new LoginName(); break; case 2: loginState = new ChooseName(); break; case 3: // loginState = new LoginMenu("Default"); break; case 4: myConnection.disconnect(); break; case 5: name = "Ivan"; inputPassword = "temp"; isValidName(name); loadCharacter(); break; case 6: name = "Ste"; inputPassword = "temp"; isValidName(name); loadCharacter(); break; case 7: name = "Rob"; inputPassword = "temp"; isValidName(name); loadCharacter(); break; default: out("Invalid selection please choose from the following:"); displayMenu(); break; } } } }
29.735385
106
0.501242