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
3592377037d1eb0f272e874f0b9c5f5d4cd95bc9
7,479
package org.ggp.base.player.request.factory; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.ggp.base.player.gamer.Gamer; import org.ggp.base.player.gamer.IIGamer; import org.ggp.base.player.request.factory.exceptions.RequestFormatException; import org.ggp.base.player.request.grammar.AbortRequest; import org.ggp.base.player.request.grammar.InfoRequest; import org.ggp.base.player.request.grammar.PlayRequest; import org.ggp.base.player.request.grammar.PreviewRequest; import org.ggp.base.player.request.grammar.Request; import org.ggp.base.player.request.grammar.SeesRequest; import org.ggp.base.player.request.grammar.StartRequest; import org.ggp.base.player.request.grammar.StopRequest; import org.ggp.base.util.game.Game; import org.ggp.base.util.gdl.factory.GdlFactory; import org.ggp.base.util.gdl.factory.exceptions.GdlFormatException; import org.ggp.base.util.gdl.grammar.DataFormat; import org.ggp.base.util.gdl.grammar.GdlConstant; import org.ggp.base.util.gdl.grammar.GdlPool; import org.ggp.base.util.gdl.grammar.GdlTerm; import org.ggp.base.util.symbol.factory.HRFSymbolFactory; import org.ggp.base.util.symbol.factory.SymbolFactory; import org.ggp.base.util.symbol.factory.exceptions.SymbolFormatException; import org.ggp.base.util.symbol.grammar.Symbol; import org.ggp.base.util.symbol.grammar.SymbolAtom; import org.ggp.base.util.symbol.grammar.SymbolList; public final class RequestFactory { private SymbolList parseSource(String source) throws RequestFormatException { try { SymbolList list = null; switch (GdlPool.format) { case HRF: Symbol sym = HRFSymbolFactory.create(source); if (sym.toString().length() == 1 && sym.toString().charAt(0) == 26) { return null; } SymbolList message = (SymbolList) sym; list = (SymbolList) message.get(message.size()-1); break; case KIF: list = (SymbolList) SymbolFactory.create(source); break; default: throw new SymbolFormatException("Data Format is not defined."); } return list; } catch (SymbolFormatException e) { throw new RequestFormatException(source, e); } } public Request create(Gamer gamer, String source) throws RequestFormatException { try { SymbolList list = parseSource(source); if (list == null) { return null; } SymbolAtom request = (SymbolAtom) list.get(0); String type = request.getValue().toLowerCase(); if (type.equals("play")) { return createPlay(gamer, list); } else if (type.equals("start")) { return createStart(gamer, list); } else if (type.equals("sees")) { return createSees((IIGamer) gamer, list); } else if (type.equals("stop")) { return createStop(gamer, list); } else if (type.equals("abort")) { return createAbort(gamer, list); } else if (type.equals("info")) { return createInfo(gamer, list); } else if (type.equals("preview")) { return createPreview(gamer, list); } else { throw new IllegalArgumentException("Unrecognized request type!"); } } catch (Exception e) { throw new RequestFormatException(source, e); } } private PlayRequest createPlay(Gamer gamer, SymbolList list) throws GdlFormatException { if (list.size() != 3) { throw new IllegalArgumentException("Expected exactly 2 arguments!"); } SymbolAtom arg1 = (SymbolAtom) list.get(1); Symbol arg2 = list.get(2); String matchId = arg1.getValue(); List<GdlTerm> moves = parseMoves(arg2); //remove head from HRF messages if (moves != null && GdlPool.format == DataFormat.HRF) { moves.remove(0); } return new PlayRequest(gamer, matchId, moves); } private SeesRequest createSees(IIGamer gamer, SymbolList list) throws GdlFormatException { if (list.size() != 3) { throw new IllegalArgumentException("Unexpected sees argument format!"); } SymbolAtom arg1 = (SymbolAtom) list.get(1); Symbol arg2 = list.get(2); String matchId = arg1.getValue(); Set<GdlTerm> sees = parseSees(arg2); return new SeesRequest(gamer, matchId, sees); } private StartRequest createStart(Gamer gamer, SymbolList list) throws GdlFormatException { if (list.size() < 6) { throw new IllegalArgumentException("Expected at least 5 arguments!"); } SymbolAtom arg1 = (SymbolAtom) list.get(1); SymbolAtom arg2 = (SymbolAtom) list.get(2); Symbol arg3 = list.get(3); SymbolAtom arg4 = (SymbolAtom) list.get(4); SymbolAtom arg5 = (SymbolAtom) list.get(5); String matchId = arg1.getValue(); GdlConstant roleName = (GdlConstant) GdlFactory.createTerm(arg2); String theRulesheet = arg3.toString(); int startClock = Integer.valueOf(arg4.getValue()); int playClock = Integer.valueOf(arg5.getValue()); // For now, there are only five standard arguments. If there are any // new standard arguments added to START, they should be added here. Game theReceivedGame = Game.createEphemeralGame(theRulesheet); return new StartRequest(gamer, matchId, roleName, theReceivedGame, startClock, playClock); } private StopRequest createStop(Gamer gamer, SymbolList list) throws GdlFormatException { if (list.size() != 3) { throw new IllegalArgumentException("Expected exactly 2 arguments!"); } SymbolAtom arg1 = (SymbolAtom) list.get(1); Symbol arg2 = list.get(2); String matchId = arg1.getValue(); List<GdlTerm> moves = parseMoves(arg2); return new StopRequest(gamer, matchId, moves); } private AbortRequest createAbort(Gamer gamer, SymbolList list) throws GdlFormatException { if (list.size() != 2) { throw new IllegalArgumentException("Expected exactly 1 argument!"); } SymbolAtom arg1 = (SymbolAtom) list.get(1); String matchId = arg1.getValue(); return new AbortRequest(gamer, matchId); } private InfoRequest createInfo(Gamer gamer, SymbolList list) throws GdlFormatException { if (list.size() != 1) { throw new IllegalArgumentException("Expected no arguments!"); } return new InfoRequest(gamer); } private PreviewRequest createPreview(Gamer gamer, SymbolList list) throws GdlFormatException { if (list.size() != 3) { throw new IllegalArgumentException("Expected exactly 2 arguments!"); } SymbolAtom arg1 = (SymbolAtom) list.get(1); SymbolAtom arg2 = (SymbolAtom) list.get(2); String theRulesheet = arg1.toString(); int previewClock = Integer.valueOf(arg2.getValue()); Game theReceivedGame = Game.createEphemeralGame(theRulesheet); return new PreviewRequest(gamer, theReceivedGame, previewClock); } private List<GdlTerm> parseMoves(Symbol symbol) throws GdlFormatException { if (symbol instanceof SymbolAtom) { return null; } else { List<GdlTerm> moves = new ArrayList<GdlTerm>(); SymbolList list = (SymbolList) symbol; for (int i = 0; i < list.size(); i++) { moves.add(GdlFactory.createTerm(list.get(i))); } return moves; } } private Set<GdlTerm> parseSees(Symbol symbol) throws GdlFormatException { if (symbol instanceof SymbolAtom) { return null; } else { Set<GdlTerm> sees = new HashSet<GdlTerm>(); SymbolList list = (SymbolList) symbol; for (int i = 0; i < list.size(); i++) { sees.add(GdlFactory.createTerm(list.get(i))); } return sees; } } }
27.906716
96
0.696885
d617d1182a58ed3295e2a1e9c91159f74fb07f41
1,259
package com.github.taller.zerosoffactorial.controller; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import java.util.HashMap; import java.util.Map; @ControllerAdvice(basePackages = "com.github.taller") public class ExceptionController { @ExceptionHandler(Throwable.class) public ResponseEntity<Map<String, String>> handleException(Exception ex) { Map<String, String> result = new HashMap<>(); result.put("ERROR", ex.getMessage()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); } @ExceptionHandler({MethodArgumentTypeMismatchException.class, IllegalArgumentException.class}) public ResponseEntity<Map<String, String>> handleMethodArgumentTypeMismatchException(Exception ex) { Map<String, String> result = new HashMap<>(); result.put("ERROR", "Incorrect input value. The correct value between 0 and " + Integer.MAX_VALUE); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); } }
35.971429
107
0.771247
a5a3ff08988efd1f68e76f030a030edd67ea8d5e
81
/** * DAO. * @author jiashuo * */ package org.restfulwhois.rdap.redirect.dao;
13.5
43
0.654321
80dbd5d7f3138fc21a2355813c5526f2fd12638f
951
package jenkins.plugins.play.commands; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import hudson.Extension; import hudson.util.FormValidation; /** * Represents the Play test command. */ public class PlayWar extends PlayCommand { @DataBoundConstructor public PlayWar(String parameter) { super(); this.parameter = parameter; } @Override public String getCommand() { return "war -o"; } @Extension public static class DescriptorImpl extends PlayCommandDescriptor { @Override public String getDisplayName() { return "Export the application as a standalone WAR archive [war]"; } public String getCommandId() { return "PLAY_WAR"; } public FormValidation doCheckParameter (@QueryParameter String parameter) { return FormValidation.validateRequired(parameter); } } }
22.116279
83
0.678233
385c452faeaba3f8df393d95cb889332c78dcfd3
737
package com.salecycle.moonfire.queries.havingspecs; import com.salecycle.moonfire.queries.models.havingspecs.*; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TypeCheckTest { @Test public void typeCheck() { assertEquals("filter", new QueryFilterHavingSpec().getType()); assertEquals("greaterThan", new GreaterThanHavingSpec().getType()); assertEquals("lessThan", new LessThanHavingSpec().getType()); assertEquals("dimSelector", new DimensionSelectorHavingSpec().getType()); assertEquals("and", new AndHavingSpec().getType()); assertEquals("or", new OrHavingSpec().getType()); assertEquals("not", new NotHavingSpec().getType()); } }
36.85
81
0.70692
66bc6c91548901d2c7d3c7e755769eab14e6dd1a
3,225
package org.sil.gatherwords; import android.content.Context; import android.support.annotation.Nullable; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static android.content.Context.MODE_PRIVATE; public class Util { private static final String TAG = Util.class.getSimpleName(); @Nullable public static File getNewCacheFile(Context context, String suffix) { File baseDir = context.getExternalCacheDir(); if (baseDir == null) { baseDir = context.getExternalFilesDir("external_cache"); } try { return File.createTempFile("gatherwords", suffix, baseDir); } catch (IOException e) { Log.e(TAG, "Unable to create temp cache file", e); return null; } } @Nullable public static File getNewDataFile(Context context, String suffix) { File baseDir = context.getDir("data", MODE_PRIVATE); try { return File.createTempFile("gatherwords", suffix, baseDir); } catch (IOException e) { Log.e(TAG, "Unable to create temp data file", e); return null; } } public static File getDataFile(Context context, String filename) { File baseDir = context.getDir("data", MODE_PRIVATE); return new File(baseDir.getAbsolutePath() + '/' + filename); } /** * Assumes `from` and `to` exist. * Returns true on success; if successful, `from` is deleted. * * Since this does a lot of I/O, please use in an AsyncTask. */ public static boolean moveFile(File from, File to) { // File.renameTo() does not work across mount points. // Files.copy() requires a higher api level. boolean success = false; InputStream is = null; OutputStream os = null; try { is = new FileInputStream(from); os = new FileOutputStream(to); copyStreamToStream(is, os); success = from.delete(); } catch (Exception e) { Log.e(TAG, "Error while moving file", e); } finally { try { if (is != null) { is.close(); } if (os != null) { os.close(); } } catch (Exception e) { Log.e(TAG, "Error closing streams", e); } } return success; } public static String readStream(InputStream is) { OutputStream os = new ByteArrayOutputStream(); try { copyStreamToStream(is, os); } catch (IOException e) { Log.e(TAG, "Error reading stream to string", e); return null; } return os.toString(); } private static void copyStreamToStream(InputStream is, OutputStream os) throws IOException { byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } }
29.861111
96
0.576124
67836aa84ce1a169e8eef802c208fe7a3bf8d87f
2,331
package org.uberfire.ext.editor.commons.client.history; import java.util.Date; public class ExtendedVersionRecordImpl implements ExtendedVersionRecord { private String _name; private String _versionNumber; private String _graphSlice; // Note: Will contain raw HTML to render a horizontal slice of the version graph private String _id; private String _author; private String _email; private String _comment; private String _uri; private Date _date; private boolean _isCurrentRule; public ExtendedVersionRecordImpl( String name, String versionNumber, String graphSlice, String id, String author, String email, String comment, String uri, Date date, boolean isCurrentRule) { _name = name; _versionNumber = versionNumber; _graphSlice = graphSlice; _id = id; _author = author; _email = email; _comment = comment; _uri = uri; _date = date; _isCurrentRule = isCurrentRule; } @Override public boolean isCurrentRule() { return _isCurrentRule; } @Override public void setGraphSlice(String graph) { _graphSlice = graph; } @Override public String name() { return _name; } @Override public String versionNumber() { return _versionNumber; } @Override public String graphSlice() { return _graphSlice; } @Override public String id() { return _id; } @Override public String author() { return _author; } @Override public String email() { return _email; } @Override public String comment() { return _comment; } @Override public String uri() { return _uri; } @Override public Date date() { return _date; } @Override public int compareTo(ExtendedVersionRecord o) { if (date() == null || o.date() == null) { return 0; } int v = date().compareTo(o.date()); if (v != 0) return v; // If two versions for two different rules have identical time stamps (only happens when rules are edited and committed manually), we need a deterministic ordering, so fall back to rule name ordering return name().compareTo(o.name()); } }
26.793103
207
0.624196
b8ec38d53947225130f98f106853228c61b826aa
8,197
package org.vitrivr.cineast.core.db.dao; import java.io.Closeable; import java.util.*; import java.util.stream.Collectors; import org.vitrivr.cineast.core.config.Config; import org.vitrivr.cineast.core.data.providers.primitive.PrimitiveTypeProvider; import org.vitrivr.cineast.core.data.tag.CompleteTag; import org.vitrivr.cineast.core.data.tag.Tag; import org.vitrivr.cineast.core.db.DBSelector; import org.vitrivr.cineast.core.db.PersistencyWriter; import org.vitrivr.cineast.core.db.RelationalOperator; public class TagHandler implements Closeable { private final PersistencyWriter<?> writer; private final DBSelector selector; /** * Name of the entity that contains the {@link Tag}s. */ public static final String TAG_ENTITY_NAME = "cineast_tags"; public static final String TAG_ID_COLUMNNAME= "id"; public static final String TAG_NAME_COLUMNNAME = "name"; public static final String TAG_DESCRIPTION_COLUMNNAME = "description"; /** * A map containing cached {@link Tag}s. */ private final HashMap<String, Tag> tagCache = new HashMap<>(); /** * Constructor for {@link TagHandler} * * @param selector {@link DBSelector} instanced used for lookup of tags. * @param writer {@link PersistencyWriter} used to persist tags. */ public TagHandler(DBSelector selector, PersistencyWriter<?> writer) { this.selector = selector; this.writer = writer; if (this.selector == null) { throw new NullPointerException("selector cannot be null"); } if (this.writer == null) { throw new NullPointerException("writer cannot be null"); } this.selector.open(TAG_ENTITY_NAME); this.writer.open(TAG_ENTITY_NAME); this.writer.setFieldNames(TAG_ID_COLUMNNAME, TAG_NAME_COLUMNNAME, TAG_DESCRIPTION_COLUMNNAME); } /** * Default constructor for {@link TagHandler}. Uses the {@link DBSelector} and {@link PersistencyWriter} from the configuration */ public TagHandler() { this(Config.sharedConfig().getDatabase().getSelectorSupplier().get(), Config.sharedConfig().getDatabase().getWriterSupplier().get()); } /** * Adds and persist a new {@link Tag} entry. * * @param id ID of the new entry. * @param name Name of the new entry. * @param description Description of the new entry. * @return True on success, false otherwise. */ public boolean addTag(String id, String name, String description) { return this.writer.persist(this.writer.generateTuple(id, name, description)); } /** * Adds and persist a new {@link Tag} entry. * * @param tag {@link Tag} that should be added. */ public boolean addTag(Tag tag) { if (tag == null) { return false; } return addTag(tag.getId(), tag.getName(), tag.getDescription()); } /** * Returns all {@link Tag}s that match the specified name. For matching, case-insensitive a left and right side truncation comparison is used. * The matching tags are returned in order of their expected relevance. * * @param name To value with which to match the {@link Tag}s. * @return List of matching {@link Tag}s. */ public List<Tag> getTagsByMatchingName(final String name) { final String lname = name.toLowerCase(); return this.selector.getRows("name", RelationalOperator.ILIKE, lname).stream() .map(TagHandler::fromMap) .sorted((o1, o2) -> { boolean o1l = o1.getName().toLowerCase().startsWith(lname); boolean o2l = o2.getName().toLowerCase().startsWith(lname); boolean o1e = o1.getName().toLowerCase().equals(lname); boolean o2e = o2.getName().toLowerCase().equals(lname); if (o1e && !o2e) { return -1; } else if (!o1e && o2e) { return 1; } else if (o1l && !o2l) { return -1; } else if (!o1l && o2l) { return 1; } else { return o1.getName().compareTo(o2.getName()); } }) .collect(Collectors.toList()); } /** * Returns all {@link Tag}s that are equal to the specified name. * * @param name To value with which to compare the {@link Tag}s. * @return List of matching {@link Tag}s. */ public List<Tag> getTagsByName(String name) { List<Map<String, PrimitiveTypeProvider>> rows = this.selector.getRows("name", name); ArrayList<Tag> _return = new ArrayList<>(rows.size()); for (Map<String, PrimitiveTypeProvider> row : rows) { Tag t = fromMap(row); if (t != null) { _return.add(t); } } return _return; } public Tag getTagById(String id) { if (id == null) { return null; } List<Map<String, PrimitiveTypeProvider>> rows = this.selector.getRows("id", id); if (rows.isEmpty()) { return null; } return fromMap(rows.get(0)); } public List<Tag> getTagsById(String... ids) { if (ids == null) { return null; } List<Map<String, PrimitiveTypeProvider>> rows = this.selector.getRows("id", ids); if (rows.isEmpty()) { return null; } ArrayList<Tag> _return = new ArrayList<>(rows.size()); for (Map<String, PrimitiveTypeProvider> row : rows) { Tag t = fromMap(row); if (t != null) { _return.add(t); } } return _return; } /** * Returns a list of all {@link Tag}s contained in the database. * <p> * TODO: Maybe should be removed, because ADAMpro caps the resultset anyway? * * @return List of all {@link Tag}s contained in the database */ public List<Tag> getAll() { return this.selector.getAll().stream().map(TagHandler::fromMap).filter(Objects::nonNull) .collect(Collectors.toList()); } /** * Returns a list of all cached {@link Tag}s. * * @return List of all {@link Tag}s contained in the cache. */ public List<Tag> getAllCached() { return new ArrayList<>(this.tagCache.values()); } public void initCache() { List<Tag> all = getAll(); for (Tag tag : all) { this.tagCache.put(tag.getId(), tag); } } public void flushCache() { this.tagCache.clear(); } public Tag getCachedById(String id) { return this.tagCache.get(id); } public List<Tag> getCachedByName(String name) { ArrayList<Tag> _return = new ArrayList<>(); for (Tag t : this.tagCache.values()) { if (t.getName().equals(name)) { _return.add(t); } } return _return; } private static Tag fromMap(Map<String, PrimitiveTypeProvider> map) { if (map == null || map.isEmpty()) { return null; } if (!map.containsKey("id") || !map.containsKey("name")) { return null; } if (!map.containsKey("description")) { return new CompleteTag(map.get("id").getString(), map.get("name").getString(), ""); } else { return new CompleteTag(map.get("id").getString(), map.get("name").getString(), map.get("description").getString()); } } @Override public void close() { this.selector.close(); this.writer.close(); } @Override protected void finalize() throws Throwable { close(); super.finalize(); } }
33.321138
147
0.557155
93e88abe36a0ac713fa4d5378f6d2e945fa7e6a0
278
package com.metaui.core.datasource.persist; import java.util.Map; /** * 持久化数据库接口 * * @author wei_jc * @since 1.0.0 */ public interface IPDB { /** * 获得持久化数据Map * * @return 返回持久化数据Map */ Map<String, ? extends Map<String, Object>> getPDBMap(); }
14.631579
59
0.600719
4f3c1ac57edbd47769a02f87dacae8788c601110
821
package tech.wetech.weshop.user.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import tech.wetech.weshop.common.service.BaseService; import tech.wetech.weshop.user.dto.GoodsFootprintDTO; import tech.wetech.weshop.user.mapper.FootprintMapper; import tech.wetech.weshop.user.po.Footprint; import tech.wetech.weshop.user.service.FootprintService; import java.util.List; /** * @author [email protected] */ @Service public class FootprintServiceImpl extends BaseService<Footprint> implements FootprintService { @Autowired private FootprintMapper footprintMapper; @Override public List<GoodsFootprintDTO> queryGoodsFootprintByUserId(Integer userId) { return footprintMapper.selectGoodsFootprintByUserId(userId); } }
30.407407
94
0.80877
6306223931810e1ac7b26f45d95762fdcf52db45
134
package com.babel17.jruntime; public class B17Object extends B17Value { public final static B17Object nil = new B17Object(); }
16.75
56
0.753731
a2d982e46d8e37c17a39d44e42a14e7258f518fb
1,339
package org.framework.hsven.mybatis.mapper; import org.apache.ibatis.annotations.Param; import org.framework.hsven.mybatis.vo.LowerCaseResultMap; import org.framework.hsven.mybatis.vo.PageRecord; import org.framework.hsven.mybatis.vo.QueryEntity; import org.framework.hsven.mybatis.vo.VarableBinds; import java.util.List; import java.util.Map; /** * */ public interface SimpleBaseGenericMapper { int queryCountByCondition(@Param("queryEntity") QueryEntity queryEntity, @Param("varableBinds") VarableBinds varableBinds); List<LowerCaseResultMap<Object>> selectOraclePageByCondition(@Param("queryEntity") QueryEntity queryEntity, @Param("varableBinds") VarableBinds varableBinds, @Param("page") PageRecord page); List<LowerCaseResultMap> executeSql(String sql); int executeInsertSql(String sql); int executeUpdateSql(String sql); int executeDeleteSql(String sql); int selectCountSql(String sql); Object selectOneResult(String sql); List<LowerCaseResultMap> executeDynamicSql(Map<String, Object> params); int insertDynamicTable(Map<String, Object> params); int executeDynamicSelectInsert(Map<String, Object> params); int updateDynamicTable(Map<String, Object> params); int deleteDynamicTable(Map<String, Object> params); void callProcedure(String procedureName); }
28.489362
194
0.775952
a5f24267d40c0df44f7eedd8f0b575b6c55e21dd
1,555
package lab9; import java.util.Scanner; /** * * @author Sanat 190953222 * Count number of characters, words, lines and vowels */ public class program1 { public static void main(String[] args){ //Initialize all the counters to 0 int noLines=0,noWords=0,noChars=0,noVow=0; String input="",temp; System.out.println("Enter a string, press ~ to stop input"); Scanner scan1=new Scanner(System.in); while(scan1.hasNext()){ temp=scan1.nextLine(); if(temp.equals("~")) break; input+=temp; /** * End of line signals * end of a word as well, * hence noWord++ */ noLines++; noWords++; } noChars=input.length(); /** * Convert to lower case to * make code uniform */ input=input.toLowerCase(); for(int i=0;i<input.length();i++){ if(input.charAt(i)=='a' || input.charAt(i)=='e' || input.charAt(i)=='i' || input.charAt(i)=='o' || input.charAt(i)=='u') noVow++; if(input.charAt(i)==' ') noWords++; } //Print all the required details System.out.println("The numer of Lines are "+noLines); System.out.println("The numer of Words are "+noWords); System.out.println("The numer of Chars are "+noChars); System.out.println("The numer of Vowels are "+noVow); } }
33.085106
133
0.505466
f64cd6203da5e4d8aa443aacca8b969947652591
613
package org.nganga.manx; import retrofit.RestAdapter; /** * Created by nganga on 9/25/15. */ //RestAdapter is the class that transforms an API interface into an object which actually makes network requests. //To use our SCService we create a RestAdapter and then use it to create a real instance of the interface. public class SoundCloud { final static RestAdapter REST_ADAPTER = new RestAdapter.Builder().setEndpoint(Config.API_URL).build(); final static SCService SC_SERVICE = REST_ADAPTER.create(SCService.class); public static SCService getService() { return SC_SERVICE; } }
26.652174
113
0.748777
60adc3294859875009376711bb4aa97f2f648d8d
1,831
package br.com.ufc.quixada.dspersist.schoolmanagement.services; import java.util.List; import java.util.Optional; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.ufc.quixada.dspersist.schoolmanagement.dto.course.CreateCourseDTO; import br.com.ufc.quixada.dspersist.schoolmanagement.dto.course.UpdateCourseDTO; import br.com.ufc.quixada.dspersist.schoolmanagement.exceptions.CourseException; import br.com.ufc.quixada.dspersist.schoolmanagement.models.Course; import br.com.ufc.quixada.dspersist.schoolmanagement.models.Student; import br.com.ufc.quixada.dspersist.schoolmanagement.repositories.CourseRepository; @Service public class CourseService { @Autowired private CourseRepository repository; public void create(CreateCourseDTO dto) { Boolean codeExists = this.repository.findByCode(dto.getCode()).isPresent(); if(Boolean.TRUE.equals(codeExists)) throw CourseException.codeAlreadyExistsError(); this.repository.save(dto.export()); } public List<Course> list() { return this.repository.findAll(); } public void delete(Long courseId) { if(!this.repository.findById(courseId).isPresent()) throw CourseException.courseNotFoundError(); this.repository.deleteById(courseId); } public void update(UpdateCourseDTO dto) { Optional<Course> courseExists = this.repository.findById(dto.getId()); if(!courseExists.isPresent()) throw CourseException.courseNotFoundError(); Optional<Course> codeExists = this.repository.findByCode(dto.getCode()); if(Boolean.TRUE.equals(codeExists.isPresent()) && !codeExists.get().getId().equals(dto.getId())) throw CourseException.codeAlreadyExistsError(); this.repository.save(dto.export()); } }
31.568966
100
0.770617
ee12b5c1899f881ef00539ad45cbf4648d47acf0
1,773
package com.hx.home.presenter; import com.hexing.libhexbase.cache.StringCache; import com.hexing.libhexbase.inter.RxBasePresenterImpl; import com.hx.base.model.UserInfoEntity; import com.hx.home.AboutActivity; import com.hx.home.Constant; import com.hx.home.HomeApplication; import com.hx.home.ManualActivity; import com.hx.home.R; import com.hx.home.contact.HomeContract; import com.hx.base.model.HomeMenu; import java.util.ArrayList; import java.util.List; public class HomePresenter extends RxBasePresenterImpl<HomeContract.View> implements HomeContract.Presenter { public HomePresenter(HomeContract.View view) { super(view); } /** * 获取左侧显示菜单 */ @Override public void getLeftMenu() { List<HomeMenu> menus = new ArrayList<>(); HomeMenu menu = new HomeMenu(); menu.name = ((UserInfoEntity) StringCache.getJavaBean(Constant.USER_INFO)).getEn_name(); menu.resourceId = R.mipmap.icon_country; menus.add(menu); menu = new HomeMenu(); menu.name = HomeApplication.getInstance().getString(R.string.home_menu_about); menu.resourceId = R.mipmap.icon_about; menu.cls = AboutActivity.class; menus.add(menu); //Instruction manual menu = new HomeMenu(); menu.name = HomeApplication.getInstance().getString(R.string.home_instruction_manual); menu.resourceId = R.mipmap.icon_instruction_manual; menu.cls = ManualActivity.class; menus.add(menu); menu = new HomeMenu(); menu.name = StringCache.get(Constant.PRE_KEY_HHU_ID); menu.resourceId = R.mipmap.icon_serial; menus.add(menu); getView().showLeftMenu(menus); } }
32.236364
110
0.671179
37ab9b31bb147beb223fcb855e3343525c652875
1,455
package dev.formathero.datetimeformatter.application; import dev.formathero.datetimeformatter.application.port.FabricatorRepository; import dev.formathero.datetimeformatter.domain.Fabricator; import java.time.ZonedDateTime; import java.util.List; public class FabricatorService { private final List<ZonedDateTime> exampleDates; private final FabricatorRepository fabricatorRepository; public FabricatorService(FabricatorRepository fabricatorRepository, List<ZonedDateTime> exampleDates) { this.exampleDates = exampleDates; this.fabricatorRepository = fabricatorRepository; } public void withPatternElement(String patternElement, String patternId) { Fabricator fabricator = findBy(patternId) .with(patternElement); fabricatorRepository.save(fabricator, patternId); } public List<String> currentExamples(String patternId) { Fabricator fabricator = findBy(patternId); return exampleDates.stream() .map(fabricator::formatFor) .toList(); } public String patternFor(String patternId) { Fabricator fabricator = findBy(patternId); return fabricator.pattern(); } private Fabricator findBy(String patternId) { return fabricatorRepository .findById(patternId) .orElse(Fabricator.EMPTY); } }
33.068182
78
0.680412
4baa33d0cf72338ae16e7c18b16066ef5205d2b0
1,429
package fun.gengzi.codecopy.exception; import fun.gengzi.codecopy.constant.RspCodeEnum; import fun.gengzi.codecopy.vo.ReturnData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DuplicateKeyException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; /** * 异常处理器 */ @RestControllerAdvice public class RrExceptionHandler { private Logger logger = LoggerFactory.getLogger(getClass()); /** * 自定义异常 */ @ExceptionHandler(RrException.class) public ReturnData handleRRException(RrException e) { ReturnData returnData = ReturnData.newInstance(); returnData.setFailure(e.getMessage()); return returnData; } @ExceptionHandler(DuplicateKeyException.class) public ReturnData handleDuplicateKeyException(DuplicateKeyException e) { logger.error(e.getMessage(), e); ReturnData returnData = ReturnData.newInstance(); returnData.setFailure("数据库中已存在该记录!"); return returnData; } @ExceptionHandler(Exception.class) public ReturnData handleException(Exception e) { logger.error(e.getMessage(), e); ReturnData returnData = ReturnData.newInstance(); returnData.setFailure("未知异常,请稍等再试!"); returnData.setStatus(RspCodeEnum.ERROR_SYSTEM.getCode()); return returnData; } }
30.404255
76
0.729181
2156c7a4a3549dc2aeaf41adf4401a8bdef5962b
984
package frc.robot; import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX; import edu.wpi.first.wpilibj.Joystick; public class Intake { WPI_TalonSRX intakeMotor; Joystick controller; double throttleValue; public Intake(int motor, Joystick controller2) { intakeMotor = new WPI_TalonSRX(motor); controller = controller2; } public void intakeControl() { // throttle right bumper if(controller.getRawButton(6) == true){ throttleValue = 0.2; } else { throttleValue = 0.0; } // left trigger / forward if(controller.getRawAxis(2) > 0.5) { intakeMotor.set(0.8 + throttleValue); } // right trigger / reverse else if(controller.getRawAxis(3) > 0.5) { intakeMotor.set(-(0.8 + throttleValue)); } // no button / do nothing else { intakeMotor.set(0.0); } } }
22.363636
54
0.561992
3ff0ca8b611af5b2ec1704560a3ac7da1ecb130a
127
package com.hubspot.dropwizard.guicier.objects; import javax.ws.rs.ext.Provider; @Provider public class ProvidedProvider { }
15.875
47
0.80315
17ce1a62d9f8d5a4b878668013d9e534b0ccd941
4,942
/* * 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 uk.ac.uea.cmp.srnaworkbench.database.entities; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import uk.ac.uea.cmp.srnaworkbench.tools.normalise.NormalisationType; import uk.ac.uea.cmp.srnaworkbench.utils.math.Logarithm; /** * * @author matt */ @Entity //@Table(name="ABUNDANCE_BOX_AND_WHISKERS") public class AbundanceBoxAndWhisker_Entity extends Distribution implements Serializable { // @Id // @Column(name="ID") // @GeneratedValue(strategy=GenerationType.AUTO) // private Long id; @OneToOne @JoinColumn(name="File_Name") // @Column(name="File_Name") private Filename_Entity sample; @Enumerated private NormalisationType normType; @Column(name="Annotation_Type") String annotationType; // @Embedded // private Distribution distribution; @Embedded private AbundanceWindow window; // @OneToMany(fetch=FetchType.LAZY, mappedBy="dist", cascade = CascadeType.ALL) // Set<AbundanceBoxAndWhisker_Outlier> outliers = new HashSet<>(); /** * No-argument constructor for Table-specific use */ protected AbundanceBoxAndWhisker_Entity(){} public AbundanceBoxAndWhisker_Entity(Filename_Entity sample, NormalisationType normType, String annotationType, Logarithm logBase, double lq, double med, double uq, double minRange, double maxRange, double minAbundance, double maxAbundance) { super(Logarithm.BASE_2,lq,med,uq,minRange,maxRange); this.sample = sample; this.normType = normType; this.annotationType = annotationType; //this.distribution = new Distribution(logBase, lq, med, uq, minRange, maxRange); this.window = new AbundanceWindow(minAbundance, maxAbundance); } public AbundanceBoxAndWhisker_Entity(Filename_Entity sample, NormalisationType normType, String annotationType, Distribution dist, double minAbundance, double maxAbundance) { super(dist); this.sample = sample; this.normType = normType; this.annotationType = annotationType; //this.distribution = new Distribution(logBase, lq, med, uq, minRange, maxRange); this.window = new AbundanceWindow(minAbundance, maxAbundance); } /** * Allows creation of an entity by initially setting sample and normType. * Distribution and window can be set later. * @param sample * @param normType */ public AbundanceBoxAndWhisker_Entity(Filename_Entity sample, NormalisationType normType, String annotationType) { this.sample = sample; this.normType = normType; this.annotationType = annotationType; } // public Distribution getDistribution() { // return distribution; // } // // public void setDistribution(Distribution distribution) { // this.distribution = distribution; // } public AbundanceWindow getWindow() { return window; } public void setWindow(AbundanceWindow window) { this.window = window; } public Filename_Entity getSample() { return sample; } public void setSample(Filename_Entity sample) { this.sample = sample; } public NormalisationType getNormType() { return normType; } public void setNormType(NormalisationType normType) { this.normType = normType; } public String getAnnotationType() { return annotationType; } public void setAnnotationType(String annotationType) { this.annotationType = annotationType; } // public Set<AbundanceBoxAndWhisker_Outlier> getOutliers() { // return outliers; // } // // public void setOutliers(Set<AbundanceBoxAndWhisker_Outlier> outliers) { // this.outliers = outliers; // } @Override public String toString() { StringBuilder sb = new StringBuilder(); // sb.append(this.id).append(":: ") sb.append(sample).append(", ").append(normType).append(", Annotation ").append(annotationType) .append("\n\t") //.append(this.getDistribution().toString()) .append("[ ").append(this.getWindow().toString()).append(" ]"); return (sb.toString()); } }
31.477707
142
0.686766
ba9620c72c96f7fcacb05c0b85adb82b244b5580
366
package me.egg82.antivpn.api.platform; import org.jetbrains.annotations.NotNull; public class BungeePluginMetadata extends AbstractPluginMetadata { private final String pluginVersion; public BungeePluginMetadata(String pluginVersion) { this.pluginVersion = pluginVersion; } public @NotNull String getVersion() { return pluginVersion; } }
26.142857
66
0.770492
7ffc96ea1f18099bb439ac39adb52a53687c720e
3,855
/* * 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.cassandra.io.util; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.concurrent.ThreadLocalRandom; import org.junit.Test; import org.junit.Assert; import org.apache.cassandra.utils.memory.MemoryUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class MemoryTest { @Test public void testByteBuffers() { byte[] bytes = new byte[1000]; ThreadLocalRandom.current().nextBytes(bytes); final Memory memory = Memory.allocate(bytes.length); memory.setBytes(0, bytes, 0, bytes.length); ByteBuffer canon = ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder()); test(canon, memory); memory.setBytes(0, new byte[1000], 0, 1000); memory.setBytes(0, canon.duplicate()); test(canon, memory); memory.close(); } @Test public void testInputStream() throws IOException { byte[] bytes = new byte[4096]; ThreadLocalRandom.current().nextBytes(bytes); final Memory memory = Memory.allocate(bytes.length); memory.setBytes(0, bytes, 0, bytes.length); try(MemoryInputStream stream = new MemoryInputStream(memory, 1024)) { byte[] bb = new byte[bytes.length]; assertEquals(bytes.length, stream.available()); stream.readFully(bb); assertEquals(0, stream.available()); assertTrue(Arrays.equals(bytes, bb)); try { stream.readInt(); fail("Expected EOF exception"); } catch (EOFException e) { //pass } } } private static void test(ByteBuffer canon, Memory memory) { ByteBuffer hollow = MemoryUtil.getHollowDirectByteBuffer(); test(canon, hollow, memory, 0, 1000); test(canon, hollow, memory, 33, 100); test(canon, hollow, memory, 77, 77); test(canon, hollow, memory, 903, 96); } private static void test(ByteBuffer canon, ByteBuffer hollow, Memory memory, int offset, int length) { canon = canon.duplicate(); canon.position(offset).limit(offset + length); canon = canon.slice().order(ByteOrder.nativeOrder()); test(canon, memory.asByteBuffer(offset, length)); memory.setByteBuffer(hollow, offset, length); test(canon, hollow); } private static void test(ByteBuffer canon, ByteBuffer test) { Assert.assertEquals(canon, test); for (int i = 0 ; i <= canon.limit() - 4 ; i += 4) Assert.assertEquals(canon.getInt(i), test.getInt(i)); for (int i = 0 ; i <= canon.limit() - 8 ; i += 8) Assert.assertEquals(canon.getLong(i), test.getLong(i)); } }
33.815789
105
0.629572
a86ea068e3973d1f7e780e183acc7a40efe480cc
311
package com.kids.api.quiz; import java.sql.Date; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NonNull; import lombok.RequiredArgsConstructor; @Data @AllArgsConstructor @RequiredArgsConstructor public class TodayQuiz { private Date date; @NonNull private Integer quizNo; }
16.368421
38
0.787781
dd98cf09d0450821779dd6219ffbffef78b7127b
3,459
package com.yangdb.fuse.executor.ontology.schema; import com.yangdb.fuse.dispatcher.driver.IdGeneratorDriver; import com.yangdb.fuse.executor.ontology.schema.load.DefaultGraphInitiator; import com.yangdb.fuse.executor.ontology.schema.load.GraphInitiator; import com.yangdb.fuse.model.Range; import com.yangdb.test.BaseITMarker; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static com.yangdb.fuse.executor.TestSuiteIndexProviderSuite.*; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; public class GraphInitiatorIT implements BaseITMarker { @Test public void testSchema() throws IOException { Set<String> strings = Arrays.asList("idx_fire_500","idx_freeze_2000","idx_fire_1500","idx_freeze_1000","own","subjectof","dragon","idx_freeze_1500","idx_fire_2000","kingdom","people","idx_fire_1000","horse","guild","idx_freeze_500","know","registeredin","originatedin","memberof").stream().collect(Collectors.toSet()); Assert.assertEquals(strings,StreamSupport.stream(nestedSchema.indices().spliterator(),false).collect(Collectors.toSet())); } @Test public void testNestedInit() throws IOException { IdGeneratorDriver<Range> idGeneratorDriver = Mockito.mock(IdGeneratorDriver.class); when(idGeneratorDriver.getNext(anyString(),anyInt())) .thenAnswer(invocationOnMock -> new Range(0,1000)); GraphInitiator initiator = new DefaultGraphInitiator(config,client,nestedProviderIfc,ontologyProvider,nestedSchema); Assert.assertEquals(19,initiator.init()); } @Test public void testCreateMappings() throws IOException { IdGeneratorDriver<Range> idGeneratorDriver = Mockito.mock(IdGeneratorDriver.class); when(idGeneratorDriver.getNext(anyString(),anyInt())) .thenAnswer(invocationOnMock -> new Range(0,1000)); GraphInitiator initiator = new DefaultGraphInitiator(config,client,nestedProviderIfc,ontologyProvider,nestedSchema); Assert.assertEquals(14,initiator.createTemplate("Dragons",mapper.writeValueAsString(nestedProvider))); } @Test @Ignore("Remove the existing template mapping before calling the API") public void testCreateIndices() throws IOException { IdGeneratorDriver<Range> idGeneratorDriver = Mockito.mock(IdGeneratorDriver.class); when(idGeneratorDriver.getNext(anyString(),anyInt())) .thenAnswer(invocationOnMock -> new Range(0,1000)); GraphInitiator initiator = new DefaultGraphInitiator(config,client,nestedProviderIfc,ontologyProvider,nestedSchema); Assert.assertEquals(13,initiator.createIndices("Dragons",mapper.writeValueAsString(nestedProvider))); } @Test public void testNestedDrop() throws IOException { IdGeneratorDriver<Range> idGeneratorDriver = Mockito.mock(IdGeneratorDriver.class); when(idGeneratorDriver.getNext(anyString(),anyInt())) .thenAnswer(invocationOnMock -> new Range(0,1000)); GraphInitiator initiator = new DefaultGraphInitiator(config,client,nestedProviderIfc,ontologyProvider,nestedSchema); Assert.assertEquals(19,initiator.drop()); } }
48.041667
326
0.756866
79c3e249a045bf9c4f799d32ab1a643130890013
660
package soul.core.models.string_mesh.utilities.components.corpus.data; public class Output implements Comparable<Output> { private String output; private double feedback; public Output(String newOutput, double newFeedback) { output = newOutput; feedback = newFeedback; } public void setOutput(String newOutput) { output = newOutput; } public void setFeedback(double newFeedback) { feedback = newFeedback; } public String getOutput() { return output; } public double getFeedback() { return feedback; } public int compareTo(Output o) { return feedback == o.getFeedback() ? 0 : (feedback > o.getFeedback() ? 1 : -1); } }
20.625
81
0.715152
79fc421ddfdbca3e7c702e19b5f149e20ef90ddf
893
package network.elrond.blockchain; import network.elrond.data.model.Block; import network.elrond.data.model.Receipt; import network.elrond.data.model.Transaction; import java.math.BigInteger; public enum BlockchainUnitType { BLOCK(String.class, Block.class), BLOCK_INDEX(BigInteger.class, String.class), TRANSACTION(String.class, Transaction.class), SETTINGS(String.class, String.class), RECEIPT(String.class, Receipt.class), TRANSACTION_RECEIPT(String.class, String.class), BLOCK_TRANSACTIONS(String.class, String.class),; private Class<?> keyType; private Class<?> valueType; BlockchainUnitType(Class<?> keyType, Class<?> valueType) { this.keyType = keyType; this.valueType = valueType; } public Class<?> getKeyType() { return keyType; } public Class<?> getValueType() { return valueType; } }
27.060606
62
0.702128
54d2536ac579750ea375facbb5eeb28babc2427e
13,260
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.directshare; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Base64; import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.regex.Matcher; import io.ipfs.api.IPFS; import io.ipfs.api.JSONParser; import io.ipfs.api.MerkleNode; import io.ipfs.api.NamedStreamable; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * Provides the UI for sharing a text with a {@link ShareContext}. */ public class SendMessageActivity extends Activity { /** * The request code for {@link SelectShareContextActivity}. This is used when the user doesn't select * any of Direct Share icons. */ private static final int REQUEST_SELECT_CONTACT = 1; /** * The text to share. */ private String mBody; private Uri mImage; /** * The ID of the context to share the text with. */ private int mContextId; // View references. private TextView mTextContactName; private TextView mTextMessageBody; public class Wrapper { public Object result; public Object[] params; } class SendImage extends AsyncTask<Object, Void, Wrapper> { @Override protected Wrapper doInBackground(Object... params) { Log.e("OPENSHARE", "INSIDE IMAGE ASYNC"); IPFS ipfs = new IPFS("beta.userfeeds.io", 5001); NamedStreamable.ByteArrayWrapper file = new NamedStreamable.ByteArrayWrapper("image", convertImageToByte((Uri) params[0])); Wrapper w = new Wrapper(); try { MerkleNode addResult = ipfs.add(file); Log.e("OPENSHARE", addResult.toJSONString()); w.result = addResult.toJSON(); w.params = params; return w; } catch (IOException e) { e.printStackTrace(); Log.e("SHARE", "SEND_IMAGE", e); } Log.e("OPENSHARE", "INSIDE IMAGE ASYNC"); return null; } public byte[] convertImageToByte(Uri uri){ byte[] data = null; try { ContentResolver cr = getBaseContext().getContentResolver(); InputStream inputStream = cr.openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); data = baos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } return data; } @Override protected void onPostExecute(Wrapper w) { super.onPostExecute(w); Map result = (Map) w.result; Log.e("AAAA", JSONParser.toString(w.result)); SendClaim sendClaim = new SendClaim(); sendClaim.execute("ipfs:" + result.get("Hash").toString(), (String) w.params[1], (String) w.params[2], (String) w.params[3], (String) w.params[4]); } } class SendClaim extends AsyncTask<String, Void, Void> { final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); @Override protected Void doInBackground(String... params) { ShareContext shareContext = ShareContext.byId(Integer.valueOf(params[1])); Log.e("OPENSHARE", "INSIDE ASYNC"); /* { "context" : "ethereum", "issued" : "2016-06-21T03:40:19Z", "type" : [ "Claim", "Backing" ], "claim" : { "target" : "alamakota", "amount" : 13 }, "signature" : { "type" : "EthereumSignature.1", "created" : "2016-06-21T03:40:19Z", "creator" : "0xfE02a56127aFfBba940bB116Fa30A3Af10d12f80", "domain" : "ethereum", "nonce" : "783b4dfa", "signatureValue" : "Rxj7Kb/tDbGHFAs6ddHjVLsHDiNyYzxs2MPmNG8G47oS06N8i0Dis5mUePIzII4+p/ewcOTjvH7aJxnKEePCO9IrlqaHnO1TfmTut2rvXxE5JNzur0qoNq2yXl+TqUWmDXoHZF+jQ7gCsmYqTWhhsG5ufo9oyqDMzPoCb9ibsNk=" } } */ JSONObject body = new JSONObject(); Log.e("A", params[0]); String target; Matcher m = Patterns.WEB_URL.matcher(params[0]); if (m.find()) { target = m.group(); } else { target = "text:base64:" + Base64.encodeToString(params[0].getBytes(), Base64.DEFAULT); } try { JSONArray labels = new JSONArray(); labels.put(params[3]); JSONObject claim = new JSONObject(); claim.put("target", target); claim.put("labels", labels); JSONObject signature = new JSONObject(); signature.put("created", System.currentTimeMillis()); signature.put("creator", params[2]); signature.put("type", shareContext.getSignatureType()); signature.put("domain", shareContext.getDomain()); signature.put("nonce", "???"); signature.put("signatureValue", ""); JSONArray types = new JSONArray(); types.put("Claim"); types.put("Labels"); body.put("context", shareContext.getIdentifier()); body.put("issued", System.currentTimeMillis()); body.put("type", types); body.put("claim", claim); body.put("signature", signature); } catch (JSONException e) { e.printStackTrace(); } try { post("https://beta.userfeeds.io:443/", body.toString()); } catch (IOException e) { e.printStackTrace(); } Log.e("OPENSHARE", "INSIDE ASYNC END"); return null; } String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); return response.body().string(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.send_message); //setTitle(R.string.sending_message); // View references. mTextContactName = (TextView) findViewById(R.id.contact_name); mTextMessageBody = (TextView) findViewById(R.id.message_body); // Resolve the share Intent. boolean resolved = resolveIntent(getIntent()); if (!resolved) { finish(); return; } // Bind event handlers. //findViewById(R.id.send).setOnClickListener(mOnClickListener); // Set up the UI. prepareUi(); // The contact ID will not be passed on when the user clicks on the app icon rather than any // of the Direct Share icons. In this case, we show another dialog for selecting a contact. if (mContextId == ShareContext.INVALID_ID) { selectContext(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_SELECT_CONTACT: if (resultCode == RESULT_OK) { mContextId = data.getIntExtra(ShareContext.ID, ShareContext.INVALID_ID); } // Give up sharing the send_message if the user didn't choose a contact. if (mContextId == ShareContext.INVALID_ID) { finish(); return; } prepareUi(); break; default: super.onActivityResult(requestCode, resultCode, data); } } /** * Resolves the passed {@link Intent}. This method can only resolve intents for sharing a plain * text. {@link #mBody} and {@link #mContextId} are modified accordingly. * * @param intent The {@link Intent}. * @return True if the {@code intent} is resolved properly. */ private boolean resolveIntent(Intent intent) { String action = intent.getAction(); String type = intent.getType(); mContextId = intent.getIntExtra(ShareContext.ID, ShareContext.INVALID_ID); if (Intent.ACTION_SEND.equals(action) && type != null) { if ("text/plain".equals(type)) { handleSendText(intent); // Handle text being sent } else if (type.startsWith("image/")) { handleSendImage(intent); // Handle single image being sent } return true; } return false; } void handleSendText(Intent intent) { mBody = intent.getStringExtra(Intent.EXTRA_TEXT); } void handleSendImage(Intent intent) { mImage = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); } /** * Sets up the UI. */ private void prepareUi() { if (mContextId != ShareContext.INVALID_ID) { ShareContext shareContext = ShareContext.byId(mContextId); ShareContextViewBinder.bind(shareContext, mTextContactName, getApplicationContext()); } mTextMessageBody.setText(mBody); } /** * Delegates selection of a {@Context} to {@link SelectShareContextActivity}. */ private void selectContext() { Intent intent = new Intent(this, SelectShareContextActivity.class); intent.setAction(SelectShareContextActivity.ACTION_SELECT_CONTACT); startActivityForResult(intent, REQUEST_SELECT_CONTACT); } public void onSendClick(View view) { EditText titleEdit = (EditText) findViewById(R.id.claimTitle); String title = titleEdit.getText().toString(); switch (view.getId()) { case R.id.thumbsup: send(title, "thumbsup"); break; case R.id.thumbsdown: send(title, "thumbsdown"); break; } } /** * Pretends to send the text to the contact. This only shows a dummy message. */ private void send(String title, String label) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final String profile = prefs.getString("selectedProfile", "error"); final String claimTitle = title; final String claimLabel = label; runOnUiThread(new Runnable() { @Override public void run() { if (mImage != null) { Log.e("NEW TASK", "IMAGE TASK"); SendImage sendImage = new SendImage(); sendImage.execute(mImage, String.valueOf(mContextId), profile, claimTitle, claimLabel); } else { Log.e("NEW TASK", "TEXT TASK"); SendClaim sendClaim = new SendClaim(); sendClaim.execute(mBody, String.valueOf(mContextId), profile, claimTitle, claimLabel); } } }); Toast.makeText(this, getString(R.string.message_sent, mBody, ShareContext.byId(mContextId).getName()), Toast.LENGTH_SHORT).show(); finish(); } }
34.263566
217
0.578959
c17b556101771020c57b99fdab3f5a6179f6bd5e
2,408
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: packimports(3) fieldsfirst lnc // Source File Name: Function.java package com.icl.saxon.expr; import java.io.PrintStream; // Referenced classes of package com.icl.saxon.expr: // Expression, XPathException public abstract class Function extends Expression { protected Expression argument[]; private int numberOfArguments; public Function() { /* 14*/ argument = new Expression[6]; /* 15*/ numberOfArguments = 0; } public void addArgument(Expression expression) { /* 22*/ if(numberOfArguments >= argument.length) { /* 23*/ Expression aexpression[] = new Expression[argument.length * 2]; /* 24*/ System.arraycopy(argument, 0, aexpression, 0, numberOfArguments); /* 25*/ argument = aexpression; } /* 27*/ argument[numberOfArguments++] = expression; } public int getNumberOfArguments() { /* 35*/ return numberOfArguments; } public abstract String getName(); protected int checkArgumentCount(int i, int j) throws XPathException { /* 57*/ int k = numberOfArguments; /* 58*/ if(i == j && k != i) /* 59*/ throw new XPathException("Function " + getName() + " must have " + i + pluralArguments(i)); /* 61*/ if(k < i) /* 62*/ throw new XPathException("Function " + getName() + " must have at least " + i + pluralArguments(i)); /* 64*/ if(k > j) /* 65*/ throw new XPathException("Function " + getName() + " must have no more than " + j + pluralArguments(j)); /* 67*/ else /* 67*/ return k; } private String pluralArguments(int i) { /* 75*/ if(i == 1) /* 75*/ return " argument"; /* 76*/ else /* 76*/ return " arguments"; } public void display(int i) { /* 84*/ System.err.println(Expression.indent(i) + "function " + getName()); /* 85*/ for(int j = 0; j < numberOfArguments; j++) /* 86*/ argument[j].display(i + 1); } }
32.986301
124
0.526578
27098fde359248990b5b4cf1ace010741d6b41ac
542
static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } }
38.714286
76
0.52952
95acea11e81df3e7ab972b38963425fd64456b24
1,184
/* MasterMaze: A Maze-Solving Game Copyright (C) 2008-2010 Eric Ahnell Any questions should be directed to the author via email at: [email protected] */ package com.puttysoftware.mastermaze.maze.objects; import com.puttysoftware.mastermaze.creatures.StatConstants; import com.puttysoftware.mastermaze.maze.generic.GenericPotion; import com.puttysoftware.mastermaze.resourcemanagers.ObjectImageConstants; public class MajorHealPotion extends GenericPotion { // Fields private static final int MIN_HEAL = 6; private static final int MAX_HEAL = 50; // Constructors public MajorHealPotion() { super(StatConstants.STAT_CURRENT_HP, true, MajorHealPotion.MIN_HEAL, MajorHealPotion.MAX_HEAL); } @Override public int getBaseID() { return ObjectImageConstants.OBJECT_IMAGE_MAJOR_HEAL_POTION; } @Override public String getName() { return "Major Heal Potion"; } @Override public String getPluralName() { return "Major Heal Potions"; } @Override public String getDescription() { return "Major Heal Potions heal you significantly when picked up."; } }
28.190476
87
0.71875
fe33e330c97a37641bc70993b9754c2a882495b5
426
import com.avaje.ebean.Ebean; import models.User; import play.Application; import play.GlobalSettings; import play.libs.Yaml; import java.util.List; /** * Created by Daniel on 2015-06-19. */ public class Global extends GlobalSettings { @Override public void onStart(Application application) { if(User.find.findRowCount() == 0) { Ebean.save((List) Yaml.load("bootstrap.yml")); } } }
21.3
58
0.673709
cec0fa685fd69597c0381e02de77c3ad5a07ef2d
1,019
package org.clyze.source.irfitter.source.model; import java.util.Collection; import org.clyze.persistent.model.Position; import org.clyze.persistent.model.UsageKind; /** * A reference to a type name (such as an annotation referencing an annotation type) * or a constant Class object (such as {@code C.class}). */ public class TypeUse extends ElementUse implements FuzzyTypes { public final String type; private Collection<String> cachedIds = null; public TypeUse(String type, Position position, SourceFile sourceFile) { super(sourceFile, position, UsageKind.TYPE); this.type = type; } @Override public SourceFile getSourceFile() { return sourceFile; } @Override public Collection<String> getIds() { if (cachedIds == null) cachedIds = resolveType(type); return cachedIds; } @Override public String toString() { return "type-use:: " + type + "@" + sourceFile.getRelativePath() + ", " + position; } }
27.540541
91
0.670265
009e31d6f5735dd7df99787f279ec7fba140e437
4,040
/*- * ============LICENSE_START======================================================= * ONAP : APPC * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Copyright (C) 2017 Amdocs * ============================================================================= * 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.appc.statemachine.objects; import org.junit.Assert; import org.junit.Test; import org.mockito.internal.util.reflection.Whitebox; import java.util.List; public class StateTest { private final String STATE_NAME = "Starting"; private State state = new State(STATE_NAME); @SuppressWarnings("unchecked") @Test public void testConstructor() { State state = new State(STATE_NAME); Assert.assertEquals("Should set stateName", STATE_NAME, Whitebox.getInternalState(state, "stateName")); Assert.assertEquals("Should set hash code", STATE_NAME.toLowerCase().hashCode(), (int)Whitebox.getInternalState(state, "hashCode")); List<Transition> transitions = (List<Transition>) Whitebox.getInternalState(state, "transitions"); Assert.assertTrue("Should initialized transtiions", transitions != null && transitions.isEmpty()); } @Test public void testHashCode() throws Exception { Assert.assertEquals("Should return proper hash code", STATE_NAME.toLowerCase().hashCode(), state.hashCode()); } @Test public void testEquals() throws Exception { Assert.assertFalse("should return false for null", state.equals(null)); Assert.assertFalse("should return false for object", state.equals(new Event(STATE_NAME))); Assert.assertFalse("should return false for different event", state.equals(new Event("Another"))); Assert.assertTrue("should return true", state.equals(new State(STATE_NAME))); Assert.assertTrue("should return true (lower case)", state.equals(new State(STATE_NAME.toLowerCase()))); } @Test public void testGetStateName() throws Exception { Assert.assertEquals("Should return STATE_NAME", STATE_NAME, state.getStateName()); } @SuppressWarnings("unchecked") @Test public void testAddAndGetTransition() throws Exception { Transition transition1 = new Transition(new Event("event1"), new State("state2")); List<Transition> transitions = (List<Transition>) Whitebox.getInternalState(state, "transitions"); Assert.assertFalse("should not have transition1", transitions.contains(transition1)); state.addTransition(transition1); transitions = (List<Transition>) Whitebox.getInternalState(state, "transitions"); Assert.assertTrue("should have added transition1", transitions.contains(transition1)); Assert.assertEquals("Should return transitions", transitions, state.getTransitions()); state.addTransition(null); Assert.assertEquals("Should not change transitions", transitions, Whitebox.getInternalState(state, "transitions")); } @Test public void testToString() throws Exception { Assert.assertEquals("Should return STATE_NAME", STATE_NAME, state.toString()); } }
44.395604
112
0.632178
7456e6887e41dbe715e87bd2870f521756c60b7a
86
/** * Service layer beans. */ package com.cea.digitalworld.dwmicroservice2.service;
17.2
53
0.744186
eca15f3a6cdfe6ad38ecdcd7a1f41561e5735627
751
package com.tvd12.ezyfox.binding.impl; import com.tvd12.ezyfox.binding.EzyBindingConfig; import com.tvd12.ezyfox.binding.EzyBindingContext; import com.tvd12.ezyfox.binding.EzyBindingContextAware; import com.tvd12.ezyfox.reflect.EzyClass; public class EzySimpleConfigurationLoader implements EzyConfigurationLoader { private final EzyClass clazz; public EzySimpleConfigurationLoader(EzyClass clazz) { this.clazz = clazz; } @Override public void load(EzyBindingContext context) { Object configurator = clazz.newInstance(); if(configurator instanceof EzyBindingContextAware) ((EzyBindingContextAware)configurator).setContext(context); if(configurator instanceof EzyBindingConfig) ((EzyBindingConfig)configurator).config(); } }
30.04
77
0.813582
00b5215ee0f85c4ae5cc2c787755a9f62281982a
4,864
package gluu.scim2.client; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import gluu.scim2.client.factory.ScimClientFactory; import gluu.scim2.client.rest.ClientSideService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.gluu.oxauth.model.util.SecurityProviderUtility; import org.gluu.oxtrust.model.scim2.user.UserResource; import org.testng.ITestContext; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Hashtable; import java.util.Map; import java.util.Properties; /** * Created by jgomer on 2017-06-09. * Base class for tests (as former BaseScimTest) but reads contents for properties from files instead of a having all JSON * content written in a single .properties file. */ public class BaseTest { private static final String FILE_PREFIX="file:"; private static final Charset DEFAULT_CHARSET=Charset.forName("UTF-8"); private static final String NEW_LINE=System.getProperty("line.separator"); protected static ClientSideService client=null; protected Logger logger = LogManager.getLogger(getClass()); protected ObjectMapper mapper=new ObjectMapper(); @BeforeSuite public void initTestSuite(ITestContext context) throws Exception { SecurityProviderUtility.installBCProvider(); logger.info("Invoked initTestSuite of '{}'", context.getCurrentXmlTest().getName()); //Properties with the file: preffix will point to real .json files stored under src/test/resources folder String properties = context.getCurrentXmlTest().getParameter("file"); Properties prop = new Properties(); prop.load(Files.newBufferedReader(Paths.get(properties), DEFAULT_CHARSET)); //do not bother much about IO issues here Map<String, String> parameters = new Hashtable<>(); //do not bother about empty keys... but //If a value is found null, this will throw a NPE since we are using a Hashtable prop.forEach((Object key, Object value) -> parameters.put(key.toString(), decodeFileValue(value.toString()))); // Override test parameters context.getSuite().getXmlSuite().setParameters(parameters); if (client==null) { setupClient(context.getSuite().getXmlSuite().getParameters()); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); } } @AfterSuite public void finalize(){ client.close(); } private void setupClient(Map<String, String> params) throws Exception{ logger.info("Initializing client..."); boolean testMode=Boolean.parseBoolean(System.getProperty("testmode")); /* To get a simpler client (not one that supports all possible operations as in this case), you can use as class parameter any other interface from gluu.scim2.client.rest or org.gluu.oxtrust.ws.rs.scim2 packages. Find an example at test method gluu.scim2.client.SampleTest#smallerClient */ if (testMode) client=ScimClientFactory.getTestClient(ClientSideService.class, params.get("domainURL"), params.get("OIDCMetadataUrl")); //client=ScimClientFactory.getDummyClient(params.get("domainURL")); else client=ScimClientFactory.getClient( ClientSideService.class, params.get("domainURL"), params.get("umaAatClientId"), params.get("umaAatClientJksPath"), params.get("umaAatClientJksPassword"), params.get("umaAatClientKeyId")); } private String decodeFileValue(String value){ String decoded = value; if (value.startsWith(FILE_PREFIX)) { value = value.substring(FILE_PREFIX.length()); //remove the prefix try (BufferedReader bfr = Files.newBufferedReader(Paths.get(value), DEFAULT_CHARSET)) { //create reader //appends every line after another decoded = bfr.lines().reduce("", (partial, next) -> partial + NEW_LINE + next); if (decoded.length()==0) logger.warn("Key '{}' is empty", value); } catch (IOException e){ logger.error(e.getMessage(), e); decoded=null; } //No need to close bfr: try-with-resources statements does it } return decoded; } public UserResource getDeepCloneUsr(UserResource bean) throws Exception{ return mapper.readValue(mapper.writeValueAsString(bean), UserResource.class); } }
40.87395
132
0.680921
72f6e1f332d83f3facbe2c2d94cd51c7d88b8e94
1,488
package modules.home.domain.usecases; import modules.home.domain.entities.AnnouncementEntity; import modules.home.domain.errors.CreateAnnouncementError; import modules.home.domain.errors.DeleteAnnouncementError; import modules.home.domain.errors.IHomeException; import modules.home.domain.repositories.IHomeRepository; import java.util.List; interface IDeleteMyAnnouncementUsecase { List<AnnouncementEntity> deleteMyAnnouncement(int userID, String productCode) throws IHomeException; } public class DeleteMyAnnouncementUsecase implements IDeleteMyAnnouncementUsecase { private IHomeRepository _repository; private static DeleteMyAnnouncementUsecase instance; private DeleteMyAnnouncementUsecase(IHomeRepository repository) { try { Thread.sleep(100); } catch (InterruptedException ex) { ex.printStackTrace(); } this._repository = repository; } public static DeleteMyAnnouncementUsecase getInstance(IHomeRepository repository) { if (instance == null) { instance = new DeleteMyAnnouncementUsecase(repository); } return instance; } @Override public List<AnnouncementEntity> deleteMyAnnouncement(int userID, String productCode) throws IHomeException { try { return _repository.deleteMyAnnouncement(userID, productCode); } catch (Exception e) { throw new DeleteAnnouncementError(e.getMessage()); } } }
30.367347
112
0.732527
11c0b6532c965d84968d76649ca77fb7d5f716dd
4,952
/* * Copyright 2017-present Skean Project Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package party.threebody.skean.web.data; import party.threebody.skean.data.query.Operator; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class SkeanWebConfig { private CriteriaVarNameConfig criteriaVarName = new CriteriaVarNameConfig(); private HeaderNameConfig headerName = new HeaderNameConfig(); private String UriVarMultiValuesDelimitter =","; public String getUriVarMultiValuesDelimitter() { return UriVarMultiValuesDelimitter; } /** * if null diabled. default to comma * @param uriVarMultiValuesDelimitter */ public void setUriVarMultiValuesDelimitter(String uriVarMultiValuesDelimitter) { this.UriVarMultiValuesDelimitter = uriVarMultiValuesDelimitter; } public CriteriaVarNameConfig getCriteriaVarName() { return criteriaVarName; } public void setCriteriaVarName(CriteriaVarNameConfig criteriaVarName) { this.criteriaVarName = criteriaVarName; } public HeaderNameConfig getHeaderName() { return headerName; } public void setHeaderName(HeaderNameConfig headerName) { this.headerName = headerName; } public static class HeaderNameConfig { private String totalCount = "X-Total-Count"; private String totalAffected = "X-Total-Affected"; public String getTotalCount() { return totalCount; } public void setTotalCount(String totalCount) { this.totalCount = totalCount; } public String getTotalAffected() { return totalAffected; } public void setTotalAffected(String totalAffected) { this.totalAffected = totalAffected; } } public static class CriteriaVarNameConfig { private List<String> pageIndex = Arrays.asList("p", "page"); private List<String> pageOffset = Arrays.asList("f", "offset"); private List<String> pageLimit = Arrays.asList("l", "limit", "per_page"); private List<String> orders = Arrays.asList("o", "orders"); private List<String> ordersAscPrefixes = Arrays.asList("+"); private List<String> ordersDescPrefixes = Arrays.asList("!", "-"); private String extesibleVarSuffixTemplate = "_{x}"; // operator displayed name -> operator real name private Map<String, String> operators = Stream.of(Operator.values()).collect( Collectors.toMap(Operator::name, Operator::name)); public List<String> getPageIndex() { return pageIndex; } public void setPageIndex(List<String> pageIndex) { this.pageIndex = pageIndex; } public List<String> getPageOffset() { return pageOffset; } public void setPageOffset(List<String> pageOffset) { this.pageOffset = pageOffset; } public List<String> getPageLimit() { return pageLimit; } public void setPageLimit(List<String> pageLimit) { this.pageLimit = pageLimit; } public List<String> getOrders() { return orders; } public void setOrders(List<String> orders) { this.orders = orders; } public List<String> getOrdersAscPrefixes() { return ordersAscPrefixes; } public void setOrdersAscPrefixes(List<String> ordersAscPrefixes) { this.ordersAscPrefixes = ordersAscPrefixes; } public List<String> getOrdersDescPrefixes() { return ordersDescPrefixes; } public void setOrdersDescPrefixes(List<String> ordersDescPrefixes) { this.ordersDescPrefixes = ordersDescPrefixes; } public String getExtesibleVarSuffixTemplate() { return extesibleVarSuffixTemplate; } public void setExtesibleVarSuffixTemplate(String extesibleVarSuffixTemplate) { this.extesibleVarSuffixTemplate = extesibleVarSuffixTemplate; } public Map<String, String> getOperators() { return operators; } public void setOperators(Map<String, String> operators) { this.operators = operators; } } }
30.012121
86
0.656099
c8b1bb6c3bba1170144fc4f73cb8a1c1c4799c42
584
package GUI.TableData; import javafx.collections.FXCollections; import javafx.collections.ObservableList; /* * Observable class model for files what will be loaded in TableView. */ public class FilesModelObservableList{ private ObservableList<FilesModel> filesModels = FXCollections.observableArrayList(); public ObservableList<FilesModel> getFilesModels() { return filesModels; } public void addFile(String globalPath, String name, String fileFormat, int length){ filesModels.add(new FilesModel(globalPath, name, fileFormat, length)); } }
26.545455
89
0.756849
f995bfeb33b2857cc55ee3ed3a07546eb3fc9a36
946
package simple.autho.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; @Entity @Data @Table(name="tb_user") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="user_id") private int userId; @Column(name="username", length = 128, nullable = false, unique = true) private String userName; @Column(length = 128, nullable = false, unique = true) private String email; @Column(name = "mobile", length = 16, nullable = false, unique = true) private String mobilePhone; private Date createDate; @Column(name="last_login") private Date lastLoginDate; @Column(name="passwd", length = 32, nullable = false, unique = true) private String passWd; }
27.028571
75
0.72093
b794b47f02d582f6a4c1bdbf5effde6d65461834
704
package com.example.demo; import akka.actor.ActorSystem; import io.vavr.concurrent.Future; import io.vavr.control.Option; import java.math.BigDecimal; public class DemoApplication { public static void main(String[] args) { ActorSystem actorSystem = ActorSystem.create(); BankCommandHandler commandHandler = new BankCommandHandler(); BankEventHandler eventHandler = new BankEventHandler(); Bank bank = new Bank(actorSystem, commandHandler, eventHandler); String id = bank.createAccount(BigDecimal.valueOf(100)).get().get().currentState.get().id; BigDecimal balance = bank.withdraw(id, BigDecimal.valueOf(50)).get().get().currentState.get().balance; System.out.println(balance); } }
29.333333
104
0.767045
b8117b42a266c569ddc3340b9bbf0cb8a8093e2b
5,280
// Source : https://leetcode.com/problems/word-ladder-ii/ // Author : Kris // Date : 2020-08-05 /***************************************************************************************************** * * Given two words (beginWord and endWord), and a dictionary's word list, find all shortest * transformation sequence(s) from beginWord to endWord, such that: * * Only one letter can be changed at a time * Each transformed word must exist in the word list. Note that beginWord is not a transformed * word. * * Note: * * Return an empty list if there is no such transformation sequence. * All words have the same length. * All words contain only lowercase alphabetic characters. * You may assume no duplicates in the word list. * You may assume beginWord and endWord are non-empty and are not the same. * * Example 1: * * Input: * beginWord = "hit", * endWord = "cog", * wordList = ["hot","dot","dog","lot","log","cog"] * * Output: * [ * ["hit","hot","dot","dog","cog"], * ["hit","hot","lot","log","cog"] * ] * * Example 2: * * Input: * beginWord = "hit" * endWord = "cog" * wordList = ["hot","dot","dog","lot","log"] * * Output: [] * * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. * ******************************************************************************************************/ class Solution { public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) { if (wordList == null || !wordList.contains(endWord)) { return new ArrayList<List<String>>(); } // add beginWord wordList.add(beginWord); // remove duplicate wordList = wordList.stream().distinct().collect(Collectors.toList()); // build graph var graph = buildGraph(wordList); // breadth first search var myQueue = bfs(graph, beginWord, endWord); // build result from myQueue return buildResult(myQueue, endWord); } Map<String, List<String>> buildGraph(List<String> wordList) { var graph = new HashMap<String, List<String>>(); for (int i = 0; i < wordList.size(); i++) { var curWord = wordList.get(i); var list = new ArrayList<String>(); graph.put(wordList.get(i), list); for (int j = 0; j < wordList.size(); j++) { if (canTransform(curWord, wordList.get(j))) { list.add(wordList.get(j)); } } } return graph; } boolean canTransform(String src, String dest) { if (src.length() != dest.length()) { return false; } var diff = 0; for (var i = 0; i < src.length(); i++) { if (src.charAt(i) != dest.charAt(i)) { diff++; } } return diff == 1; } List<Node> bfs(Map<String, List<String>> graph, String beginWord, String endWord) { var myQueue = new ArrayList<Node>(); var visit = new HashMap<String, Integer>(); var level = 0; // simulate a queue by list myQueue.add(new Node(beginWord, -1)); visit.put(beginWord, level); var finish = false; var i = 0; while (i < myQueue.size()) { level++; var size = myQueue.size(); for (; i < size; i++) { var cur = myQueue.get(i); var neighbors = graph.get(cur.word); for (var neighbor : neighbors) { if (neighbor.equals(cur.word)) { finish = true; } if (visit.containsKey(neighbor) && level != visit.get(neighbor)) { continue; } myQueue.add(new Node(neighbor, i)); visit.put(neighbor, level); } } if (finish) { break; } } return myQueue; } List<List<String>> buildResult(List<Node> myQueue, String endWord) { myQueue.forEach(x -> System.out.print(x.word + ", ")); var paths = new ArrayList<List<String>>(); var lastNodes = new ArrayList<Node>(); for (var i = 0; i < myQueue.size(); i++) { if (myQueue.get(i).word.equals(endWord)) { lastNodes.add(myQueue.get(i)); } } for (var i = 0; i < lastNodes.size(); i++) { var one = new ArrayList<String>(); var cur = lastNodes.get(i); while (cur.prePos != -1) { one.add(0, cur.word); cur = myQueue.get(cur.prePos); }; one.add(0, cur.word); paths.add(one); } return paths; } } class Node { String word; int prePos; public Node(String word, int prePos) { this.word = word; this.prePos = prePos; } }
29.497207
104
0.473106
6708a6fd194a7408597cc004e18ec11e65246419
984
package com.turkcell.rentACar.business.abstracts; import java.util.List; import com.turkcell.rentACar.business.dtos.BrandDto; import com.turkcell.rentACar.business.dtos.BrandListDto; import com.turkcell.rentACar.business.requests.createRequests.CreateBrandRequest; import com.turkcell.rentACar.business.requests.updateRequests.UpdateBrandRequest; import com.turkcell.rentACar.core.utilities.exceptions.BusinessException; import com.turkcell.rentACar.core.utilities.results.DataResult; import com.turkcell.rentACar.core.utilities.results.Result; public interface BrandService { DataResult<List<BrandListDto>> getAll(); Result add(CreateBrandRequest createBrandRequest) throws BusinessException; DataResult<BrandDto> getById(int id) throws BusinessException; Result update(UpdateBrandRequest updateBrandRequest) throws BusinessException; Result deleteById(int id) throws BusinessException; void checkIfBrandExists(int id) throws BusinessException; }
32.8
82
0.830285
c2a2e752698117537748da58e9def14a9a91b2be
1,046
package org.sadtech.bot.gitlab.data.impl; import lombok.NonNull; import org.sadtech.bot.gitlab.context.domain.entity.Discussion; import org.sadtech.bot.gitlab.context.repository.DiscussionRepository; import org.sadtech.bot.gitlab.data.jpa.DiscussionJpaRepository; import org.sadtech.haiti.database.repository.manager.AbstractSimpleManagerRepository; import org.springframework.stereotype.Repository; import java.util.List; /** * // TODO: 11.02.2021 Добавить описание. * * @author upagge 11.02.2021 */ @Repository public class DiscussionRepositoryImpl extends AbstractSimpleManagerRepository<Discussion, String> implements DiscussionRepository { private final DiscussionJpaRepository jpaRepository; public DiscussionRepositoryImpl(DiscussionJpaRepository jpaRepository) { super(jpaRepository); this.jpaRepository = jpaRepository; } @Override public List<Discussion> findAllByMergeRequestId(@NonNull Long mergeRequestId) { return jpaRepository.findAllByMergeRequestId(mergeRequestId); } }
31.69697
131
0.797323
6c21e1a05594557f0e160f73da855281396e2d58
1,584
package com.tsengfhy.vservice.basic.config; import com.tsengfhy.vservice.basic.repository.SysJobDetailsRepository; import com.tsengfhy.vservice.basic.template.SchedulerTemplate; import com.tsengfhy.vservice.basic.template.impl.QuartzSchedulerTemplate; import lombok.extern.slf4j.Slf4j; import org.quartz.Scheduler; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.JpaRepository; import javax.annotation.PostConstruct; @Slf4j @Configuration @ConditionalOnClass({Scheduler.class}) @AutoConfigureAfter({QuartzAutoConfiguration.class}) public class QuartzConfig { @PostConstruct public void init() { log.info("VService module [Quartz] is loaded"); } @Configuration @ConditionalOnClass({JpaRepository.class}) @AutoConfigureAfter({JPAConfig.class}) static class TemplateConfig { @Bean public SchedulerTemplate schedulerTemplate(Scheduler scheduler, SysJobDetailsRepository sysJobDetailsRepository) throws Exception { QuartzSchedulerTemplate schedulerTemplate = new QuartzSchedulerTemplate(); schedulerTemplate.setScheduler(scheduler); schedulerTemplate.setSysJobDetailsRepository(sysJobDetailsRepository); return schedulerTemplate; } } }
35.2
139
0.794823
1bd44470c7749502190383ec32fca7ff07f5309d
138
package novi.uni.compserver.model.enums; public enum SportName { FOOTBALL, RUGBY, BASKETBALL, BASEBALL, VOLLEYBALL }
13.8
40
0.681159
99c92467f7bf31142e9202c0cba4c016024b3317
7,868
// // Copyright (c) 2013 Ford Motor Company // package com.smartdevicelink.proxy; import java.util.Vector; import com.smartdevicelink.exception.SmartDeviceLinkException; import com.smartdevicelink.exception.SmartDeviceLinkExceptionCause; import com.smartdevicelink.proxy.rpc.SyncMsgVersion; import com.smartdevicelink.proxy.rpc.enums.Language; import com.smartdevicelink.trace.SyncTrace; public class SmartDeviceLinkProxy extends SmartDeviceLinkProxyBase<IProxyListener> { private static final String SMARTDEVICELINK_LIB_TRACE_KEY = "42baba60-eb57-11df-98cf-0800200c9a66"; private static final String SMARTDEVICELINK_LIB_PRIVATE_TOKEN = "{DAE1A88C-6C16-4768-ACA5-6F1247EA01C2}"; /** * Constructor for the SmartDeviceLinkProxy object, the proxy for communicating between the App and SmartDeviceLink. * * @param listener - Reference to the object in the App listening to callbacks from SmartDeviceLink. * @throws SmartDeviceLinkException */ public SmartDeviceLinkProxy(IProxyListener listener) throws SmartDeviceLinkException { super( listener, /*application context*/null, /*enable advanced lifecycle management*/false, /*app name*/ null, /*ngn media screen app name*/null, /*vr synonyms*/null, /*is media app*/ null, /*SyncMsgVersion*/null, /*language desired*/null, /*autoActivateID*/null, /*callbackToUIThread*/ true); SyncTrace.logProxyEvent("Application constructed SmartDeviceLinkProxy instance passing in: IProxyListener.", SMARTDEVICELINK_LIB_TRACE_KEY); } /** * Constructor for the SmartDeviceLinkProxy object, the proxy for communicating between the App and SmartDeviceLink. * * @param listener - Reference to the object in the App listening to callbacks from SmartDeviceLink. * @param applicationContext - Context of the application. Used to access application specific resources. * @throws SmartDeviceLinkException */ public SmartDeviceLinkProxy(IProxyListener listener, SmartDeviceLinkProxyConfigurationResources SmartDeviceLinkProxyConfigurationResources) throws SmartDeviceLinkException { super( listener, SmartDeviceLinkProxyConfigurationResources, /*enable advanced lifecycle management*/false, /*app name*/ null, /*ngn media screen app name*/null, /*vr synonyms*/null, /*is media app*/ null, /*SyncMsgVersion*/null, /*language desired*/null, /*autoActivateID*/null, /*callbackToUIThread*/ true); SyncTrace.logProxyEvent("Application constructed SmartDeviceLinkProxy instance passing in: IProxyListener, SmartDeviceLinkProxyConfigurationResources.", SMARTDEVICELINK_LIB_TRACE_KEY); } /** * Constructor for the SmartDeviceLinkProxy object, the proxy for communicating between the App and SmartDeviceLink. * * @param listener - Reference to the object in the App listening to callbacks from SmartDeviceLink. * @param callbackToUIThread - If true, all callbacks will occur on the UI thread. * @throws SmartDeviceLinkException */ public SmartDeviceLinkProxy(IProxyListener listener, boolean callbackToUIThread) throws SmartDeviceLinkException { super( listener, /*SmartDeviceLink proxy configuration resources*/null, /*enable advanced lifecycle management*/false, /*app name*/ null, /*ngn media screen app name*/null, /*vr synonyms*/null, /*is media app*/ null, /*SyncMsgVersion*/null, /*language desired*/null, /*autoActivateID*/null, callbackToUIThread); SyncTrace.logProxyEvent("Application constructed SmartDeviceLinkProxy instance passing in: IProxyListener, callBackToUIThread.", SMARTDEVICELINK_LIB_TRACE_KEY); } /** * Constructor for the SmartDeviceLinkProxy object, the proxy for communicating between the App and SmartDeviceLink. * * @param listener - Reference to the object in the App listening to callbacks from SmartDeviceLink. * @param applicationContext - Context of the application. Used to access application specific resources. * @param callbackToUIThread - If true, all callbacks will occur on the UI thread. * @throws SmartDeviceLinkException */ public SmartDeviceLinkProxy(IProxyListener listener, SmartDeviceLinkProxyConfigurationResources SmartDeviceLinkProxyConfigurationResources, boolean callbackToUIThread) throws SmartDeviceLinkException { super( listener, SmartDeviceLinkProxyConfigurationResources, /*enable advanced lifecycle management*/false, /*app name*/ null, /*ngn media screen app name*/null, /*vr synonyms*/null, /*is media app*/ null, /*SyncMsgVersion*/null, /*language desired*/null, /*autoActivateID*/null, callbackToUIThread); SyncTrace.logProxyEvent("Application constructed SmartDeviceLinkProxy instance passing in: IProxyListener, callBackToUIThread.", SMARTDEVICELINK_LIB_TRACE_KEY); } /******************** Public Helper Methods *************************/ /** * Sends a RegisterAppInterface RPCRequest to SmartDeviceLink. Responses are captured through callback on IProxyListener. * * @param SyncMsgVersion * @param appName * @param ngnMediaScreenAppName * @param vrSynonyms * @param isMediaApp * @param languageDesired * @param autoActivateID * @param correlationID * * @throws SmartDeviceLinkException */ public void registerAppInterface( SyncMsgVersion SyncMsgVersion, String appName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, Language languageDesired, String autoActivateID, Integer correlationID) throws SmartDeviceLinkException { // Test if proxy has been disposed if (_proxyDisposed) { throw new SmartDeviceLinkException("This SmartDeviceLinkProxy object has been disposed, it is no long capable of sending requests.", SmartDeviceLinkExceptionCause.SMARTDEVICELINK_PROXY_DISPOSED); } registerAppInterfacePrivate( SyncMsgVersion, appName, ngnMediaScreenAppName, vrSynonyms, isMediaApp, languageDesired, autoActivateID, correlationID); } /** * Sends a RegisterAppInterface RPCRequest to SmartDeviceLink. Responses are captured through callback on IProxyListener. * * @param appName * @param isMediaApp * @param autoActivateID * @throws SmartDeviceLinkException */ public void registerAppInterface( String appName, Boolean isMediaApp, String autoActivateID, Integer correlationID) throws SmartDeviceLinkException { registerAppInterface( /*SyncMsgVersion*/null, appName, /*ngnMediaScreenAppName*/null, /*vrSynonyms*/null, isMediaApp, /*languageDesired*/null, autoActivateID, correlationID); } /** * Sends a RegisterAppInterface RPCRequest to SmartDeviceLink. Responses are captured through callback on IProxyListener. * * @param appName * @throws SmartDeviceLinkException */ public void registerAppInterface(String appName, Integer correlationID) throws SmartDeviceLinkException { registerAppInterface(appName, false, "", correlationID); } /** * Sends an UnregisterAppInterface RPCRequest to SmartDeviceLink. Responses are captured through callback on IProxyListener. * * @param correlationID * @throws SmartDeviceLinkException */ public void unregisterAppInterface(Integer correlationID) throws SmartDeviceLinkException { // Test if proxy has been disposed if (_proxyDisposed) { throw new SmartDeviceLinkException("This SmartDeviceLinkProxy object has been disposed, it is no long capable of executing methods.", SmartDeviceLinkExceptionCause.SMARTDEVICELINK_PROXY_DISPOSED); } unregisterAppInterfacePrivate(correlationID); } /** * Returns is isConnected state of the SmartDeviceLink transport. * * @return Boolean isConnected */ public Boolean getIsConnected() { return super.getIsConnected(); } }
36.425926
198
0.756228
09f2db41b1e754917f91bb4fe3757ad14c1f078b
2,333
/* * Copyright Dingxuan. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.bcia.javachain.core.ledger.kvledger.txmgmt.rwsetutil; import com.google.protobuf.ByteString; import org.bcia.julongchain.protos.ledger.rwset.Rwset; import org.bcia.julongchain.protos.ledger.rwset.kvrwset.KvRwset; /** * 操作CollHashedRwSet辅助类 * * @author sunzongyu * @date 2018/04/08 * @company Dingxuan */ public class CollHashedRwSet { private String collectionName = null; private KvRwset.HashedRWSet hashedRwSet = null; private ByteString pvtRwSetHash = null; public CollHashedRwSet(String collectionName, ByteString pvtRwSetHash, KvRwset.HashedRWSet hashedRwSet) { this.collectionName = collectionName; this.hashedRwSet = hashedRwSet; this.pvtRwSetHash = pvtRwSetHash; } public String getCollectionName() { return collectionName; } public void setCollectionName(String collectionName) { this.collectionName = collectionName; } public KvRwset.HashedRWSet getHashedRwSet() { return hashedRwSet; } public void setHashedRwSet(KvRwset.HashedRWSet hashedRwSet) { this.hashedRwSet = hashedRwSet; } public ByteString getPvtRwSetHash() { return pvtRwSetHash; } public void setPvtRwSetHash(ByteString pvtRwSetHash) { this.pvtRwSetHash = pvtRwSetHash; } /** * 将CollHashedRwSet转换为proto中CollectionHashedReadWriteSet */ public Rwset.CollectionHashedReadWriteSet toProtoMsg(){ Rwset.CollectionHashedReadWriteSet.Builder builder = Rwset.CollectionHashedReadWriteSet.newBuilder() .setCollectionName(collectionName) .setPvtRwsetHash(pvtRwSetHash) .setHashedRwset(hashedRwSet.toByteString()); return builder.build(); } }
31.106667
109
0.729104
c6c5ceed3fbfc1ea122dfca8633155f35993c053
2,175
package lgw.com.uiwedgit.adapter; import android.app.Activity; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import lgw.com.uiwedgit.R; import lgw.com.uiwidget.StickyHeaderDecoration; public class StickyAdapter extends RecyclerView.Adapter<StickyAdapter.InnerHolder> implements StickyHeaderDecoration.StickHeaderInterface { public StickyAdapter( Activity activity, List<String> dates ) { this.activity = activity; this.dates = dates; } @Override public boolean isSticky( int position ) { return position % 10 == 0; } Activity activity; private List<String> dates; @Override public InnerHolder onCreateViewHolder( ViewGroup parent, int viewType ) { View inflate = LayoutInflater.from( activity ).inflate( R.layout.item_refresh_recylerview, parent, false ); return new InnerHolder( inflate ); } @Override public void onBindViewHolder( InnerHolder holder, int position ) { holder.itemView.setBackgroundResource( android.R.color.white ); holder.tvText.setTextColor( Color.DKGRAY ); holder.tvText.setText( dates.get( position ) ); } @Override public int getItemCount() { return dates.size(); } View stickyView; TextView textView; @Override public View getStickyView( RecyclerView parent, int position ) { if ( stickyView == null ) { stickyView = LayoutInflater.from( activity ).inflate( R.layout.item_refresh_recylerview, parent, false ); textView = stickyView.findViewById( R.id.tvContent ); textView.setTextColor( Color.RED ); textView.setBackgroundColor( Color.BLUE ); } textView.setText( position / 10 + "" ); return stickyView; } @Override public String getStickyViewAx( int position ) { return position / 10 + " is clicked"; } class InnerHolder extends RecyclerView.ViewHolder { TextView tvText; public InnerHolder( View itemView ) { super( itemView ); tvText = ( TextView ) itemView.findViewById( R.id.tvContent ); } } }
27.531646
139
0.724138
3a636efdbb554004d4829b09dc876ae97e0f0068
4,613
/* * Copyright (c) 2016 Nova Ordis LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.novaordis.utilities.os; import io.novaordis.utilities.Files; import org.slf4j.Logger; import java.io.File; /** * A proxy for the underlying operating system. A thread-safe JVM-level singleton that can be used for native command * execution. * * Implementations must correctly implement equals() and hashCode(). * * @author Ovidiu Feodorov <[email protected]> * @since 7/31/16 */ public interface OS extends NativeExecutor { // Constants ------------------------------------------------------------------------------------------------------- String OS_IMPLEMENTATION_PROPERTY_NAME = "os.class"; // // Conventional OS names // @SuppressWarnings("unused") String MacOS = "MacOS"; @SuppressWarnings("unused") String Linux = "Linux"; @SuppressWarnings("unused") String Windows = "Windows"; // // cached instance // OS[] instance = new OS[1]; // Static ---------------------------------------------------------------------------------------------------------- /** * Build and return the OS implementation appropriated for this system. The default behavior can be modified by * setting "os.class" system property to contain a fully qualified class name of an OS implementation. * * The method caches the instance internally upon creation. It is guaranteed that two successive invocations return * instances that are identical (instance1 == instance2). */ static OS getInstance() throws Exception { synchronized (instance) { if (instance[0] != null) { return instance[0]; } // // first attempt to look up a custom implementation - this is mainly useful while testing // String osImplementationClassName = System.getProperty(OS_IMPLEMENTATION_PROPERTY_NAME); if (osImplementationClassName != null) { Class c = Class.forName(osImplementationClassName); instance[0] = (OS) c.newInstance(); } else { String osName = System.getProperty("os.name"); if (osName == null) { throw new IllegalStateException( "'" + OS_IMPLEMENTATION_PROPERTY_NAME + "' or 'os.name' system properties not available"); } String lcOsName = osName.toLowerCase(); if (lcOsName.contains("mac")) { instance[0] = new MacOS(); } else if (lcOsName.contains("linux")) { instance[0] = new LinuxOS(); } else if (lcOsName.contains("windows")) { instance[0] = new WindowsOS(); } else { throw new IllegalStateException("unrecognized 'os.name' value " + osName); } } return instance[0]; } } /** * Clears the cached OS instance, if any. */ static void clearInstance() { synchronized (instance) { instance[0] = null; } } static void logExecution(Logger log, File directory, String command) { if (log == null) { return; } String location = ""; if (directory != null) { location = directory.getAbsolutePath(); location = Files.normalizePath(location); location = " in " + location; } log.debug("executing \"" + command + "\"" + location); } // Public ---------------------------------------------------------------------------------------------------------- /** * @see OSConfiguration */ OSConfiguration getConfiguration(); /** * "Linux" (OS.Linux), "MacOS" (OS.MacOS), "Windows" (OS.Windows). * * @see OS#Linux * @see OS#MacOS * @see OS#Windows */ String getName(); }
27.957576
120
0.537828
3fa2e64a696d33247e17411eac6c908a6c1a1194
5,768
package com.nd.shapedexamproj.util; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.nd.shapedexamproj.App; import com.nd.shapedexamproj.R; import com.nd.shapedexamproj.view.numberpicker.NumericWheelAdapter; import com.nd.shapedexamproj.view.numberpicker.OnWheelScrollListener; import com.nd.shapedexamproj.view.numberpicker.WheelView; import com.tming.common.net.TmingHttp; import com.tming.common.net.TmingHttp.RequestCallback; import com.tming.common.util.Log; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * 送花对话框 * @author zll * create in 2014-4-8 */ public class FlowerDialog { private Context context ; private Button send_9_flower_btn ,send_99_flower_btn,send_all_flower_btn; private int rest_flowers ; //剩余的鲜花数 private int light_black ; private Drawable send_flower_btn_disabled = null; public FlowerDialog(Context context ){ this.context = context ; light_black = context.getResources().getColor(R.color.light_black); send_flower_btn_disabled = context.getResources().getDrawable(R.drawable.send_flower_btn_disabled); } /** * 打开送鲜花的对话框 */ int current_num ; Dialog dialog = null; public void showSendFlowerDialog(final int rest_flower_num){ View send_flower_view = LayoutInflater.from(App.getAppContext()).inflate(R.layout.send_flower_view, null); final WheelView wheelView = (WheelView) send_flower_view.findViewById(R.id.send_flower_numpicker); send_9_flower_btn = (Button) send_flower_view.findViewById(R.id.send_9_flower_btn); if(rest_flower_num < 9){ send_9_flower_btn.setClickable(false); send_9_flower_btn.setBackgroundDrawable(send_flower_btn_disabled); send_9_flower_btn.setTextColor(light_black); } send_99_flower_btn = (Button) send_flower_view.findViewById(R.id.send_99_flower_btn); if(rest_flower_num < 99){ send_99_flower_btn.setClickable(false); send_99_flower_btn.setBackgroundDrawable(send_flower_btn_disabled); send_99_flower_btn.setTextColor(light_black); } send_all_flower_btn = (Button) send_flower_view.findViewById(R.id.send_all_flower_btn); if(rest_flower_num == 0){ send_all_flower_btn.setClickable(false); send_all_flower_btn.setBackgroundDrawable(send_flower_btn_disabled); send_all_flower_btn.setTextColor(light_black); } TextView send_flower_rest_tv = (TextView) send_flower_view.findViewById(R.id.send_flower_rest_tv); send_flower_rest_tv.setText("剩余" + rest_flower_num + "朵花"); Button negative_button = (Button) send_flower_view.findViewById(R.id.negative_button); Button positive_button = (Button) send_flower_view.findViewById(R.id.positive_button); wheelView.setAdapter(new NumericWheelAdapter(0, rest_flower_num, "%02d")); /*wheelView.setLabel("mins");*/ //设置选中项上的文字 wheelView.setCyclic(true); /*wheelView.setCurrentItem(1);*/ OnWheelScrollListener scrollListener = new OnWheelScrollListener() { @Override public void onScrollingStarted(WheelView wheel) { } @Override public void onScrollingFinished(WheelView wheel) { current_num = wheelView.getCurrentItem(); Log.e("花", current_num+"朵"); } }; wheelView.addScrollingListener(scrollListener); Builder builder = new Builder(context).setView(send_flower_view); send_9_flower_btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(rest_flower_num >= 9){ current_num = 9; wheelView.setCurrentItem(current_num,true); } } }); send_99_flower_btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(rest_flower_num >= 99){ current_num = 99; wheelView.setCurrentItem(current_num,true); } } }); send_all_flower_btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { current_num = rest_flower_num ; wheelView.setCurrentItem(current_num,true); } }); negative_button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(dialog != null){ dialog .dismiss(); } } }); positive_button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //送花 if(current_num != 0){ sendFlower(current_num,dialog); } else { Toast.makeText(context, "您的花已经送完了", Toast.LENGTH_SHORT).show(); } } }); dialog = builder.show(); } /** * 送花 */ private void sendFlower(int flowercount,final Dialog dialog){ String url = Constants.SEND_FLOWER; Map<String,Object> map = new HashMap<String,Object>(); map.put("userid", App.getUserId()); map.put("receiverid", 22); //TODO 用假数据 map.put("source", 0); //直接送:0,动态里送:1 map.put("flowercount", flowercount); TmingHttp.asyncRequest(url, map, new RequestCallback<String>() { @Override public String onReqestSuccess(String respones) throws Exception { JSONObject jobj = new JSONObject(); return jobj.getString("flag"); } @Override public void success(String respones) { if(respones.equals("1")){ Toast.makeText(context, "送花成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "参数错误", Toast.LENGTH_SHORT).show(); } if(dialog != null){ dialog.dismiss(); } } @Override public void exception(Exception exception) { Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show(); } }); } }
28.84
108
0.734917
e55d1794d6817abf0ef883d9fb12c7638c3e9b05
2,019
/* * Copyright (c) 2021 gematik GmbH * * 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 de.gematik.rezeps.dataexchange; import java.io.Serializable; import java.util.Arrays; import java.util.Objects; public class TaskCloseData implements Serializable { private static final long serialVersionUID = 4309535994521204782L; private int statusCode; private byte[] signature; private SignedReceipt signedReceipt; public TaskCloseData(int statusCode, byte[] signature) { this.statusCode = statusCode; this.signature = signature; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public byte[] getSignature() { return signature; } public void setSignature(byte[] signature) { this.signature = signature; } public SignedReceipt getSignedReceipt() { return signedReceipt; } public void setSignedPrescription(final SignedReceipt signedReceipt) { this.signedReceipt = signedReceipt; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TaskCloseData that = (TaskCloseData) o; return statusCode == that.statusCode && Arrays.equals(signature, that.signature); } @Override public int hashCode() { int result = Objects.hash(statusCode); result = 31 * result + Arrays.hashCode(signature); return result; } }
25.884615
85
0.708767
786098343b62022af363563bd5a69d79e270ab2a
5,910
/* * 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.jackrabbit.oak.plugins.observation.filter; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.MISSING_NODE; import com.google.common.base.Predicate; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * An universal {@code Filter} implementation, which can be parametrised by * a {@link Selector} and a {@code Predicate}. The selector maps a call back * on this filter to a {@code NodeState}. That node state is in turn passed * to the predicate for determining whether to include or to exclude the * respective event. */ public class UniversalFilter implements EventFilter { private final NodeState beforeState; private final NodeState afterState; private final Selector selector; private final Predicate<NodeState> predicate; /** * Create a new instance of an universal filter rooted at the passed trees. * * @param before before state * @param after after state * @param selector selector for selecting the tree to match the predicate against * @param predicate predicate for determining whether to include or to exclude an event */ public UniversalFilter( @NotNull NodeState before, @NotNull NodeState after, @NotNull Selector selector, @NotNull Predicate<NodeState> predicate) { this.beforeState = checkNotNull(before); this.afterState = checkNotNull(after); this.predicate = checkNotNull(predicate); this.selector = checkNotNull(selector); } /** * A selector instance maps call backs on {@code Filters} to {@code NodeState} instances, * which should be used for determining inclusion or exclusion of the associated event. */ public interface Selector { /** * Map a property event. * @param filter filter instance on which respective call back occurred. * @param before before state or {@code null} for * {@link EventFilter#includeAdd(PropertyState)} * @param after after state or {@code null} for * {@link EventFilter#includeDelete(PropertyState)} * @return a {@code NodeState} instance for basing the filtering criterion (predicate) upon */ @NotNull NodeState select(@NotNull UniversalFilter filter, @Nullable PropertyState before, @Nullable PropertyState after); /** * Map a node event. * @param filter filter instance on which respective call back occurred. * @param name name of the child node state * @param before before state or {@code null} for * {@link EventFilter#includeAdd(String, NodeState)} * @param after after state or {@code null} for * {@link EventFilter#includeDelete(String, NodeState)} * @return a NodeState instance for basing the filtering criterion (predicate) upon */ @NotNull NodeState select(@NotNull UniversalFilter filter, @NotNull String name, @NotNull NodeState before, @NotNull NodeState after); } /** * @return before state for this filter */ @NotNull public NodeState getBeforeState() { return beforeState; } /** * @return after state for this filter */ @NotNull public NodeState getAfterState() { return afterState; } @Override public boolean includeAdd(PropertyState after) { return predicate.apply(selector.select(this, null, after)); } @Override public boolean includeChange(PropertyState before, PropertyState after) { return predicate.apply(selector.select(this, before, after)); } @Override public boolean includeDelete(PropertyState before) { return predicate.apply(selector.select(this, before, null)); } @Override public boolean includeAdd(String name, NodeState after) { return predicate.apply(selector.select(this, name, MISSING_NODE, after)); } @Override public boolean includeDelete(String name, NodeState before) { return predicate.apply(selector.select(this, name, before, MISSING_NODE)); } @Override public boolean includeMove(String sourcePath, String name, NodeState moved) { return predicate.apply(selector.select(this, name, MISSING_NODE, moved)); } @Override public boolean includeReorder(String destName, String name, NodeState reordered) { return predicate.apply(selector.select(this, name, MISSING_NODE, reordered)); } @Override public EventFilter create(String name, NodeState before, NodeState after) { return new UniversalFilter( beforeState.getChildNode(name), afterState.getChildNode(name), selector, predicate); } }
38.376623
99
0.681557
640aac8b01f02425b71cd8902d47f447eaadebdc
1,030
public class EditDIstance { int min(int a, int b, int c) { return Math.min(a, Math.min(b, c)); } public int minDistance(String word1, String word2) { if (word1.equals("")) { return word2.length(); } else if (word2.equals("")) { return word1.length(); } int [][] distances = new int[word1.length() + 1][word2.length() + 1]; for (int i = 0; i < word1.length(); i++) { distances[i][0] = i; } for (int j = 0; j <= word2.length(); j++) { distances[0][j] = j; } for (int i = 0; i < word1.length(); i++) { for (int j = 0; j < word2.length(); j++) { int a = i + 1, b = j + 1; int min = min(distances[a - 1][b], distances[a][b - 1], distances[a - 1][b - 1]); distances[a][b] = word1.charAt(i) != word2.charAt(j) ? min + 1 : distances[a - 1][b - 1]; } } return distances[word1.length()][word2.length()]; } }
36.785714
105
0.450485
a50c2a2ed8e512c7978a8f89b43e47e84b269790
2,341
/* * * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.amazon.opendistroforelasticsearch.sql.elasticsearch.setting; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import com.amazon.opendistroforelasticsearch.sql.common.setting.Settings; import java.util.List; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.unit.ByteSizeValue; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class ElasticsearchSettingsTest { @Mock private ClusterSettings clusterSettings; @Test void getSettingValue() { ElasticsearchSettings settings = new ElasticsearchSettings(clusterSettings); ByteSizeValue sizeValue = settings.getSettingValue(Settings.Key.PPL_QUERY_MEMORY_LIMIT); assertNotNull(sizeValue); } @Test void pluginSettings() { List<Setting<?>> settings = ElasticsearchSettings.pluginSettings(); assertFalse(settings.isEmpty()); } @Test void update() { ElasticsearchSettings settings = new ElasticsearchSettings(clusterSettings); ByteSizeValue oldValue = settings.getSettingValue(Settings.Key.PPL_QUERY_MEMORY_LIMIT); ElasticsearchSettings.Updater updater = settings.new Updater(Settings.Key.PPL_QUERY_MEMORY_LIMIT); updater.accept(new ByteSizeValue(0L)); ByteSizeValue newValue = settings.getSettingValue(Settings.Key.PPL_QUERY_MEMORY_LIMIT); assertNotEquals(newValue.getBytes(), oldValue.getBytes()); } }
34.940299
92
0.773174
95e271772988c46131611bd3877883c122b9d1ff
121
package org.unirail.AdHoc; //Make AdHoc generate code for a particular device in Rust language. public interface InRS {}
30.25
68
0.793388
54ebafb24133a65aba243e90b34243c71863120e
581
package com.mark.login.service; import com.mark.model.common.dtos.ResponseResult; import com.mark.model.user.pojos.ApUser; /** * @Description : 用户登录验证 * @Author : Markburt * @CreateDate : 2020/2/22$ 下午 07:39$ * @UpdateUser : Markburt * @UpdateDate : 2020/2/22$ 下午 07:39$ * @UpdateRemark : Project Build * @Version : 1.0 */ public interface ApUserLoginService { /** *根据用户名和密码登录验证 * @param user * @return */ ResponseResult loginAuth(ApUser user); /** * 根据用户名和密码登录验证 V2 */ ResponseResult loginAuthV2(ApUser user); }
18.741935
49
0.638554
d3255c4fdf97d9a2c296f6f1ade2385fb8d9e49f
1,734
package com.example.sample_p; import android.os.AsyncTask; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Properties; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; /** * SSH接続用クラス */ public class SSHConnector extends AsyncTask<Void, Void, String> { private Session session; private ChannelExec channel; MainActivity main_ = null; String ret = null; SSHConnector(MainActivity mainActivity){main_ = mainActivity;} @Override protected String doInBackground(Void... params) { try { JSch jsch = new JSch(); session = jsch.getSession(main_.strUser, main_.strHost, main_.nPort); session.setPassword(main_.strPass); Properties prop = new Properties(); prop.put("StrictHostKeyChecking", "no"); session.setConfig(prop); session.connect(); // コマンド送信 channel = (ChannelExec)session.openChannel("exec"); channel.setCommand(main_.strCommand); channel.setErrStream(System.err); channel.connect(); // 受信処理 BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } channel.disconnect(); session.disconnect(); int returnCode = channel.getExitStatus(); // コマンドの戻り値を取得する System.out.println(returnCode); ret = "OK!"; } catch (JSchException e) { e.printStackTrace(); ret = "error!"; } catch (Exception e) { e.printStackTrace(); ret = "error!"; } return ret; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // doInBackground後処理 main_.showToast(result); } }
26.272727
95
0.71684
07daf2cbf96d8642571a354a17c5b5579c1afbf9
498
package com.taotao.cloud.hadoop.mr.secondarysort; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapreduce.Partitioner; public class ItemIdPartitioner extends Partitioner<OrderBean, NullWritable> { @Override public int getPartition(OrderBean bean, NullWritable value, int numReduceTasks) { //相同id的订单bean,会发往相同的partition //而且,产生的分区数,是会跟用户设置的reduce task数保持一致 return (bean.getItemid().hashCode() & Integer.MAX_VALUE) % numReduceTasks; } }
27.666667
85
0.753012
a90da986414cfdb1e5a6d31b0934ecde0f88f4f2
470
package com.softicar.platform.emf.data.table.export.node; import com.softicar.platform.dom.node.IDomNode; import com.softicar.platform.emf.data.table.export.popup.TableExportPopupButton; /** * Implemented by {@link IDomNode}s whose contents shall completely be ignored * during table exports triggered via {@link TableExportPopupButton}. * * @author Alexander Schmidt */ public interface ITableExportEmptyNode extends ITableExportManipulatedNode { // nothing }
29.375
80
0.8
7f01bb6601a28eaf3cb36b1e7322580b8c22598c
1,751
/* * 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 io.github.moosbusch.audiothekar.filter; import java.io.IOException; import java.util.Collections; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientResponseContext; import javax.ws.rs.client.ClientResponseFilter; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * * @author komano */ @Provider public class ClientFilter implements ClientResponseFilter { private static final Logger LOGGER = LogManager.getLogger(ClientFilter.class); @Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { final MultivaluedMap<String, Object> requestHeaders = requestContext.getHeaders(); final MultivaluedMap<String, String> responseHeaders = responseContext.getHeaders(); final String contentType = responseContext.getHeaderString(HttpHeaders.CONTENT_TYPE); if (contentType != null) { if (contentType.startsWith(MediaType.TEXT_HTML)) { requestContext.abortWith(Response.status(Response.Status.NO_CONTENT).entity(null).build()); } if (contentType.toLowerCase().contains("audio/mpeg")) { responseContext.getHeaders().put(HttpHeaders.CONTENT_TYPE, Collections.singletonList("application/octet-stream")); } } } }
36.479167
130
0.743004
14657efaab830a2b0aa25eced054844d43848d0b
8,731
/** * Copyright 2010 - 2019 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.tree; import jetbrains.exodus.TestUtil; import jetbrains.exodus.core.dataStructures.hash.IntHashMap; import org.junit.Test; import java.io.IOException; import java.util.Map; import static org.junit.Assert.assertEquals; public abstract class TreeDeleteTest extends TreeBaseTest { @Test public void testDeleteNoDuplicates() throws IOException { tm = createMutableTree(false, 1); tm.put(kv(1, "1")); assertEquals(1, tm.getSize()); assertEquals(value("1"), tm.get(key(1))); assertEquals(false, tm.delete(key(2))); assertEquals(true, tm.delete(key(1))); assertEquals(0, tm.getSize()); assertEquals(null, tm.get(key(1))); long a = saveTree(); reopen(); t = openTree(a, false); assertEquals(0, tm.getSize()); assertEquals(null, tm.get(key(1))); } @Test public void testDeleteNoDuplicates2() throws IOException { tm = createMutableTree(false, 1); tm.put(key("1"), value("1")); tm.put(key("11"), value("11")); tm.put(key("111"), value("111")); long a = saveTree(); reopen(); t = openTree(a, false); tm = t.getMutableCopy(); assertEquals(3, tm.getSize()); assertEquals(value("1"), tm.get(key("1"))); assertEquals(value("11"), tm.get(key("11"))); assertEquals(value("111"), tm.get(key("111"))); assertEquals(false, tm.delete(key(2))); assertEquals(true, tm.delete(key("111"))); assertEquals(true, tm.delete(key("11"))); assertEquals(1, tm.getSize()); assertEquals(null, tm.get(key("11"))); a = saveTree(); reopen(); t = openTree(a, false); assertEquals(1, tm.getSize()); assertEquals(null, tm.get(key("111"))); assertEquals(null, tm.get(key("11"))); valueEquals("1", tm.get(key("1"))); } /*@Test public void testDeleteNoDuplicates2() throws IOException { tm = createMutableTree(false); getTreeMutable().put(kv(1, "1")); getTreeMutable().put(kv(2, "2")); getTreeMutable().put(kv(3, "3")); getTreeMutable().put(kv(4, "4")); getTreeMutable().put(kv(5, "5")); assertEquals(5, tm.getSize()); long a = saveTree(); tm = openTree(a, false).getMutableCopy(); System.out.println("Orig-----------------------"); dump(getTreeMutable()); assertEquals(5, tm.getSize()); tm.delete(key(1)); tm.delete(key(2)); tm.delete(key(3)); assertEquals(2, tm.getSize()); System.out.println("After delete-----------------------"); dump(getTreeMutable()); writeItems(tm); a = saveTree(); assertEquals(2, tm.getSize()); System.out.println("After delete and save-----------------------"); dump(getTreeMutable()); writeItems(tm); tm = openTree(a, false).getMutableCopy(); assertEquals(2, tm.getSize()); System.out.println("After delete, save and reopen-----------------------"); dump(getTreeMutable()); writeItems(tm); tm.delete(key(4)); System.out.println("After delete 4-----------------------"); dump(getTreeMutable()); writeItems(tm); tm.delete(key(5)); System.out.println("After delete 5-----------------------"); dump(getTreeMutable()); writeItems(tm); assertEquals(0, tm.getSize()); a = saveTree(); t = openTree(a, false); assertTrue(t.isEmpty()); assertEquals(0, t.getSize()); assertFalse(t.openCursor().getNext()); } */ @Test public void testDeleteNotExistingKey() throws IOException { tm = createMutableTree(false, 1); getTreeMutable().put(kv(1, "1")); assertEquals(1, tm.getSize()); assertEquals(value("1"), tm.get(key(1))); assertEquals(false, tm.delete(key(-1))); assertEquals(false, tm.delete(key(-2))); assertEquals(false, tm.delete(key(-3))); assertEquals(false, tm.delete(key(2))); assertEquals(true, tm.delete(key(1))); assertEquals(false, tm.delete(key(1))); assertEquals(false, tm.delete(key(-1))); assertEquals(false, tm.delete(key(-2))); assertEquals(0, tm.getSize()); assertEquals(null, tm.get(key(1))); long a = saveTree(); reopen(); t = openTree(a, false); assertEquals(0, t.getSize()); assertEquals(null, t.get(key(1))); assertEquals(null, t.get(key(-1))); assertEquals(null, t.get(key(2))); } @Test public void testDeleteNotExistingKey2() throws IOException { tm = createMutableTree(false, 1); getTreeMutable().put(kv(1, "1")); getTreeMutable().put(kv(11, "1")); getTreeMutable().put(kv(111, "1")); assertEquals(3, tm.getSize()); assertEquals(value("1"), tm.get(key(1))); assertEquals(false, tm.delete(key(-1))); assertEquals(false, tm.delete(key(-2))); assertEquals(false, tm.delete(key(-3))); assertEquals(false, tm.delete(key(2))); assertEquals(true, tm.delete(key(1))); assertEquals(false, tm.delete(key(1))); assertEquals(true, tm.delete(key(11))); assertEquals(false, tm.delete(key(11))); assertEquals(true, tm.delete(key(111))); assertEquals(false, tm.delete(key(111))); assertEquals(false, tm.delete(key(-1))); assertEquals(false, tm.delete(key(-2))); assertEquals(0, tm.getSize()); assertEquals(null, tm.get(key(1))); long a = saveTree(); reopen(); t = openTree(a, false); assertEquals(0, t.getSize()); assertEquals(null, t.get(key(1))); assertEquals(null, t.get(key(-1))); assertEquals(null, t.get(key(2))); } @Test public void testPutDeleteRandomWithoutDuplicates() throws Throwable { tm = createMutableTree(false, 1); final IntHashMap<String> map = new IntHashMap<>(); final int count = 30000; TestUtil.time("Put took ", new Runnable() { @Override public void run() { for (int i = 0; i < count; ++i) { final int key = Math.abs(RANDOM.nextInt()); final String value = Integer.toString(i); tm.put(key(Integer.toString(key)), value(value)); map.put(key, value); } } }); long address = saveTree(); reopen(); t = openTree(address, false); tm = t.getMutableCopy(); TestUtil.time("Delete took ", new Runnable() { @Override public void run() { for (int i = 0; i < count; ++i) { final int key = Math.abs(RANDOM.nextInt()); assertEquals(map.remove(key) != null, tm.delete(key(Integer.toString(key)))); } } }); address = saveTree(); reopen(); t = openTree(address, false); assertEquals(map.size(), t.getSize()); TestUtil.time("Get took ", new Runnable() { @Override public void run() { for (final Map.Entry<Integer, String> entry : map.entrySet()) { final Integer key = entry.getKey(); final String value = entry.getValue(); valueEquals(value, t.get(key(Integer.toString(key)))); } } }); tm = t.getMutableCopy(); TestUtil.time("Missing get took ", new Runnable() { @Override public void run() { for (int i = 0; i < count; ++i) { final int key = Math.abs(RANDOM.nextInt()); if (!map.containsKey(key)) { assertEquals(false, tm.delete(key(Integer.toString(key)))); } } } }); } }
31.981685
97
0.54232
772e3ba616ea681782b85c1e7f5df651c95b8e5c
1,120
package ru.test.cucumber; import app.Application; import io.cucumber.java8.En; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; import model.Product; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; @RunWith(Cucumber.class) @CucumberOptions(plugin = {"pretty"}) public class AddingAndRemoveItemFromCart extends CucumberTestBase implements En { private Product.Builder builder = Product.newEntity(); private Product product; public AddingAndRemoveItemFromCart() { When("user added the 3 product with size {string} to the cart", (String size) -> { product = builder.withSize(size).build(); for (int i = 0; i < 3; i++) { app.addProductToCart(product); } }); Then("quantity increased by 3 in the cart", () -> assertEquals(3, app.getQuantityInCartProductPage())); When("the user went to the cart and deleted all products from it", () -> app.removeProductFromCart()); Then("the cart is empty", () -> assertEquals(0, app.getQuantityInCartCartPage())); } }
36.129032
111
0.683929
8e2db438517dd954e6488711fdbba24d36a4c13a
7,477
package itb2.gui; import java.awt.Cursor; import java.awt.Desktop; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.swing.Box; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import itb2.engine.Controller; import itb2.engine.io.FilterIO; import itb2.engine.io.ImageIO; import itb2.image.BinaryImage; import itb2.image.DrawableImage; import itb2.image.GrayscaleImage; import itb2.image.GroupedImage; import itb2.image.HsiImage; import itb2.image.HsvImage; import itb2.image.Image; import itb2.image.ImageConverter; import itb2.image.ImageFactory; import itb2.image.RgbImage; public class EditorMenuBar extends JMenuBar { private static final long serialVersionUID = -217686192194157463L; private static final String TYPE_FILTER = "filter", TYPE_IMAGE = "image"; private final EditorGui gui; private final JMenu imageMenu, filterMenu, converterMenu; public EditorMenuBar(EditorGui gui) { this.gui = gui; // Build image menu imageMenu = new JMenu("Last Images"); add(imageMenu); // Build filter menu filterMenu = new JMenu("Last Filters"); add(filterMenu); // Add menu items and register listener synchronized (ImageIO.getLastImages()) { ImageIO.getLastImages().addListener(new Listener(imageMenu, TYPE_IMAGE)); for(File file : ImageIO.getLastImages()) imageMenu.add(new Item(file, TYPE_IMAGE)); } synchronized (FilterIO.getLastFilters()) { FilterIO.getLastFilters().addListener(new Listener(filterMenu, TYPE_FILTER)); for(File file : FilterIO.getLastFilters()) filterMenu.add(new Item(file, TYPE_FILTER)); } // Build converter menu converterMenu = new JMenu("Convert Image"); converterMenu.add(getConverter("RGB", RgbImage.class)); converterMenu.add(getConverter("HSI", HsiImage.class)); converterMenu.add(getConverter("HSV", HsvImage.class)); converterMenu.addSeparator(); converterMenu.add(getConverter("Grayscale", GrayscaleImage.class)); converterMenu.add(getConverter("Binary", BinaryImage.class)); converterMenu.addSeparator(); converterMenu.add(getConverter("Drawable", DrawableImage.class)); converterMenu.add(getConverter("Grouped", GroupedImage.class)); converterMenu.addSeparator(); JMenu converterByteMenu = new JMenu("Byte Precision"); converterByteMenu.add(getConverter("RGB", ImageFactory.bytePrecision().rgb())); converterByteMenu.add(getConverter("HSI", ImageFactory.bytePrecision().hsi())); converterByteMenu.add(getConverter("HSV", ImageFactory.bytePrecision().hsv())); converterByteMenu.addSeparator(); converterByteMenu.add(getConverter("Grayscale", ImageFactory.bytePrecision().gray())); converterByteMenu.add(getConverter("Binary", ImageFactory.bytePrecision().binary())); converterByteMenu.addSeparator(); converterByteMenu.add(getConverter("Drawable", ImageFactory.bytePrecision().drawable())); converterByteMenu.add(getConverter("Grouped", ImageFactory.bytePrecision().group())); JMenu converterDoubleMenu = new JMenu("Double Precision"); converterDoubleMenu.add(getConverter("RGB", ImageFactory.doublePrecision().rgb())); converterDoubleMenu.add(getConverter("HSI", ImageFactory.doublePrecision().hsi())); converterDoubleMenu.add(getConverter("HSV", ImageFactory.doublePrecision().hsv())); converterDoubleMenu.addSeparator(); converterDoubleMenu.add(getConverter("Grayscale", ImageFactory.doublePrecision().gray())); converterDoubleMenu.addSeparator(); converterDoubleMenu.add(getConverter("Grouped", ImageFactory.doublePrecision().group())); converterMenu.add(converterByteMenu); converterMenu.add(converterDoubleMenu); add(converterMenu); // Add version JLabel version = createVersionLabel(); if(version != null) { add(Box.createHorizontalGlue()); add(version); add(Box.createHorizontalStrut(5)); } } private JMenuItem getConverter(String text, Class<? extends Image> destination) { JMenuItem item = new JMenuItem(text); item.addActionListener(e -> { try { List<Image> input = gui.getImageList().getSelectedImages(); List<Image> output = new ArrayList<>(input.size()); for(Image image : input) output.add( ImageConverter.convert(image, destination) ); Controller.getImageManager().getImageList().addAll(output); } catch(Exception ex) { Controller.getCommunicationManager().error("Error while converting images:\n%s", ex.getMessage()); } }); return item; } private JLabel createVersionLabel() { try(InputStream stream = getClass().getResourceAsStream("/info.txt")) { Properties props = new Properties(); props.load(stream); String version = props.getProperty("version"); if(version == null || version.isEmpty()) return null; JLabel label = new JLabel(version); String url = props.getProperty("url"); if(url != null && !url.isEmpty()) { label.setToolTipText(url); label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); label.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { // Ignore double click if(e.getClickCount() > 1) return; // If desktop is supported open GitHub project if(Desktop.isDesktopSupported()) try { Desktop.getDesktop().browse(new URI(url)); return; } catch(Exception ex) { // Ignore } // Otherwise print URL to log Controller.getCommunicationManager().info(url); } }); } return label; } catch(Exception e) { // Don't display version. It's not mandatory. return null; } } private class Listener implements ListDataListener { final JMenu menu; final String type; Listener(JMenu menu, String type) { this.menu = menu; this.type = type; } @Override public void contentsChanged(ListDataEvent e) { List<?> list = (List<?>)e.getSource(); for(int i = e.getIndex1(); i >= e.getIndex0(); i--) { File file = (File)list.get(i); menu.remove(i); menu.insert(new Item(file, type), i); } } @Override public void intervalAdded(ListDataEvent e) { List<?> list = (List<?>)e.getSource(); for(int i = e.getIndex0(); i <= e.getIndex1(); i++) { File file = (File)list.get(i); menu.insert(new Item(file, type), i); } } @Override public void intervalRemoved(ListDataEvent e) { for(int i = e.getIndex1(); i >= e.getIndex0(); i--) menu.remove(i); } } private class Item extends JMenuItem { private static final long serialVersionUID = 8849058756010952698L; public Item(File file, String type) { super(file.getPath()); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { if(type == TYPE_FILTER) Controller.getFilterManager().loadFilter(file); else if(type == TYPE_IMAGE) Controller.getImageManager().loadImage(file); } catch(Exception ex) { Controller.getCommunicationManager().error("Could not open %s: '%s'", type, file.getName()); } } }); } } }
31.024896
102
0.70991
e2684e2f27a5af5f43ab36fc3fc64fec4d0066bb
4,710
/* * 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.servicemix.camel.nmr; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.CamelSpringTestSupport; import org.apache.camel.CamelContext; import org.apache.cxf.Bus; import org.apache.cxf.BusFactory; import org.apache.cxf.bus.CXFBusFactory; import org.apache.cxf.endpoint.ServerImpl; import org.apache.cxf.frontend.ClientFactoryBean; import org.apache.cxf.frontend.ClientProxyFactoryBean; import org.apache.cxf.frontend.ServerFactoryBean; import org.springframework.beans.BeansException; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SmxToCxfTest extends CamelSpringTestSupport { private static final String BUS_BEAN_NAME = "Bus"; protected static final String ROUTER_ADDRESS = "http://localhost:19000/router"; protected static final String SERVICE_ADDRESS = "local://smx/helloworld"; protected static final String SERVICE_CLASS = "serviceClass=org.apache.servicemix.camel.nmr.HelloService"; private String routerEndpointURI = String.format("cxf://%s?%s&dataFormat=POJO&setDefaultBus=true&bus=#%s", ROUTER_ADDRESS, SERVICE_CLASS, BUS_BEAN_NAME); private String serviceEndpointURI = String.format("cxf://%s?%s&dataFormat=POJO&setDefaultBus=true&bus=#%s", SERVICE_ADDRESS, SERVICE_CLASS, BUS_BEAN_NAME); private ServerImpl server; private Bus bus; @Override protected void setUp() throws Exception { bus = CXFBusFactory.getDefaultBus(); super.setUp(); startService(); } protected ClassPathXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/servicemix/camel/spring/DummyBean.xml") { @Override public <T> T getBean(String name, Class<T> requiredType) throws BeansException { if (BUS_BEAN_NAME.equals(name)) { return requiredType.cast(bus); } return super.getBean(name, requiredType); //To change body of overridden methods use File | Settings | File Templates. } }; } protected void assertValidContext(CamelContext context) { assertNotNull("No context found!", context); } protected void startService() { //start a service ServerFactoryBean svrBean = new ServerFactoryBean(); svrBean.setAddress(SERVICE_ADDRESS); svrBean.setServiceClass(HelloService.class); svrBean.setServiceBean(new HelloServiceImpl()); svrBean.setBus(CXFBusFactory.getDefaultBus()); server = (ServerImpl)svrBean.create(); server.start(); } @Override protected void tearDown() throws Exception { if (server != null) { server.stop(); } super.tearDown(); } protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(routerEndpointURI).to("smx:testEndpoint");// like what do in binding component from("smx:testEndpoint").to(serviceEndpointURI);// like what do in se } }; } public void testInvokingServiceFromCXFClient() throws Exception { Bus bus = BusFactory.getDefaultBus(); ClientProxyFactoryBean proxyFactory = new ClientProxyFactoryBean(); ClientFactoryBean clientBean = proxyFactory.getClientFactoryBean(); clientBean.setAddress(ROUTER_ADDRESS); clientBean.setServiceClass(HelloService.class); clientBean.setBus(bus); HelloService client = (HelloService) proxyFactory.create(); String result = client.echo("hello world"); assertEquals("we should get the right answer from router", "hello world echo", result); } }
38.92562
137
0.687473
e865b2ecbbbbba7704a3460727bd3b367b798b2f
5,667
/* The following passage applies to all software and text files in this distribution, including this one: Copyright (c) 2002 Networks Associates Technology, Inc. under sponsorship of the Defense Advanced Research Projects Agency (DARPA). All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: -> Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -> Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -> Neither the name of the Network Associates nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.jhuapl.idmef; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; /** * <pre> * The Action class is used to describe any actions taken by the * analyzer in response to the event. Is is represented in the XML DTD * as follows: * * &lt!ENTITY % attvals.actioncat " * ( block-installed | notification-sent | taken-offline | * other ) * "&gt * &lt!ELEMENT Action (#PCDATA | EMPTY)* &gt * &lt!ATTLIST Action * category %attvals.actioncat; 'other' * &gt * * Action has one attribute: * * category * The type of action taken. The permitted values are shown below. * The default value is "other." * * Rank Keyword Description * ---- ------- ----------- * 0 BLOCK_INSTALLED A block of some sort was installed to * prevent an attack from reaching its * destination. The block could be a port * block, address block, etc., or disabling * a user account. * 1 NOTIFICATION_SENT A notification message of some sort was * sent out-of-band (via pager, e-mail, * etc.). Does not include the * transmission of this alert. * 2 TAKEN_OFFLINE A system, computer, or user was taken * offline, as when the computer is shut * OTHER Anything not in one of the above * categories. * * The element itself may be empty, or may contain a textual description * of the action, if the analyzer is able to provide additional details. * </pre> * <p>See also the <a href='http://search.ietf.org/internet-drafts/draft-ietf-idwg-idmef-xml-07.txt'>IETF IDMEF Draft Specification v0.7</a>. */ public class Action implements XMLSerializable { // xml element and attribute names private static final String ATTRIBUTE_CATEGORY = "category"; public static final String ELEMENT_NAME = "Action"; // action categories public static final String BLOCK_INSTALLED = "block-installed"; public static final String NOTIFICATION_SENT = "notification-sent"; public static final String TAKEN_OFFLINE = "taken-offline"; public static final String OTHER = "other"; public Action(){ this( null, null ); } public Action( String category, String description ){ if( category != null ){ m_category = category; } m_description = description; } public Action( Node node ){ NamedNodeMap attributes = node.getAttributes(); Node attribute = attributes.getNamedItem( ATTRIBUTE_CATEGORY ); if( attribute != null ){ m_category = attribute.getNodeValue(); } m_description = XMLUtils.getAssociatedString( node ); } public String getCategory(){ return m_category; } public void setCategory( String category ){ m_category = category; } public String getDescription(){ return m_description; } public void setDescription( String description ){ m_description = description; } public Node convertToXML( Document parent ){ Element actionNode = parent.createElement( ELEMENT_NAME ); if( m_category != null ){ actionNode.setAttribute( ATTRIBUTE_CATEGORY, m_category ); } if( m_description != null ){ actionNode.appendChild( parent.createTextNode( m_description ) ); } return actionNode; } // default to other private String m_category = "other"; private String m_description; }
38.55102
141
0.648138
482e0c4428cc503a85e6abe51ed5bd8ada11c014
1,674
package xyz.issc.daca.spec; import lombok.Data; import java.util.HashMap; @Data public class Routine { public static final int MODE_ROUTINE = 0; //when at routine mode, the procedure will not be retained public static final int MODE_FILTER = 1; //when at filter mode, the procedure will be retained until specific flows flush the procedure from the conn public static final int FILTER_NONE = 0; //not as filter public static final int FILTER_BLOCK = 1; //block all other procedures and filter procedures listed in the filtered public static final int FILTER_PASS = 2; //pass all other procedures and filter procedures listed in the filtered //not used public static final int RETAIN_MODE_NORMAL = 0; //creds removed when the procedure is finished public static final int RETAIN_MODE_ALWAYS = 1; //creds is retained throughout the connection public static final int RETAIN_MODE_REPLACE = 2; //creds is retained after the procedure lifetime until by other procedures declared or the same type String name; FlowGroupSpec[] flowGroupSpecs; //the first flow is the opening for the procedure int repeat; //-1 for infinite repeat boolean isAutostart = false; int retainMode = RETAIN_MODE_NORMAL; //filtering mode attributes int filterMode = FILTER_NONE; //filter is disabled by default String[] filtered; //routines to be filtered String[] recyclables; //routine that can recycle the retained creds after finishing //creds are initialized by the first flow containing the attrs, flows in the routine should meet the creds requirements HashMap<String, SvoSpec> creds; int qosWeight; }
40.829268
153
0.752091
3bc8f45024a600e6ef73b0da008cce82b5eb1ec4
978
package tic.model; public class GameEntity implements Entity{ protected int size; protected double xPos; protected double yPos; protected String imagePath; protected boolean naught; public GameEntity(double x, double y, double size, boolean naught){ this.xPos = x; this.yPos = y; this.size = (int) Math.round(size); if (naught){ this.imagePath = "slimeRb.png"; } else { this.imagePath = "fireball.png"; } this.naught = naught; } @Override public double getXPos() { return this.xPos; } @Override public double getYPos() { return this.yPos; } @Override public double getHeight() { return this.size; } @Override public double getWidth() { return this.size; } @Override public String getImagePath(){ return this.imagePath; } @Override public boolean getNaught() { return this.naught; } }
25.736842
72
0.599182
e12d38025916c03bfa7e8d1787a549ea757a18b4
1,207
package svenhjol.charm.module; import net.minecraft.util.DyeColor; import net.minecraft.util.Identifier; import svenhjol.charm.Charm; import svenhjol.charm.base.CharmModule; import svenhjol.charm.base.iface.Config; import svenhjol.charm.base.iface.Module; import svenhjol.charm.client.CoreClient; @Module(mod = Charm.MOD_ID, client = CoreClient.class, alwaysEnabled = true, description = "Core configuration values.") public class Core extends CharmModule { public static final Identifier MSG_SERVER_OPEN_INVENTORY = new Identifier(Charm.MOD_ID, "server_open_inventory"); @Config(name = "Debug mode", description = "If true, routes additional debug messages into the standard game log.") public static boolean debug = false; @Config(name = "Inventory button return", description = "If inventory crafting or inventory ender chest modules are enabled, pressing escape or inventory key returns you to the inventory rather than closing the window.") public static boolean inventoryButtonReturn = false; @Config(name = "Enchantment glint color", description = "Set the default glint color for all enchanted items.") public static String glintColor = DyeColor.PURPLE.getName(); }
50.291667
224
0.781276
fe378d27ffe16d3879fd70af8e9d19293b07b1ea
1,788
/* * Copyright 2017-2019 University of Hildesheim, Software Systems Engineering * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ssehub.kernel_haven.fe_analysis.fes; import net.ssehub.kernel_haven.SetUpException; import net.ssehub.kernel_haven.analysis.AnalysisComponent; import net.ssehub.kernel_haven.analysis.PipelineAnalysis; import net.ssehub.kernel_haven.config.Configuration; import net.ssehub.kernel_haven.fe_analysis.pcs.PcFinder; import net.ssehub.kernel_haven.util.null_checks.NonNull; /** * An analysis that finds feature effect formulas for variables. * * @author Adam */ public class FeatureEffectAnalysis extends PipelineAnalysis { /** * Creates a new {@link FeatureEffectAnalysis}. * * @param config The global configuration. */ public FeatureEffectAnalysis(@NonNull Configuration config) { super(config); } @Override protected @NonNull AnalysisComponent<?> createPipeline() throws SetUpException { return new NonBooleanFeExpander(config, new FeatureEffectFinder(config, new PcFinder(config, getCmComponent(), getBmComponent() ) ) ); } }
33.111111
84
0.696309
35907a444ff9c829a36c4546cee24a543a2b922a
2,397
/* * Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package simpleserver.config.xml; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import simpleserver.Player; public class PlayerStorage extends Storage { private Map<String, PlayerConfig> players = new HashMap<String, PlayerConfig>(); void add(PlayerConfig player) { players.put(player.name, player); } public void setGroup(String name, int group) { name = name.toLowerCase(); if (contains(name)) { players.get(name).group = group; } else { players.put(name, new PlayerConfig(name, group)); } } public void remove(String name) { name = name.toLowerCase(); if (contains(name)) { players.remove(name); } } public boolean contains(String name) { name = name.toLowerCase(); return players.containsKey(name); } public Integer group(String name) { name = name.toLowerCase(); return contains(name) ? players.get(name).group : null; } public Integer get(Player player) { return group(player.getName()); } public int count() { return players.size(); } @Override Iterator<PlayerConfig> iterator() { return players.values().iterator(); } @Override void add(XMLTag child) { add((PlayerConfig) child); } }
29.9625
82
0.71214
204b7a9e19fdb65bb47befdf47da727adc15f8ac
2,062
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.12.06 at 10:00:50 AM EST // package org.slc.sli.test.edfi.entities; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for PerformanceBaseType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="PerformanceBaseType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}token"> * &lt;enumeration value="Advanced"/> * &lt;enumeration value="Proficient"/> * &lt;enumeration value="Basic"/> * &lt;enumeration value="Below Basic"/> * &lt;enumeration value="Well Below Basic"/> * &lt;enumeration value="Pass"/> * &lt;enumeration value="Fail"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "PerformanceBaseType") @XmlEnum public enum PerformanceBaseType { @XmlEnumValue("Advanced") ADVANCED("Advanced"), @XmlEnumValue("Proficient") PROFICIENT("Proficient"), @XmlEnumValue("Basic") BASIC("Basic"), @XmlEnumValue("Below Basic") BELOW_BASIC("Below Basic"), @XmlEnumValue("Well Below Basic") WELL_BELOW_BASIC("Well Below Basic"), @XmlEnumValue("Pass") PASS("Pass"), @XmlEnumValue("Fail") FAIL("Fail"); private final String value; PerformanceBaseType(String v) { value = v; } public String value() { return value; } public static PerformanceBaseType fromValue(String v) { for (PerformanceBaseType c: PerformanceBaseType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
27.864865
124
0.654219
e448f8100dc5bd5b984c30cf991ca49a7a5f4c60
4,377
package oracle; import netP5.NetAddress; import oscP5.OscMessage; import oscP5.OscP5; import java.util.ArrayList; /** * Created by mrzl on 31.03.2016. */ public class OracleOsc{ OscP5 osc; NetAddress addr; Settings settings; private ArrayList< MarkovManager > markovs; public void setup() { settings = new Settings(); osc = new OscP5( this, 12000 ); addr = new NetAddress( "127.0.0.1", 12001 ); ArrayList< String > files = new ArrayList<>(); files.add( "admin_medosch.txt" ); files.add( "allan_watts.txt" ); files.add( "benjamin_bratton.txt" ); files.add( "cynthia_goodman.txt" ); files.add( "domenic_quaranta.txt" ); files.add( "drunvalo_melchizedek.txt" ); files.add( "errki_hutamo.txt" ); files.add( "espen_aarseth.txt" ); files.add( "friedrich_kittler.txt" ); files.add( "gene_youngblood.txt" ); files.add( "harold_cohen.txt" ); files.add( "jasia_reichardt.txt" ); files.add( "john_thackara.txt" ); files.add( "jussi_parikka.txt" ); files.add( "katherine_hayles.txt" ); files.add( "lev_manovich.txt" ); files.add( "lisaa_gitelman.txt" ); files.add( "lucien_sfez.txt" ); files.add( "marilyn_raffaele.txt" ); files.add( "michael_benedikt.txt" ); files.add( "minna_tarkka.txt" ); files.add( "naom_chomsky.txt" ); files.add( "neil_whitehead-michael_wesch.txt" ); files.add( "nick_bostrom.txt" ); files.add( "peter_weibel.txt" ); files.add( "pierre_levy.txt" ); files.add( "roman_verostko.txt" ); files.add( "sherry_turkle.txt" ); files.add( "sissel_marie_tonn.txt" ); files.add( "wark_mckenzie.txt" ); files.add( "wjt_mitchell.txt" ); markovs = new ArrayList<>(); /* for ( String author : files ) { MarkovManager m = new MarkovManager(); m.train( "text" + File.separator + "oraclev2" + File.separator + author, author, false ); markovs.add( m ); } */ for ( String author : files ) { MarkovManager m = new MarkovManager(); m.load( author ); markovs.add( m ); } } public String getContinued( String message ) throws Exception { String inputWordsString = message.trim(); while ( inputWordsString.startsWith( "." ) || inputWordsString.startsWith( "," ) || inputWordsString.startsWith( ";" ) || inputWordsString.startsWith( ":" ) || inputWordsString.startsWith( "-" ) || inputWordsString.startsWith( "_" ) ) { // removing some leading special characters inputWordsString = inputWordsString.substring( 1 ); } inputWordsString = inputWordsString.trim(); System.out.println( inputWordsString ); String result = null; ArrayList< Integer > markovDepths = new ArrayList<>(); ArrayList< String > answers = new ArrayList<>(); for ( MarkovManager m : markovs ) { int depth = m.getMarkovDepthOrder( m.strip( inputWordsString ) ); String answer = m.getAnswer( inputWordsString ); markovDepths.add( depth ); answers.add( answer ); } result = answers.get( Settings.maxIndex( markovDepths ) ); return result; } public void oscEvent( OscMessage msg ) { if( msg.addrPattern().equals( "/get" ) ){ String text = msg.get( 0 ).stringValue(); String threadId = msg.get( 1 ).stringValue(); String answer = null; System.out.println( "Request was: " + text ); try { answer = getContinued( text ); OscMessage oscReply = new OscMessage( "/answer" ); oscReply.add( answer ); oscReply.add( threadId ); osc.send( oscReply, addr ); System.out.println( "Sending reply: " + answer ); } catch ( Exception e ) { System.out.println( "No answer.. skipping." ); } } } public static void main( String[] args ) { OracleOsc oracle = new OracleOsc(); oracle.setup(); } }
33.669231
101
0.556317
118dad2454aa4538628670b541b92683b25c3f28
1,960
package com.github.wrdlbrnft.primitivecollections; import com.github.wrdlbrnft.primitivecollections.bytes.ByteArrayList; import com.github.wrdlbrnft.primitivecollections.bytes.ByteArraySet; import com.github.wrdlbrnft.primitivecollections.bytes.ByteList; import com.github.wrdlbrnft.primitivecollections.bytes.ByteSet; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; /** * Created with Android Studio<br> * User: Xaver<br> * Date: 09/12/2016 */ public class ByteCollectionTests { private static final byte[] UNIQUE_BYTES = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26}; @Test public void testByteArrayListAdd() { final ByteList collection = new ByteArrayList(); for (byte b : UNIQUE_BYTES) { collection.add(b); } Assert.assertThat(collection.toArray(), CoreMatchers.equalTo(UNIQUE_BYTES)); } @Test public void testByteArrayListContains() { final ByteList collection = new ByteArrayList(); for (byte b : UNIQUE_BYTES) { collection.add(b); } for (byte b : UNIQUE_BYTES) { Assert.assertThat(collection.contains(b), CoreMatchers.is(true)); } } @Test public void testByteArraySetAdd() { final ByteSet collection = new ByteArraySet(); for (byte b : UNIQUE_BYTES) { collection.add(b); } for (byte b : UNIQUE_BYTES) { collection.add(b); } Assert.assertThat(collection.toArray(), CoreMatchers.equalTo(UNIQUE_BYTES)); } @Test public void testByteArraySetContains() { final ByteSet collection = new ByteArraySet(); for (byte b : UNIQUE_BYTES) { collection.add(b); } for (byte b : UNIQUE_BYTES) { Assert.assertThat(collection.contains(b), CoreMatchers.is(true)); } } }
30.153846
153
0.638265
ba88805b13f3e28481ed27686ac888e69e0129fa
4,681
/* * Copyright 2017-2019 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 io.r2dbc.postgresql.message.frontend; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.r2dbc.postgresql.message.Format; import io.r2dbc.postgresql.util.Assert; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; import java.util.List; import java.util.Objects; import static io.r2dbc.postgresql.message.frontend.FrontendMessageUtils.writeByte; import static io.r2dbc.postgresql.message.frontend.FrontendMessageUtils.writeBytes; import static io.r2dbc.postgresql.message.frontend.FrontendMessageUtils.writeInt; import static io.r2dbc.postgresql.message.frontend.FrontendMessageUtils.writeLengthPlaceholder; import static io.r2dbc.postgresql.message.frontend.FrontendMessageUtils.writeShort; import static io.r2dbc.postgresql.message.frontend.FrontendMessageUtils.writeSize; /** * The FunctionCall message. */ public final class FunctionCall implements FrontendMessage { private static final int NULL = -1; private final List<Format> argumentFormats; private final List<ByteBuf> arguments; private final int functionId; private final Format resultFormat; /** * Creates a new message. * * @param argumentFormats the argument formats * @param arguments the value of the arguments, in the format indicated by the associated format * @param functionId the object ID of the function to call * @param resultFormat the format code for the function result * @throws IllegalArgumentException if {@code argumentFormats}, {@code arguments}, or {@code resultFormat} is {@code null} */ public FunctionCall(List<Format> argumentFormats, List<ByteBuf> arguments, int functionId, Format resultFormat) { this.argumentFormats = Assert.requireNonNull(argumentFormats, "argumentFormats must not be null"); this.arguments = Assert.requireNonNull(arguments, "arguments must not be null"); this.functionId = functionId; this.resultFormat = Assert.requireNonNull(resultFormat, "resultFormat must not be null"); } @Override public Publisher<ByteBuf> encode(ByteBufAllocator byteBufAllocator) { Assert.requireNonNull(byteBufAllocator, "byteBufAllocator must not be null"); return Mono.defer(() -> { ByteBuf out = byteBufAllocator.ioBuffer(); writeByte(out, 'F'); writeLengthPlaceholder(out); writeInt(out, this.functionId); writeShort(out, this.argumentFormats.size()); this.argumentFormats.forEach(format -> writeShort(out, format.getDiscriminator())); writeShort(out, this.arguments.size()); this.arguments.forEach(argument -> { if (argument == null) { writeInt(out, NULL); } else { writeInt(out, argument.readableBytes()); writeBytes(out, argument); } }); writeShort(out, this.resultFormat.getDiscriminator()); return Mono.just(writeSize(out)); }); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FunctionCall that = (FunctionCall) o; return this.functionId == that.functionId && Objects.equals(this.argumentFormats, that.argumentFormats) && Objects.equals(this.arguments, that.arguments) && this.resultFormat == that.resultFormat; } @Override public int hashCode() { return Objects.hash(this.argumentFormats, this.arguments, this.functionId, this.resultFormat); } @Override public String toString() { return "FunctionCall{" + "argumentFormats=" + this.argumentFormats + ", arguments=" + this.arguments + ", functionId=" + this.functionId + ", resultFormat=" + this.resultFormat + '}'; } }
36.570313
126
0.674215
19ae20c2ac1f0df6050c4de90160e7ae71582340
3,635
package com.example.artyom.monyceeper4u; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ EditText editText; Button button; TextView textView3; TextView textView5; TextView textView7; TextView textView9; TextView textView11; TextView textView13; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText) findViewById(R.id.editText); button = (Button) findViewById(R.id.button); textView3 = (TextView) findViewById(R.id.textView3); textView5 = (TextView) findViewById(R.id.textView5); textView7 = (TextView) findViewById(R.id.textView7); textView9 = (TextView) findViewById(R.id.textView9); textView11 = (TextView) findViewById(R.id.textView11); textView13 = (TextView) findViewById(R.id.textView13); button.setOnClickListener(this); } @Override public void onClick(View v) { double N = 0; double res = 0.62; double res2 = 0.07; double res3 = 0.11; double res4 = 0.04; double res5= 0.13; double res6 = 0.03; double settxt1 = 0; double settxt2 = 0; double settxt3 = 0; double settxt4 = 0; double settxt5 = 0; double settxt6 = 0; if (TextUtils.isEmpty(editText.getText().toString())) return; N = Double.parseDouble(editText.getText().toString()); switch (v.getId()) { case R.id.button: settxt1 = N*res; settxt2 = N*res2; settxt3 = N*res3; settxt4 = N*res4; settxt5 = N*res5; settxt6 = N*res6; break; default: break; } textView3.setText(Double.toString(settxt1)); textView5.setText(Double.toString(settxt2)); textView7.setText(Double.toString(settxt3)); textView9.setText(Double.toString(settxt4)); textView11.setText(Double.toString(settxt5)); textView13.setText(Double.toString(settxt6)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
33.657407
85
0.560385
ba2a78392a72755060700df380b65b920c2c245d
3,283
package tk.minarik.nomad.data; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.util.StringUtils; import java.io.IOException; /** * TODO Add meaningful description * <p> * Created by darko on 1.9.2016.. */ @Data @NoArgsConstructor @AllArgsConstructor public class RestartPolicy { /** * Attempts is the number of restarts allowed in an Interval. */ @JsonProperty("Attempts") private int attempts; /** * Interval is a time duration that is specified in nanoseconds. The Interval begins when the first task * starts and ensures that only Attempts number of restarts happens within it. If more than Attempts number * of failures happen, behavior is controlled by Mode. */ @JsonProperty("Interval") private int interval; /** * A duration to wait before restarting a task. It is specified in nanoseconds. A random jitter of up to 25% is added to the delay. */ @JsonProperty("Delay") private int delay; /** * Mode - Mode is given as a string and controls the behavior when the task fails more than Attempts times in an Interval. Possible values are listed below: * delay - delay will delay the next restart until the next Interval is reached. * fail - fail will not restart the task again. */ @JsonProperty("Mode") @JsonSerialize(using = ModeSerializer.class) @JsonDeserialize(using = ModeDeserializer.class) private Mode mode = Mode.Fail; /** * Mode is given as a string and controls the behavior when the task fails more than Attempts times in an Interval. Possible values are listed below: * delay - delay will delay the next restart until the next Interval is reached. * fail - fail will not restart the task again. */ public enum Mode { Delay, Fail } /** * Serializes mode to decapitalized form */ private static class ModeSerializer extends StdSerializer<Mode> { public ModeSerializer() { super(Mode.class); } @Override public void serialize(Mode value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeString(value.name().toLowerCase()); } } /** * Deserializes mode from decapitalized form */ private static class ModeDeserializer extends StdDeserializer<Mode> { public ModeDeserializer(){ super(Mode.class); } @Override public Mode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { return Mode.valueOf(StringUtils.capitalize(p.getText())); } } }
34.197917
160
0.709717
dd731cf241f4895bdd7f3772f7e455c2da8204bb
3,129
package se.kth.scs.remote; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.net.Socket; import java.util.LinkedList; import se.kth.scs.partitioning.Vertex; import se.kth.scs.remote.messages.Protocol; import se.kth.scs.remote.messages.Serializer; /** * This class is handles a session to communicate with a client. * * @author Hooman */ public class QueryHandler implements Runnable { private final ServerStorage state; private final Socket socket; public QueryHandler(ServerStorage state, Socket socket) { this.state = state; this.socket = socket; } @Override public void run() { try { DataInputStream input = new DataInputStream(socket.getInputStream()); DataOutputStream output = new DataOutputStream(socket.getOutputStream()); while (true) { byte request = input.readByte(); if (request == Protocol.VERTICES_READ_REQUEST) { int[] vids = Serializer.deserializeRequest(input); LinkedList<Vertex> response = state.getVertices(vids); Serializer.serializeVerticesReadResponse(output, response); } else if (request == Protocol.VERTICES_WRITE_REQUEST) { int[] vertices = Serializer.deserializeRequest(input); state.putVertices(vertices); } else if (request == Protocol.PARTITIONS_REQUEST) { int[] response = state.getPartitions(); Serializer.serializePartitionsReadResponse(output, response); } else if (request == Protocol.PARTITIONS_WRITE_REQUEST) { int[] partitions = Serializer.deserializeRequest(input); state.putPartitions(partitions); } else if (request == Protocol.ALL_VERTICES_REQUEST) { int expectedSize = Serializer.deserializeAllVerticesRequest(input); int[] response = state.getAllVertices(expectedSize); Serializer.serializeAllVerticesReadResponse(output, response); } else if (request == Protocol.CLOSE_SESSION_REQUEST) { System.out.println("A close-session request is received."); break; } else if (request == Protocol.CLEAR_ALL_REQUEST) { state.releaseResources(true); } else if (request == Protocol.CLEAR_ALL_BUT_DEGREE_REQUEST) { state.releaseResources(false); } else if (request == Protocol.WAIT_FOR_ALL_UPDATES_REQUEST) { int expectedSize = Serializer.deserializeAllVerticesRequest(input); state.waitForAllUpdates(expectedSize); output.writeByte(Protocol.WAIT_FOR_ALL_UPDATES_RESPONSE); output.flush(); } else { throw new Exception(String.format("Request type %d is not found.", request)); } } } catch (Exception ex) { if (!(ex instanceof EOFException)) { ex.printStackTrace(); } } try { if (!socket.isClosed()) { socket.close(); } System.out.println("Socket is closed."); } catch (IOException ex) { if (!(ex instanceof EOFException)) { ex.printStackTrace(); } } } }
35.965517
87
0.667306
33ef0a2bfae7ba12dbbfe01b37990dd8628c496d
6,343
package org.dstadler.commoncrawl; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import org.apache.commons.lang3.time.FastDateFormat; import org.apache.poi.Version; import org.apache.poi.stress.FileHandler; import org.apache.poi.stress.TestAllFiles; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Stream; import static org.dstadler.commoncrawl.POIFileScanner.HANDLERS; /** * Load a list of files and their mime-types from a JSON file and process the * files according to a mapping of the mime-type to extension. * * This is just a helper tool, the main tool for running the regression-tests is {@link ProcessFiles} */ public class ProcessJSONListOfFiles { private static final File BASE_DIR = new File("/"); private static final File RESULT_FILE = new File("result-vm-" + Version.getVersion() + "-" + FastDateFormat.getInstance("yyyy-MM-dd-HH-mm").format(new Date()) + ".json"); private static final Set<String> EXCLUDES = new HashSet<>(); static { EXCLUDES.add("/data2/docs/commoncrawl2/5W/5WUVHHK4YQ5HJQVPA5WG4F3TB2UGZJGF"); } public static void main(String[] args) throws Throwable { final File jsonFile; if(args.length == 0) { jsonFile = new File("/opt/file-type-detection/filetypes.txt"); } else { jsonFile = new File(args[0]); } processFile(jsonFile); } static void processFile(File jsonFile) throws InterruptedException, IOException { try (Writer resultWriter = new FileWriter(RESULT_FILE, true)) { ExecutorService executor = Executors.newSingleThreadExecutor(); long start = System.currentTimeMillis(); try { // read once for line-count to have progress-reporting in the output try (Stream<String> lines = Files.lines(jsonFile.toPath(), Charset.defaultCharset())) { FileHandlingRunnable.filesCount = lines.count(); } // and a second time for the actual processing try (Stream<String> lines = Files.lines(jsonFile.toPath(), Charset.defaultCharset())) { lines.forEachOrdered(line -> process(line, executor, start, resultWriter)); } executor.shutdown(); System.out.println("Having results from " + FileHandlingRunnable.filesCount + " files with " + FileHandlingRunnable.ignored.get() + " ignored files overall"); } catch (Throwable e) { e.printStackTrace(); // stop as soon as possible when any throwable is caught executor.shutdownNow(); throw e; } System.out.println("Awaiting termination"); executor.awaitTermination(60, TimeUnit.MINUTES); System.out.println("Done"); } catch (Throwable e) { e.printStackTrace(); throw e; } } protected static void process(String line, ExecutorService executor, long start, Writer resultWriter) { try { JsonElement jelement = JsonParser.parseString(line); JsonObject jobject = jelement.getAsJsonObject(); String fileName = jobject.get("fileName").getAsString(); try { String mimeType = jobject.get("mediaType").getAsString(); // only process certain mime-types if (!MimeTypes.matches(mimeType)) { FileHandlingRunnable.ignored.incrementAndGet(); return; } if (EXCLUDES.contains(fileName)) { FileHandlingRunnable.ignored.incrementAndGet(); return; } // use to re-start at a certain file if it is specified here if (fileName.compareTo("") <= 0) { FileHandlingRunnable.ignored.incrementAndGet(); return; } FileHandler fileHandler = HANDLERS.get(MimeTypes.toExtension(mimeType)); //new FileHandlingRunnable(start, fileName, fileHandler, resultWriter).run(); FileHandlingRunnable runnable = new FileHandlingRunnable(start, fileName, fileHandler, resultWriter, BASE_DIR); Future<?> future = executor.submit(runnable); // wait for execution and receive any results while (true) { try { // immediately wait for the future with a Timeout to stop any that take too long future.get(1, TimeUnit.MINUTES); // done for this future break; } catch (TimeoutException e) { ProcessFiles.handleTimeout(resultWriter, e); } catch (OutOfMemoryError e) { ProcessFiles.handleOOM(resultWriter, e); } catch (ExecutionException e) { //writeResult(resultWriter, future.get, null, true); System.out.println("Fatal exception for future: " + future); e.printStackTrace(); } } } catch (OutOfMemoryError e) { System.out.println("OutOfMemory exception: " + e); e.printStackTrace(); FileHandlingRunnable.writeResult(resultWriter, fileName, null, true, -1); } } catch (JsonParseException e) { System.out.println("Could not parse JSON for line: " + line); } catch (RuntimeException | InterruptedException e) { throw new RuntimeException("While handling line: " + line, e); } } }
40.660256
174
0.602869
c8470e73488f13e987157742176d120530ba7f06
906
package Mensaje; import java.io.Serializable; public abstract class Mensaje implements Serializable{ /* Tipos de mensajes 0 - Conexion 1 - Confirmacion conexion 2 - Cerrar conexion 3 - Confirmacion cerrar conexion 4 - Lista Usuarios 5 - Confirmacion lista de usuarios 6 - Pedir Fichero 7 - Emitir Fichero 8 - Preparado Cliente Servidor 9 - Preparado Servidor Cliente */ /** * */ private static final long serialVersionUID = 1L; protected int _tipo; protected String _origen; protected String _destino; public Mensaje(String origen, String destino) { _origen = origen; _destino = destino; } public int getTipo() { return _tipo; } public String getOrigen() { return _origen; } public String getDestino() { return _destino; } public String toString() { return "TIPO: " + _tipo + ", ORIGEN: " + _origen + ", DESTINO: " + _destino; } }
16.178571
78
0.684327
f5927d07ab3c3b607ab98e4bd3b603815142ee50
1,231
package de.uulm.vs.autodetect.mds.framework.model.containers; /** * A container for a (3D) position. * * @author Rens van der Heijden */ public class PositionContainer implements MaatContainer { private final double[] pos; public PositionContainer(double[] position) { this.pos = position; } public double[] getPosition() { return this.pos; } public double getX() { return this.pos[0]; } public double getY() { return this.pos[1]; } public double getZ() { return this.pos[2]; } @Override public WorldModelDataTypeEnum getDataType() { return WorldModelDataTypeEnum.POSITION; } /** * Compute distance between two positions using simple Euclidean distance */ public double distance(PositionContainer prevPos) { double diffX = Math.abs(prevPos.getX() - this.getX()); double diffY = Math.abs(prevPos.getY() - this.getY()); double diffZ = Math.abs(prevPos.getZ() - this.getZ()); return Math.sqrt(diffX * diffX + diffY * diffY + diffZ * diffZ); } @Override public String toString() { return "(" + pos[0] + "," + pos[1] + "," + pos[2] + ")"; } }
23.226415
77
0.600325
c000cf23cd64eaf5ab35b9c33f1031b0c22a3aeb
973
package com.futurice.project.test.device; import com.futurice.project.MainActivity; import com.futurice.project.R; import com.robotium.solo.Solo; import android.test.ActivityInstrumentationTestCase2; import android.view.View; import android.widget.TextView; public class BookFragmentTest extends ActivityInstrumentationTestCase2<MainActivity> { private Solo solo; public BookFragmentTest() { super(MainActivity.class); } @Override protected void setUp() throws Exception { solo = new Solo(getInstrumentation(), getActivity()); } public void test_shouldShowBookTitle() throws Exception { TextView titleText = (TextView) solo.getView(R.id.title); assertEquals(View.VISIBLE, titleText.getVisibility()); assertNotSame("How Rx will Change the World", titleText.getText().toString()); solo.sleep(1000); assertEquals("How Rx will Change the World", titleText.getText().toString()); } }
31.387097
86
0.725591
3705dca4f55925c7d64a74b99a1f573159692888
11,132
/* * Copyright (C) 2019 All rights reserved for FaraSource (ABBAS GHASEMI) * https://farasource.com */ package ghasemi.abbas.book.sqlite; import android.content.ContentValues; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import ghasemi.abbas.book.general.AndroidUtilities; public class BookDB extends AnalyzeDB { private final String[] related = new String[]{ "و", "به", "را", "چه" , "که", "در", "تا", "از", "روی" , "زیر", "رو", "بر", "ما", "زیرا", "هم", "ولی", "با", "یا", "پس" , "اگر", "نه", "چون", "ی", "چرا", "ها", "های", "هایی", "هائی", "سپس", "ترین", "تر", "می", "آنرا", "آن", "او" }; private final String[] empty = new String[]{ ".", "،", "-", ",", ">", "<", "'", "\"", "?", "+", "؟", "=", "/", "_", "!", "@", "#", "$", "%", "\\", ";", ":", "*" }; private BookDB() { super(); } public static BookDB getInstance() { return new BookDB(); } public void seasons(final String season, final String season_id, final ResultRequest resultRequest) { AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() { @Override public void run() { String query = String.format("select id,title,content,post_type,icon_name from book where season = %s and season_id = %s", season, season_id); Cursor cursor = getSqLiteDatabase().rawQuery(query, null); if (cursor.moveToFirst()) { List<SqlModel> list = new ArrayList<>(); do { SqlModel sqlModel = new SqlModel(cursor.getInt(0), Integer.parseInt(season), Integer.parseInt(season_id), cursor.getString(1), cursor.getString(2), cursor.getString(3), -1, cursor.getString(4)); list.add(sqlModel); } while (cursor.moveToNext()); cursor.close(); resultRequest.onSuccess(list); } else { cursor.close(); resultRequest.onFail(); } } }); } public void post(final String contentID, final ResultRequest resultRequest) { AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() { @Override public void run() { String query = String.format("select title,content,is_favorite from book where id = %s", contentID); Cursor cursor = getSqLiteDatabase().rawQuery(query, null); if (cursor.moveToFirst()) { List<SqlModel> list = new ArrayList<>(); SqlModel sqlModel = new SqlModel(Integer.parseInt(contentID), -1, -1, cursor.getString(0), cursor.getString(1), "post", cursor.getInt(2), null); list.add(sqlModel); cursor.close(); resultRequest.onSuccess(list); } else { resultRequest.onFail(); } } }); } public void addPostFavorite(final String contentID) { AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() { @Override public void run() { ContentValues values = new ContentValues(); values.put("is_favorite", 1); getSqLiteDatabase().update("book", values, "id = ?", new String[]{contentID}); values = new ContentValues(); values.put("post_id", contentID); getSqLiteDatabase().insert("favorites", null, values); } }); } public void removePostFavorite(final String contentID) { AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() { @Override public void run() { ContentValues values = new ContentValues(); values.put("is_favorite", 0); getSqLiteDatabase().update("book", values, "id = ?", new String[]{contentID}); getSqLiteDatabase().delete("favorites", "post_id = ?", new String[]{contentID}); } }); } public void favorite(final ResultRequest resultRequest) { AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() { @Override public void run() { Cursor cursor = getSqLiteDatabase().rawQuery("select id,title,content,season_id,icon_name from book where id in (select post_id from favorites)", null); if (cursor.moveToFirst()) { List<SqlModel> sqlModelList = new ArrayList<>(); do { sqlModelList.add(new SqlModel(cursor.getInt(0), -1, cursor.getInt(3), cursor.getString(1), cursor.getString(2), "post", -1, cursor.getString(4))); } while (cursor.moveToNext()); cursor.close(); resultRequest.onSuccess(sqlModelList); } else { resultRequest.onFail(); } } }); } public void search(final Bundle bundle, final ResultRequest resultRequest) { AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() { @Override public void run() { ArrayList<String> parts = new ArrayList<>(); parts.add(bundle.getString("search")); if (bundle.getBoolean("similar")) { String query = bundle.getString("search"); for (String em : empty) { query = query.replace(em, " "); } parts.addAll(Arrays.asList(query.split(" "))); for (int i = 0; i < parts.size(); i++) { for (String related : BookDB.this.related) { if (parts.get(i).equals(related) || parts.get(i).length() < 3) { parts.remove(i--); break; } } } } if (parts.isEmpty()) { resultRequest.onFail(); } else { List<SqlModel> sqlModelList = new ArrayList<>(); if (bundle.getBoolean("title")) { searchQuery(parts, "title", bundle, sqlModelList); } if (bundle.getBoolean("content")) { searchQuery(parts, "content", bundle, sqlModelList); } if (sqlModelList.isEmpty()) { resultRequest.onFail(); } else { sqlModelList.add(new SqlModel(-1, -1, -1, null, null, join(parts), -1, null)); resultRequest.onSuccess(sqlModelList); } } } }); } private void searchQuery(ArrayList<String> search, String on, Bundle bundle, List<SqlModel> sqlModelList) { String q = createLike(search, on); String query = String.format("select id,season,season_id,title,post_type,icon_name from book where post_type in('post','row_list','card_list','classic_list') and (%s)", q); if (!bundle.getBoolean("all")) { query += " and season_id = " + bundle.getString("season_id"); } if (bundle.getBoolean("fav")) { query += " and is_favorite = 0"; } Cursor cursor = getSqLiteDatabase().rawQuery(query, null); if (cursor.moveToFirst()) { sqlModelList.add(new SqlModel(-1, -1, -1, null, null, on, -1, null)); do { sqlModelList.add(new SqlModel(cursor.getInt(0), cursor.getInt(1), cursor.getInt(2), cursor.getString(3), on, cursor.getString(4), -1, cursor.getString(5))); } while (cursor.moveToNext()); } cursor.close(); } private String createLike(ArrayList<String> search, String on) { StringBuilder query = new StringBuilder(); for (int i = 1; i < search.size(); i++) { query.append(String.format("%s like '%s%s%s'", on, "%", search.get(i).trim(), "%")); if (i < search.size() - 1) { query.append(" and "); } } if (query.toString().isEmpty()) { query.append(String.format("%s like '%s%s%s'", on, "%", search.get(0), "%")); } else { query.append(String.format(" or %s like '%s%s%s'", on, "%", search.get(0), "%")); } return query.toString(); } private String join(ArrayList<String> search) { StringBuilder stringBuilder = new StringBuilder(); for (String part : search) { stringBuilder.append(",").append(part); } return stringBuilder.substring(1); } public void single(final String post_type, final ResultRequest resultRequest) { AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() { @Override public void run() { Cursor cursor = getSqLiteDatabase().rawQuery(String.format("select title,content from book where post_type = '%s' limit 1", post_type), null); if (cursor.moveToFirst()) { List<SqlModel> list = new ArrayList<>(); SqlModel sqlModel = new SqlModel(-1, -1, -1, cursor.getString(0), cursor.getString(1), post_type, -1, null); list.add(sqlModel); cursor.close(); resultRequest.onSuccess(list); } else { cursor.close(); resultRequest.onFail(); } } }); } public void requestTypeFromId(String id, final ResultRequest resultRequest) { AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() { @Override public void run() { String query = String.format("select id,season,season_id,title,content,post_type,icon_name from book where id = %s", id); Cursor cursor = getSqLiteDatabase().rawQuery(query, null); if (cursor.moveToFirst()) { List<SqlModel> list = new ArrayList<>(); SqlModel sqlModel = new SqlModel(cursor.getInt(0), cursor.getInt(1), cursor.getInt(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), -1, cursor.getString(6)); list.add(sqlModel); cursor.close(); resultRequest.onSuccess(list); } else { cursor.close(); resultRequest.onFail(); } } }); } }
42.326996
180
0.50018
5c9ba3abe262e244338c43d02135d91db33e39ca
394
package com.yousuf.android.moviesearch.network; import com.yousuf.android.moviesearch.model.MovieList; import java.util.Map; import retrofit2.http.GET; import retrofit2.http.QueryMap; import rx.Observable; /** * Created by yousufsyed on 4/20/17. */ public interface TheMovieApi { @GET("search/movie?") Observable<MovieList> getMovieList(@QueryMap Map<String, String> params); }
19.7
77
0.756345
d3edffdc754e18e0e7426c3e64ee0b3bc9a260da
14,123
package com.epicnuss55.epicsExtremeSurvival.Events; import com.epicnuss55.epicsExtremeSurvival.EpicsExtremeSurvival; import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.block.Blocks; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.AbstractGui; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Items; import net.minecraft.nbt.CompoundNBT; import net.minecraft.tags.FluidTags; import net.minecraft.util.DamageSource; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvents; import net.minecraft.util.math.*; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.world.Difficulty; import net.minecraft.world.World; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.gui.ForgeIngameGui; import net.minecraftforge.event.entity.living.LivingDamageEvent; import net.minecraftforge.event.entity.living.LivingEntityUseItemEvent; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.living.LivingHealEvent; import net.minecraftforge.event.entity.player.AttackEntityEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; @Mod.EventBusSubscriber(modid = EpicsExtremeSurvival.MODID) public class ThirstStuffs { //*---------------EVENTS---------------*\\ //wont heal unless water is also high enough @SubscribeEvent public void Heal(LivingHealEvent event) { if (event.getEntity() instanceof PlayerEntity) { if (thirstValue < 8.5f) { event.setCanceled(true); } else { Dehydration = Dehydration + REGEN; event.setCanceled(false); } } } private static BlockRayTraceResult rayTrace(World worldIn, PlayerEntity player, RayTraceContext.FluidMode fluidMode) { float f = player.rotationPitch; float f1 = player.rotationYaw; Vector3d vector3d = player.getEyePosition(1.0F); float f2 = MathHelper.cos(-f1 * ((float)Math.PI / 180F) - (float)Math.PI); float f3 = MathHelper.sin(-f1 * ((float)Math.PI / 180F) - (float)Math.PI); float f4 = -MathHelper.cos(-f * ((float)Math.PI / 180F)); float f5 = MathHelper.sin(-f * ((float)Math.PI / 180F)); float f6 = f3 * f4; float f7 = f2 * f4; double d0 = player.getAttribute(net.minecraftforge.common.ForgeMod.REACH_DISTANCE.get()).getValue();; Vector3d vector3d1 = vector3d.add((double)f6 * d0, (double)f5 * d0, (double)f7 * d0); return worldIn.rayTraceBlocks(new RayTraceContext(vector3d, vector3d1, RayTraceContext.BlockMode.OUTLINE, fluidMode, player)); } private static int Thirst_Effect = 0; @SubscribeEvent public void RightClick(PlayerInteractEvent event) { RayTraceResult res = rayTrace(event.getWorld(), event.getPlayer(), RayTraceContext.FluidMode.SOURCE_ONLY); if (res.getType() == RayTraceResult.Type.BLOCK) { BlockPos blockpos = ((BlockRayTraceResult) res).getPos(); if (event.getWorld().getFluidState(blockpos).isTagged(FluidTags.WATER) && event.getWorld().isBlockModifiable(event.getPlayer(), blockpos)) { event.getWorld().playSound(event.getPlayer(), event.getPlayer().getPosX(), event.getPlayer().getPosY(), event.getPlayer().getPosZ(), SoundEvents.ENTITY_GENERIC_DRINK, SoundCategory.NEUTRAL, 1.0F, 1.0F); AddThirst(.5f); Thirst_Effect = 600; } } } //thirst logic @SubscribeEvent public void TDehydration(LivingEvent.LivingUpdateEvent event) { if (event.getEntityLiving() instanceof PlayerEntity && !((PlayerEntity) event.getEntityLiving()).isCreative()) { if (thirstValue != 0 && event.getEntityLiving().getEntityWorld().getDifficulty() != Difficulty.PEACEFUL) dehydrator((PlayerEntity) event.getEntityLiving()); if (thirstValue == 0) dehydrated = true; if (thirstValue < 3f) dehydrationEvent((PlayerEntity) event.getEntityLiving()); if (Thirst_Effect > 0) { Thirst_Effect--; Dehydration = Dehydration + DEHYDRATED_DEBUFF; } animate(); } } //If drinks any bottled liquids then adds half a bar back @SubscribeEvent public void DrinkWater(LivingEntityUseItemEvent.Finish event) { if (event.getResultStack().getItem() == Items.GLASS_BOTTLE.getItem() && event.getEntity().getEntityWorld().isRemote()) AddThirst(0.5f); if (event.getResultStack().getItem() == Items.HONEY_BOTTLE.getItem() && event.getEntity().getEntityWorld().isRemote()) AddThirst(1f); } //after the player dies and respawns, thirst value resets @SubscribeEvent public void Respawn(PlayerEvent.PlayerRespawnEvent event) { if (event.getEntity().equals(Minecraft.getInstance().player)) { thirstValue = 10f; } } //Renderer @SubscribeEvent public void Overlay(RenderGameOverlayEvent.Post event) { if (event.getType() == RenderGameOverlayEvent.ElementType.FOOD) { Minecraft mc = Minecraft.getInstance(); int y = mc.getMainWindow().getScaledHeight() - ForgeIngameGui.right_height; int x = mc.getMainWindow().getScaledWidth() / 2 + 82; MatrixStack stack = event.getMatrixStack(); mc.getTextureManager().bindTexture(new ResourceLocation(EpicsExtremeSurvival.MODID, "textures/gui/overlays.png")); renderThirstBar(stack, x, y); mc.getTextureManager().bindTexture(AbstractGui.GUI_ICONS_LOCATION); } } //*---------------LOGIC---------------*\\ //render logic public static void renderThirstBar(MatrixStack stack, int x, int y) { int fullAmount = (int) thirstValue; boolean drawHalf = fullAmount != thirstValue; int iterator = 0; if (Minecraft.getInstance().player.areEyesInFluid(FluidTags.WATER) || Minecraft.getInstance().player.getAir() < 300) { y = y-9; } if (Thirst_Effect > 0) { while (iterator != fullAmount) { if (animate) { if ((iterator % 2) == 0) { draw(stack, x - (iterator * 8), y + 1, 0, 10, 9, 9); } else draw(stack, x - (iterator * 8), y - 1, 0, 10, 9, 9); } else draw(stack, x - (iterator * 8), y, 0, 10, 9, 9); iterator = iterator + 1; } if (drawHalf) { if (animate) { if ((iterator % 2) == 0) { draw(stack, x - (iterator * 8), y + 2, 20, 10, 9, 9); } else draw(stack, x - (iterator * 8), y - 2, 20, 10, 9, 9); } else draw(stack, x - (iterator * 8), y, 10, 10, 9, 9); iterator = iterator + 1; } while (iterator != 10) { if (animate) { if ((iterator % 2) == 0) { draw(stack, x - (iterator * 8), y + 1, 30, 10, 9, 9); } else draw(stack, x - (iterator * 8), y - 1, 30, 10, 9, 9); } else draw(stack, x - (iterator * 8), y, 30, 10, 9, 9); iterator = iterator + 1; } } else { while (iterator != fullAmount) { if (animate) { if ((iterator % 2) == 0) { draw(stack, x - (iterator * 8), y + 1, 0, 0, 9, 9); } else draw(stack, x - (iterator * 8), y - 1, 0, 0, 9, 9); } else draw(stack, x - (iterator * 8), y, 0, 0, 9, 9); iterator = iterator + 1; } if (drawHalf) { if (animate) { if ((iterator % 2) == 0) { draw(stack, x - (iterator * 8), y + 2, 20, 0, 9, 9); } else draw(stack, x - (iterator * 8), y - 2, 20, 0, 9, 9); } else draw(stack, x - (iterator * 8), y, 10, 0, 9, 9); iterator = iterator + 1; } while (iterator != 10) { if (animate) { if ((iterator % 2) == 0) { draw(stack, x - (iterator * 8), y + 1, 30, 0, 9, 9); } else draw(stack, x - (iterator * 8), y - 1, 30, 0, 9, 9); } else draw(stack, x - (iterator * 8), y, 30, 0, 9, 9); iterator = iterator + 1; } } } //hunger icon bobbing private static int animTick = 0; private static int animating = 0; private static boolean animate = false; private static void animate() { if (!animate) { animTick++; if (thirstValue <= 10f && thirstValue >= 9.5f && animTick > 640) { animate = true; animTick = 0; } else if (thirstValue <= 9f && thirstValue >= 8f && animTick > 200) { animate = true; animTick = 0; } else if (thirstValue <= 7.5f && thirstValue >= 6.5f && animTick > 160) { animate = true; animTick = 0; } else if (thirstValue <= 6f && thirstValue >= 5f && animTick > 80) { animate = true; animTick = 0; } else if (thirstValue <= 4.5f && thirstValue >= 3.5f && animTick > 20) { animate = true; animTick = 0; } else if (thirstValue <= 3f && thirstValue >= 2f && animTick > 10) { animate = true; animTick = 0; } else if (thirstValue <= 1.5f && thirstValue >= 0f && animTick > 5) { animate = true; animTick = 0; } } if (animate) { animating++; if (animating > 5) { animate = false; animating = 0; } } } //render simplifier lol private static void draw(MatrixStack stack, int ScreenXPos, int ScreenYPos, int textureXStartPos, int textureYStartPos, int textureXEndPos, int textureYEndPos) { Minecraft.getInstance().ingameGUI.blit(stack, ScreenXPos, ScreenYPos, textureXStartPos, textureYStartPos, textureXEndPos, textureYEndPos); } public static float thirstValue = 10f; public static int damageTick = 0; //when thirst value is below 3 bars, fire this public static void dehydrationEvent(PlayerEntity player) { if (player.isSprinting()) player.setSprinting(false); if (thirstValue == 0) { damageTick++; if (damageTick == 100) { damageTick = 0; switch (player.getEntityWorld().getDifficulty()) { case NORMAL: case EASY: if (player.getHealth() < 10f) player.attackEntityFrom(DamageSource.STARVE, 1); break; case HARD: player.attackEntityFrom(DamageSource.STARVE, 1); } } } } private static double Dehydration = 0; private static Boolean dehydrated = false; private static final double SWIMMING = 0.01; private static final double BLOCK_BREAKING = 1; private static final double SPRINTING = 0.05; private static final double JUMPING = 2; private static final double ATTACKING = 2; private static final double TAKING_DAMAGE = 4; private static final double DEHYDRATED_DEBUFF = 0.1; private static final double REGEN = 5; //reduces your thirst when preforming certain actions (see above) private static void dehydrator(PlayerEntity player) { if (player.getEntityWorld().getBlockState(player.getPosition()).equals(Blocks.WATER.getDefaultState()) && !dehydrated) Dehydration = Dehydration + SWIMMING; if (player.isSprinting() && !dehydrated) Dehydration = Dehydration + SPRINTING; if (Dehydration > 50) { Dehydration = 0; thirstValue = thirstValue - 0.5f; } } @SubscribeEvent public void BlockBreak(BlockEvent.BreakEvent event) { if (!dehydrated) Dehydration = Dehydration + BLOCK_BREAKING; } @SubscribeEvent public void Jump(LivingEvent.LivingJumpEvent event) { if (event.getEntity() == Minecraft.getInstance().player && !dehydrated) Dehydration = Dehydration + JUMPING; } @SubscribeEvent public void Attack(AttackEntityEvent event) { if (!dehydrated) Dehydration = Dehydration + ATTACKING; } @SubscribeEvent public void Damage(LivingDamageEvent event) { if (event.getEntity() == Minecraft.getInstance().player && !dehydrated) { Dehydration = Dehydration + TAKING_DAMAGE; } } //Thirst adder public static void AddThirst(float added) { float finalVal = added + thirstValue; if (finalVal <= 10) { thirstValue = finalVal; } else thirstValue = 10f; } //Thirst save system public static final String THIRST_NBT = "thirstval"; public static final String DEHYDRATION_NBT = "dehydrationval"; public static final String THIRST_EFFECT_NBT = "thirsteffectval"; public static void read(CompoundNBT compound) { thirstValue = compound.getFloat(THIRST_NBT); Dehydration = compound.getFloat(DEHYDRATION_NBT); Thirst_Effect = compound.getInt(THIRST_EFFECT_NBT); } public static void write(CompoundNBT compound) { compound.putFloat(THIRST_NBT, thirstValue); compound.putDouble(DEHYDRATION_NBT, Dehydration); compound.putInt(THIRST_EFFECT_NBT, Thirst_Effect); } }
41.055233
218
0.589039
cbe8f3c8b560369750deef4946253306921429ec
749
package com.github.signed.inmemory.ftp; import java.io.File; import java.util.Collections; import java.util.List; import com.github.signed.inmemory.shared.configuration.Port; public class FtpServerConfiguration { private final File rootDirectory; private final Port port; private final Iterable<FtpUser> users; public FtpServerConfiguration(File rootDirectory, Port port, List<FtpUser> users) { this.rootDirectory = rootDirectory; this.port = port; this.users = Collections.unmodifiableList(users); } public int port() { return port.port(); } public File rootDirectory() { return rootDirectory; } public Iterable<FtpUser> users() { return users; } }
23.40625
87
0.688919
3be8bf4537b81ef7e99c4d6bc2cda1236d35220e
13,644
/* * www.javagl.de - Flow * * Copyright (c) 2012-2017 Marco Hutter - http://www.javagl.de * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package de.javagl.flow.io.xml; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Utility methods related to XML handling */ public class XmlUtils { /** * A default XML document */ private static Document defaultDocument = null; /** * Returns a default XML document * * @return The default XML document */ public static Document getDefaultDocument() { if (defaultDocument == null) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = null; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { // Can not happen, since it's the default configuration throw new XmlException("Could not create default document", e); } defaultDocument = documentBuilder.newDocument(); } return defaultDocument; } /** * Creates a formatted String representation of the given XML node * * @param node The node * @return The formatted String representation of the given node * @throws XmlException If there was an error while writing. * This should never be the case for this method, because the * XML is written into a String, and no exceptional situation * (like IOException) can happen here. */ public static String toString(Node node) { StringWriter stringWriter = new StringWriter(); write(node, stringWriter); return stringWriter.toString(); } /** * Writes a formatted String representation of the given XML node * to the given output stream. The caller is responsible for * closing the given stream. * * @param node The node * @param outputStream The output stream to write to * @throws XmlException If there was an error while writing */ public static void write(Node node, OutputStream outputStream) { OutputStreamWriter writer = new OutputStreamWriter(outputStream); write(node, writer); } /** * Writes a formatted String representation of the given XML node * to the given writer. * * @param node The node * @param writer The writer to write to * @throws XmlException If there was an error while writing */ private static void write(Node node, Writer writer) { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = null; try { transformer = transformerFactory.newTransformer(); } catch (TransformerConfigurationException canNotHappen) { // Can not happen here throw new XmlException( "Could not create transformer", canNotHappen); } transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); int indent = 4; transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent)); DOMSource source = new DOMSource(node); StreamResult xmlOutput = new StreamResult(writer); try { transformer.transform(source, xmlOutput); } catch (TransformerException e) { throw new XmlException("Could not transform node", e); } } /** * Creates an XML node by reading the contents of the given input stream. * * @param inputStream The input stream to read from * @return The parsed node * @throws XmlException If there was an error while reading */ public static Node read(InputStream inputStream) throws XmlException { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputStream); Node node = document.getDocumentElement(); return node; } catch (ParserConfigurationException canNotHappen) { // Can not happen with a default configuration throw new XmlException("Could not create parser", canNotHappen); } catch (SAXException e) { throw new XmlException("XML parsing error", e); } catch (IOException e) { throw new XmlException("IO error while reading XML", e); } } /** * Creates an XML node from the * {@link #getDefaultDocument() default document} whose only child * is a text node that contains the string representation of the * given object * * @param tagName The tag name for the node * @param contents The object whose string representation will be * the contents of the text node * @return The node */ static Node createTextNode(String tagName, Object contents) { Document d = XmlUtils.getDefaultDocument(); Element node = d.createElement(tagName); node.appendChild(d.createTextNode(String.valueOf(contents))); return node; } /** * Returns the attribute with the given name from the given node. * If the respective attribute could not be obtained, the given * default value will be returned * * @param node The node to obtain the attribute from * @param attributeName The name of the attribute * @param defaultValue The default value to return when the specified * attribute could not be obtained * @return The value of the attribute, or the default value */ static String getAttributeValue( Node node, String attributeName, String defaultValue) { NamedNodeMap attributes = node.getAttributes(); Node attributeNode = attributes.getNamedItem(attributeName); if (attributeNode == null) { return defaultValue; } String value = attributeNode.getNodeValue(); if (value == null) { return defaultValue; } return value; } /** * Returns the attribute with the given name from the given node. * * @param node The node to obtain the attribute from * @param attributeName The name of the attribute * @return The value of the attribute * @throws XmlException If no value of the attribute with the given * name could be obtained. */ static String getRequiredAttributeValue(Node node, String attributeName) { NamedNodeMap attributes = node.getAttributes(); Node attributeNode = attributes.getNamedItem(attributeName); if (attributeNode == null) { throw new XmlException( "No attribute with name \"" + attributeName + "\" found"); } String value = attributeNode.getNodeValue(); if (value == null) { throw new XmlException( "Attribute with name \"" + attributeName + "\" has no value"); } return value; } /** * Removes any whitespace from the text nodes that are descendants * of the given node. Any text node that becomes empty due to this * (that is, any text node that only contained whitespaces) will * be removed. * * @param node The node to remove whitespaces from */ static void removeWhitespace(Node node) { NodeList childList = node.getChildNodes(); List<Node> toRemove = new ArrayList<Node>(); for (int i = 0; i < childList.getLength(); i++) { Node child = childList.item(i); if (child.getNodeType() == Node.TEXT_NODE) { String text = child.getTextContent(); String trimmed = text.trim(); if (trimmed.isEmpty()) { toRemove.add(child); } else if (trimmed.length() < text.length()) { child.setTextContent(trimmed); } } removeWhitespace(child); } for (Node c : toRemove) { node.removeChild(c); } } /** * Verify that the name of the given node matches the expected tag name * (ignoring upper/lowercase), and throw an XmlException if this is not * the case. * * @param node The node * @param expected The expected tag name * @throws XmlException If the node name does not match the expected name */ static void verifyNodeName(Node node, String expected) { if (!node.getNodeName().equalsIgnoreCase(expected)) { throw new XmlException( "Expected <" + expected + "> tag, " + "but found <" + node.getNodeName() + ">"); } } /** * Resolve the value in the given map whose key is the value of * the specified attribute. * * @param <T> The type of the elements in the map * @param node The node * @param attributeName The name of the attribute * @param map The map * @return The value in the map whose key is the value of the * specified attribute * @throws XmlException If either the given node does not contain * an attribute with the given name, or the map does not contain * a value for the respective attribute value */ static <T> T resolve( Node node, String attributeName, Map<String, ? extends T> map) { String id = XmlUtils.getAttributeValue(node, attributeName, null); if (id == null) { throw new XmlException( "No attribute \"" + attributeName + "\" found"); } T result = map.get(id); if (result == null) { throw new XmlException( "Could not resolve value with id \"" + id + "\""); } return result; } /** * Parse an int value from the first child of the given node. * * @param node The node * @return The int value * @throws XmlException If no int value could be parsed */ static int readInt(Node node) { String value = node.getFirstChild().getNodeValue(); try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new XmlException( "Expected int value, found \"" + value + "\"", e); } } /** * Private constructor to prevent instantiation */ private XmlUtils() { // Private constructor to prevent instantiation } }
34.024938
80
0.600704
c86fb78ea65236e995c73779e87e4ca11bfd94ee
7,147
/* * Copyright (c) 2004 jPOS.org * * See terms of license at http://jpos.org/license.html * */ package tlv; import iso.TestUtils; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import com.futeh.progeny.iso.ISOException; import com.futeh.progeny.iso.ISOUtil; import com.futeh.progeny.tlv.TLVList; import com.futeh.progeny.tlv.TLVMsg; import static org.junit.jupiter.api.Assertions.*; /** * @author Bharavi */ public class TestTLVMsg { byte[] aid1={(byte)0xA0,(byte)0x00,0x00,0x00,(byte)0x96,0x02,0x00}; byte[] aid2={(byte)0xA0,(byte)0x00,0x00,0x00,(byte)0x96,0x02,0x01}; byte[] aid3={(byte)0xA0,(byte)0x00,0x00,0x00,(byte)0x96,0x02,0x02}; byte[] atc={(byte)0x00,(byte)0x01}; byte[] mac=ISOUtil.hex2byte("0ED701005000522400000000158501AA"); byte[] data=ISOUtil.hex2byte("8407A00000009602008407A00000009602018407A00000009602029F70020001"); byte[] dataWithPadding=ISOUtil.hex2byte("8407A0000000960200FFFF00008407A00000009602010000FFFF8407A00000009602029F70020001"); byte[] dataWithTrailingPadding=ISOUtil.hex2byte("8407A00000009602008407A00000009602018407A00000009602029F70020001FFFFFFFFFFFFFFFF0000000000000000FF00FF00FF00"); byte[] dataAtOffset=ISOUtil.hex2byte("000000008407A00000009602008407A00000009602018407A00000009602029F70020001"); byte[] data2=ISOUtil.hex2byte("0100168407A00000009602008407A00000009602018407A00000009602029F70020001"); byte[] dataLong=ISOUtil.hex2byte("6481945A13303030353232343030303030303030313538355F3401019F2608C63CEB0B838CE5E09F360200E59F3704045680009F5604000000109F90010B50494E20556E626C6F636B9F6008452278451F42E4697F3B0F9F5D01019F5E080000000000000001580200E09F33030010409F3501119F9002100ED701005000522400000000158501AA9F50054D434849509F510430343030"); byte[] dataLongTag=ISOUtil.hex2byte("5A13303132333435363738393031323334353637385F3401019F2608C63CEB0B838CE5E09F360200E59F3704045680009F5604000000109F90010B50494E20556E626C6F636B9F6008452278451F42E4697F3B0F9F5D01019F5E080000000000000001580200E09F33030010409F3501119F9002100ED701005000522400000000158501AA9F50054D434849509F510430343030"); byte[] dataLongAtOffset=ISOUtil.hex2byte("01006481945A13303030353232343030303030303030313538355F3401019F2608C63CEB0B838CE5E09F360200E59F3704045680009F5604000000109F90010B50494E20556E626C6F636B9F6008452278451F42E4697F3B0F9F5D01019F5E080000000000000001580200E09F33030010409F3501119F9002100ED701005000522400000000158501AA9F50054D434849509F510430343030"); byte[] dataT=ISOUtil.hex2byte("84"); byte[] dataTL=ISOUtil.hex2byte("8407"); byte[] dataBadLength=ISOUtil.hex2byte("8481A8010203"); /* * @see TestCase#setUp() */ protected void setUp() throws Exception { } @Test public void testUnpack() throws Exception { TLVList tlvList=new TLVList(); tlvList.unpack(data); TLVMsg m1=tlvList.find(0x84); TLVMsg m2=tlvList.findNextTLV(); TLVMsg m3=tlvList.findNextTLV(); TLVMsg m4=tlvList.find(0x9F70); TestUtils.assertEquals(aid1,m1.getValue()); TestUtils.assertEquals(aid2,m2.getValue()); TestUtils.assertEquals(aid3,m3.getValue()); TestUtils.assertEquals(atc, m4.getValue()); } @Test public void testUnpackPadded() throws Exception { TLVList tlvList=new TLVList(); tlvList.unpack(dataWithPadding); TLVMsg m1=tlvList.find(0x84); TLVMsg m2=tlvList.findNextTLV(); TLVMsg m3=tlvList.findNextTLV(); TLVMsg m4=tlvList.find(0x9F70); TestUtils.assertEquals(aid1,m1.getValue()); TestUtils.assertEquals(aid2,m2.getValue()); TestUtils.assertEquals(aid3,m3.getValue()); TestUtils.assertEquals(atc, m4.getValue()); } @Test public void testUnpackTrailingPadded() throws Exception { TLVList tlvList=new TLVList(); tlvList.unpack(dataWithTrailingPadding); TLVMsg m1=tlvList.find(0x84); TLVMsg m2=tlvList.findNextTLV(); TLVMsg m3=tlvList.findNextTLV(); TLVMsg m4=tlvList.find(0x9F70); TestUtils.assertEquals(aid1,m1.getValue()); TestUtils.assertEquals(aid2,m2.getValue()); TestUtils.assertEquals(aid3,m3.getValue()); TestUtils.assertEquals(atc, m4.getValue()); } @Test public void testUnpackWithOffset() throws Exception { TLVList tlvList=new TLVList(); tlvList.unpack(data2,3); TLVMsg m1=tlvList.find(0x84); TLVMsg m2=tlvList.findNextTLV(); TLVMsg m3=tlvList.findNextTLV(); TLVMsg m4=tlvList.find(0x9F70); TestUtils.assertEquals(aid1,m1.getValue()); TestUtils.assertEquals(aid2,m2.getValue()); TestUtils.assertEquals(aid3,m3.getValue()); TestUtils.assertEquals(atc, m4.getValue()); } @Test public void testPack() { TLVList tlv=new TLVList(); tlv.append(0x84,aid1); tlv.append(0x84,aid2); tlv.append(0x84,aid3); tlv.append(0x9F70,atc); TestUtils.assertEquals(data, tlv.pack()); } @Test public void testUnpackLong() { TLVList tlv = new TLVList(); try { tlv.unpack(dataLong); } catch (ISOException e) { fail("TLVList.unpack should work with long length indicator"); } } @Test public void testUnpackWithOffsetLong() { TLVList tlv = new TLVList(); try { tlv.unpack(dataLongAtOffset,2); } catch (Exception e) { fail("TLVList.unpack should work from an offset and long length indicator"); } } @Test public void testUnpackLongTag() { TLVList tlv = new TLVList(); try { tlv.unpack(dataLongTag); } catch (ISOException e) { fail("TLVList.unpack should work on data with long tag lengths"); } TLVMsg macTLVMsg = tlv.find(0x9F9002); assertNotNull(macTLVMsg); assertEquals(macTLVMsg.getTag(),0x9f9002); TestUtils.assertEquals(mac,macTLVMsg.getValue()); } @Test public void testUnpackT() { TLVList tlv = new TLVList(); try { tlv.unpack(dataT); fail("TLVList.unpack should catch incomplete tags - tags without LVs"); } catch (ISOException e) { assertTrue(e.toString().indexOf("BAD TLV FORMAT") > -1); } } @Test public void testUnpackTL() { TLVList tlv = new TLVList(); try { tlv.unpack(dataTL); fail("TLVList.unpack should catch incomplete tags"); } catch (ISOException e) { assertTrue(e.toString().indexOf("BAD TLV FORMAT") > -1); } } @Test public void testUnpackBadLength() { TLVList tlv = new TLVList(); try { tlv.unpack(dataBadLength); fail("TLVList.unpack should catch Lengths indicationg value outside of data range"); } catch (ISOException e) { assertTrue(e.toString().indexOf("BAD TLV FORMAT") > -1); } } }
34.694175
356
0.682524
8feb1c3ff3765893fafed192c0c1efeb98078e78
3,039
/** * The MIT License (MIT) * * Copyright (c) 2015 Halo9Pan * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package info.inkstack.troll.seg; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.chenlb.mmseg4j.Dictionary; import com.chenlb.mmseg4j.MMSeg; import com.chenlb.mmseg4j.Seg; import com.chenlb.mmseg4j.Word; /** * 基于com.chenlb.mmseg4j的分词实现 * * @author Halo9Pan * */ public abstract class MMSegSegment implements ISegment { private static Logger logger = LoggerFactory.getLogger(MMSegSegment.class); protected Dictionary dict; public MMSegSegment() { this.dict = Dictionary.getInstance(); } /** * 返回com.chenlb.mmseg4j不同的分词实现 * * @return */ protected abstract Seg initializeSeg(); /* * (non-Javadoc) * * @see com.iqiyi.lego.tags.seg.ISegment#segWords(java.lang.String) */ public List<String> segWords(String content) { Reader reader = new StringReader(content); List<String> list = this.segWords(reader); return list; } /* * (non-Javadoc) * * @see info.inkstack.troll.seg.ISegment#segWords(java.io.File) */ public List<String> segWords(File file) throws FileNotFoundException { Reader reader = new FileReader(file); List<String> list = this.segWords(reader); return list; } private List<String> segWords(Reader reader) { List<String> list = new ArrayList<String>(); Seg seg = this.initializeSeg(); // 取得不同的分词具体算法 MMSeg mmSeg = new MMSeg(reader, seg); Word word = null; try { while ((word = mmSeg.next()) != null) { String w = word.getString(); list.add(w); } } catch (IOException e) { logger.warn("Exception when segging words.", e); } return list; } }
28.942857
82
0.701218
9f7cc58fb553c49ef5c5eef1cd35c836b2e94c88
1,300
package dev.jlibra.client.jsonrpc; import dev.jlibra.client.views.Account; import dev.jlibra.client.views.CurrencyInfo; import dev.jlibra.client.views.event.Event; import dev.jlibra.client.views.BlockMetadata; import dev.jlibra.client.views.StateProof; import dev.jlibra.client.views.transaction.Transaction; public enum JsonRpcMethod { GET_ACCOUNT(Account.class, false, true), GET_METADATA(BlockMetadata.class, false, false), GET_TRANSACTIONS(Transaction.class, true, false), GET_ACCOUNT_TRANSACTIONS(Transaction.class, true, false), GET_ACCOUNT_TRANSACTION(Transaction.class, false, true), GET_EVENTS(Event.class, true, false), GET_STATE_PROOF(StateProof.class, false, true), GET_CURRENCIES(CurrencyInfo.class, true, false), SUBMIT(Void.class, false, false); private Class resultType; private boolean listResult; private boolean optional; private JsonRpcMethod(Class resultType, boolean listResult, boolean optional) { this.resultType = resultType; this.listResult = listResult; this.optional = optional; } public Class resultType() { return resultType; } public boolean isOptional() { return optional; } public boolean isListResult() { return listResult; } }
28.888889
83
0.725385
4ca9a9b82e38b8634edb8eb486fbe3d7831599d1
27,120
/* * 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.carbondata.processing.store; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.carbondata.common.logging.LogServiceFactory; import org.apache.carbondata.core.constants.CarbonCommonConstants; import org.apache.carbondata.core.constants.CarbonV3DataFormatConstants; import org.apache.carbondata.core.datastore.compression.SnappyCompressor; import org.apache.carbondata.core.datastore.exception.CarbonDataWriterException; import org.apache.carbondata.core.datastore.row.CarbonRow; import org.apache.carbondata.core.datastore.row.WriteStepRowUtil; import org.apache.carbondata.core.keygenerator.KeyGenException; import org.apache.carbondata.core.metadata.ColumnarFormatVersion; import org.apache.carbondata.core.metadata.datatype.DataType; import org.apache.carbondata.core.metadata.datatype.DataTypes; import org.apache.carbondata.core.metadata.schema.table.column.CarbonDimension; import org.apache.carbondata.core.util.CarbonProperties; import org.apache.carbondata.core.util.CarbonThreadFactory; import org.apache.carbondata.processing.datatypes.GenericDataType; import org.apache.carbondata.processing.store.writer.CarbonFactDataWriter; import org.apache.log4j.Logger; /** * Fact data handler class to handle the fact data */ public class CarbonFactDataHandlerColumnar implements CarbonFactHandler { /** * LOGGER */ private static final Logger LOGGER = LogServiceFactory.getLogService(CarbonFactDataHandlerColumnar.class.getName()); private CarbonFactDataHandlerModel model; /** * data writer */ private CarbonFactDataWriter dataWriter; /** * total number of entries in blocklet */ private int entryCount; /** * blocklet size (for V1 and V2) or page size (for V3). A Producer thread will start to process * once this size of input is reached */ private int pageSize; private long processedDataCount; private ExecutorService producerExecutorService; private List<Future<Void>> producerExecutorServiceTaskList; private ExecutorService consumerExecutorService; private List<Future<Void>> consumerExecutorServiceTaskList; private List<CarbonRow> dataRows; private int[] noDictColumnPageSize; /** * semaphore which will used for managing node holder objects */ private Semaphore semaphore; /** * counter that incremented for every job submitted to data writer thread */ private int writerTaskSequenceCounter; /** * a private class that will hold the data for blocklets */ private TablePageList tablePageList; /** * number of cores configured */ private int numberOfCores; /** * integer that will be incremented for every new blocklet submitted to producer for processing * the data and decremented every time consumer fetches the blocklet for writing */ private AtomicInteger blockletProcessingCount; /** * flag to check whether all blocklets have been finished writing */ private boolean processingComplete; /** * current data format version */ private ColumnarFormatVersion version; /* * cannot use the indexMap of model directly, * modifying map in model directly will create problem if accessed later, * Hence take a copy and work on it. * */ private Map<Integer, GenericDataType> complexIndexMapCopy = null; /* configured page size in MB*/ private int configuredPageSizeInBytes = 0; /** * CarbonFactDataHandler constructor */ public CarbonFactDataHandlerColumnar(CarbonFactDataHandlerModel model) { this.model = model; initParameters(model); this.version = CarbonProperties.getInstance().getFormatVersion(); StringBuffer noInvertedIdxCol = new StringBuffer(); for (CarbonDimension cd : model.getSegmentProperties().getDimensions()) { if (!cd.isUseInvertedIndex()) { noInvertedIdxCol.append(cd.getColName()).append(","); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Columns considered as NoInverted Index are " + noInvertedIdxCol.toString()); } this.complexIndexMapCopy = new HashMap<>(); for (Map.Entry<Integer, GenericDataType> entry: model.getComplexIndexMap().entrySet()) { this.complexIndexMapCopy.put(entry.getKey(), entry.getValue().deepCopy()); } String pageSizeStrInBytes = model.getTableSpec().getCarbonTable().getTableInfo().getFactTable().getTableProperties() .get(CarbonCommonConstants.TABLE_PAGE_SIZE_INMB); if (pageSizeStrInBytes != null) { configuredPageSizeInBytes = Integer.parseInt(pageSizeStrInBytes) * 1024 * 1024; } } private void initParameters(CarbonFactDataHandlerModel model) { this.numberOfCores = model.getNumberOfCores(); blockletProcessingCount = new AtomicInteger(0); producerExecutorService = Executors.newFixedThreadPool(model.getNumberOfCores(), new CarbonThreadFactory( String.format("ProducerPool:%s, range: %d", model.getTableName(), model.getBucketId()), true)); producerExecutorServiceTaskList = new ArrayList<>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE); LOGGER.debug("Initializing writer executors"); consumerExecutorService = Executors.newFixedThreadPool(1, new CarbonThreadFactory( String.format("ConsumerPool:%s, range: %d", model.getTableName(), model.getBucketId()), true)); consumerExecutorServiceTaskList = new ArrayList<>(1); semaphore = new Semaphore(numberOfCores); tablePageList = new TablePageList(); // Start the consumer which will take each blocklet/page in order and write to a file Consumer consumer = new Consumer(tablePageList); consumerExecutorServiceTaskList.add(consumerExecutorService.submit(consumer)); } private void setComplexMapSurrogateIndex(int dimensionCount) { int surrIndex = 0; for (int i = 0; i < dimensionCount; i++) { GenericDataType complexDataType = model.getComplexIndexMap().get(i); if (complexDataType != null) { List<GenericDataType> primitiveTypes = new ArrayList<GenericDataType>(); complexDataType.getAllPrimitiveChildren(primitiveTypes); for (GenericDataType eachPrimitive : primitiveTypes) { if (eachPrimitive.getIsColumnDictionary()) { eachPrimitive.setSurrogateIndex(surrIndex++); } } } else { surrIndex++; } } } /** * This method will be used to get and update the step properties which will * required to run this step * * @throws CarbonDataWriterException */ public void initialise() throws CarbonDataWriterException { setWritingConfiguration(); } /** * below method will be used to add row to store * * @param row * @throws CarbonDataWriterException */ public void addDataToStore(CarbonRow row) throws CarbonDataWriterException { int totalComplexColumnDepth = setFlatCarbonRowForComplex(row); if (noDictColumnPageSize == null) { // initialization using first row. model.setNoDictAllComplexColumnDepth(totalComplexColumnDepth); if (model.getNoDictDataTypesList().size() + model.getNoDictAllComplexColumnDepth() > 0) { noDictColumnPageSize = new int[model.getNoDictDataTypesList().size() + model.getNoDictAllComplexColumnDepth()]; } } dataRows.add(row); this.entryCount++; // if entry count reaches to leaf node size then we are ready to write // this to leaf node file and update the intermediate files if (this.entryCount == this.pageSize || needToCutThePage(row)) { try { semaphore.acquire(); producerExecutorServiceTaskList.add( producerExecutorService.submit( new Producer(tablePageList, dataRows, ++writerTaskSequenceCounter, false) ) ); blockletProcessingCount.incrementAndGet(); // set the entry count to zero processedDataCount += entryCount; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Total Number Of records added to store: " + processedDataCount); } dataRows = new ArrayList<>(this.pageSize); this.entryCount = 0; // re-init the complexIndexMap this.complexIndexMapCopy = new HashMap<>(); for (Map.Entry<Integer, GenericDataType> entry : model.getComplexIndexMap().entrySet()) { this.complexIndexMapCopy.put(entry.getKey(), entry.getValue().deepCopy()); } noDictColumnPageSize = new int[model.getNoDictDataTypesList().size() + model.getNoDictAllComplexColumnDepth()]; } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); throw new CarbonDataWriterException(e); } } } /** * Check if column page can be added more rows after adding this row to page. * only few no-dictionary dimensions columns (string, varchar, * complex columns) can grow huge in size. * * * @param row carbonRow * @return false if next rows can be added to same page. * true if next rows cannot be added to same page */ private boolean needToCutThePage(CarbonRow row) { List<DataType> noDictDataTypesList = model.getNoDictDataTypesList(); int totalNoDictPageCount = noDictDataTypesList.size() + model.getNoDictAllComplexColumnDepth(); if (totalNoDictPageCount > 0) { int currentElementLength; int bucketCounter = 0; if (configuredPageSizeInBytes == 0) { // no need to cut the page // use default value /*configuredPageSizeInBytes = CarbonCommonConstants.TABLE_PAGE_SIZE_INMB_DEFAULT * 1024 * 1024;*/ return false; } Object[] nonDictArray = WriteStepRowUtil.getNoDictAndComplexDimension(row); for (int i = 0; i < noDictDataTypesList.size(); i++) { DataType columnType = noDictDataTypesList.get(i); if ((columnType == DataTypes.STRING) || (columnType == DataTypes.VARCHAR) || (columnType == DataTypes.BINARY)) { currentElementLength = ((byte[]) nonDictArray[i]).length; noDictColumnPageSize[bucketCounter] += currentElementLength; canSnappyHandleThisRow(noDictColumnPageSize[bucketCounter]); // If current page size is more than configured page size, cut the page here. if (noDictColumnPageSize[bucketCounter] + dataRows.size() * 4 >= configuredPageSizeInBytes) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("cutting the page. Rows count in this page: " + dataRows.size()); } // re-init for next page noDictColumnPageSize = new int[totalNoDictPageCount]; return true; } bucketCounter++; } else if (columnType.isComplexType()) { // this is for depth of each complex column, model is having only total depth. GenericDataType genericDataType = complexIndexMapCopy .get(i - model.getNoDictionaryCount() + model.getPrimitiveDimLens().length); int depth = genericDataType.getDepth(); List<ArrayList<byte[]>> flatComplexColumnList = (List<ArrayList<byte[]>>) nonDictArray[i]; for (int k = 0; k < depth; k++) { ArrayList<byte[]> children = flatComplexColumnList.get(k); // Add child element from inner list. int complexElementSize = 0; for (byte[] child : children) { complexElementSize += child.length; } noDictColumnPageSize[bucketCounter] += complexElementSize; canSnappyHandleThisRow(noDictColumnPageSize[bucketCounter]); // If current page size is more than configured page size, cut the page here. if (noDictColumnPageSize[bucketCounter] + dataRows.size() * 4 >= configuredPageSizeInBytes) { LOGGER.info("cutting the page. Rows count: " + dataRows.size()); // re-init for next page noDictColumnPageSize = new int[totalNoDictPageCount]; return true; } bucketCounter++; } } } } return false; } private int setFlatCarbonRowForComplex(CarbonRow row) { int noDictTotalComplexChildDepth = 0; Object[] noDictAndComplexDimension = WriteStepRowUtil.getNoDictAndComplexDimension(row); for (int i = 0; i < noDictAndComplexDimension.length; i++) { // complex types starts after no dictionary dimensions if (i >= model.getNoDictionaryCount() && (model.getTableSpec().getNoDictionaryDimensionSpec() .get(i).getSchemaDataType().isComplexType())) { // this is for depth of each complex column, model is having only total depth. GenericDataType genericDataType = complexIndexMapCopy .get(i - model.getNoDictionaryCount() + model.getPrimitiveDimLens().length); int depth = genericDataType.getDepth(); // initialize flatComplexColumnList List<ArrayList<byte[]>> flatComplexColumnList = new ArrayList<>(depth); for (int k = 0; k < depth; k++) { flatComplexColumnList.add(new ArrayList<byte[]>()); } // flatten the complex byteArray as per depth try { ByteBuffer byteArrayInput = ByteBuffer.wrap((byte[])noDictAndComplexDimension[i]); ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutput); genericDataType.parseComplexValue(byteArrayInput, dataOutputStream, model.getComplexDimensionKeyGenerator()); genericDataType.getColumnarDataForComplexType(flatComplexColumnList, ByteBuffer.wrap(byteArrayOutput.toByteArray())); byteArrayOutput.close(); } catch (IOException | KeyGenException e) { throw new CarbonDataWriterException("Problem in splitting and writing complex data", e); } noDictTotalComplexChildDepth += flatComplexColumnList.size(); // update the complex column data with the flat data noDictAndComplexDimension[i] = flatComplexColumnList; } } return noDictTotalComplexChildDepth; } private void canSnappyHandleThisRow(int currentRowSize) { if (currentRowSize > SnappyCompressor.MAX_BYTE_TO_COMPRESS) { throw new RuntimeException(" page size: " + currentRowSize + " exceed snappy size: " + SnappyCompressor.MAX_BYTE_TO_COMPRESS + " Bytes. Snappy cannot compress it "); } } /** * generate the EncodedTablePage from the input rows (one page in case of V3 format) */ private TablePage processDataRows(List<CarbonRow> dataRows) throws CarbonDataWriterException, IOException { if (dataRows.size() == 0) { return new TablePage(model, 0); } TablePage tablePage = new TablePage(model, dataRows.size()); int rowId = 0; // convert row to columnar data for (CarbonRow row : dataRows) { tablePage.addRow(rowId++, row); } tablePage.encode(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Number Of records processed: " + dataRows.size()); } return tablePage; } /** * below method will be used to finish the data handler * * @throws CarbonDataWriterException */ public void finish() throws CarbonDataWriterException { // still some data is present in stores if entryCount is more // than 0 if (null == dataWriter) { return; } if (producerExecutorService.isShutdown()) { return; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Started Finish Operation"); } try { semaphore.acquire(); producerExecutorServiceTaskList.add(producerExecutorService .submit(new Producer(tablePageList, dataRows, ++writerTaskSequenceCounter, true))); blockletProcessingCount.incrementAndGet(); processedDataCount += entryCount; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Total Number Of records added to store: " + processedDataCount); } closeWriterExecutionService(producerExecutorService); processWriteTaskSubmitList(producerExecutorServiceTaskList); processingComplete = true; } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); throw new CarbonDataWriterException(e); } } /** * This method will close writer execution service and get the node holders and * add them to node holder list * * @param service the service to shutdown * @throws CarbonDataWriterException */ private void closeWriterExecutionService(ExecutorService service) throws CarbonDataWriterException { try { service.shutdown(); service.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); throw new CarbonDataWriterException(e); } } /** * This method will iterate through future task list and check if any exception * occurred during the thread execution * * @param taskList * @throws CarbonDataWriterException */ private void processWriteTaskSubmitList(List<Future<Void>> taskList) throws CarbonDataWriterException { for (int i = 0; i < taskList.size(); i++) { try { taskList.get(i).get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error(e.getMessage(), e); throw new CarbonDataWriterException(e); } } } // return the number of complex column after complex columns are expanded private int getExpandedComplexColsCount() { return model.getExpandedComplexColsCount(); } /** * below method will be used to close the handler */ public void closeHandler() throws CarbonDataWriterException { if (null != this.dataWriter) { // wait until all blocklets have been finished writing while (blockletProcessingCount.get() > 0) { try { Thread.sleep(50); } catch (InterruptedException e) { throw new CarbonDataWriterException(e); } } consumerExecutorService.shutdownNow(); processWriteTaskSubmitList(consumerExecutorServiceTaskList); this.dataWriter.writeFooter(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("All blocklets have been finished writing"); } // close all the open stream for both the files this.dataWriter.closeWriter(); } this.dataWriter = null; } /** * Below method will be to configure fact file writing configuration * * @throws CarbonDataWriterException */ private void setWritingConfiguration() throws CarbonDataWriterException { // get blocklet size this.pageSize = Integer.parseInt(CarbonProperties.getInstance() .getProperty(CarbonCommonConstants.BLOCKLET_SIZE, CarbonCommonConstants.BLOCKLET_SIZE_DEFAULT_VAL)); // support less than 32000 rows in one page, because we support super long string, // if it is long enough, a column page with 32000 rows will exceed 2GB if (version == ColumnarFormatVersion.V3) { this.pageSize = pageSize < CarbonV3DataFormatConstants.NUMBER_OF_ROWS_PER_BLOCKLET_COLUMN_PAGE_DEFAULT ? pageSize : CarbonV3DataFormatConstants.NUMBER_OF_ROWS_PER_BLOCKLET_COLUMN_PAGE_DEFAULT; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Number of rows per column page is configured as pageSize = " + pageSize); } dataRows = new ArrayList<>(this.pageSize); setComplexMapSurrogateIndex(model.getDimensionCount()); this.dataWriter = getFactDataWriter(); // initialize the channel; this.dataWriter.initializeWriter(); } /** * This method combines primitive dimensions with complex metadata columns * * @param primitiveBlockKeySize * @return all dimensions cardinality including complex dimension metadata column */ private int[] getBlockKeySizeWithComplexTypes(int[] primitiveBlockKeySize) { int allColsCount = getExpandedComplexColsCount(); int[] blockKeySizeWithComplexTypes = new int[allColsCount]; List<Integer> blockKeySizeWithComplex = new ArrayList<Integer>(blockKeySizeWithComplexTypes.length); int dictDimensionCount = model.getDimensionCount(); for (int i = 0; i < dictDimensionCount; i++) { GenericDataType complexDataType = model.getComplexIndexMap().get(i); if (complexDataType != null) { complexDataType.fillBlockKeySize(blockKeySizeWithComplex, primitiveBlockKeySize); } else { blockKeySizeWithComplex.add(primitiveBlockKeySize[i]); } } for (int i = 0; i < blockKeySizeWithComplexTypes.length; i++) { blockKeySizeWithComplexTypes[i] = blockKeySizeWithComplex.get(i); } return blockKeySizeWithComplexTypes; } /** * Below method will be used to get the fact data writer instance * * @return data writer instance */ private CarbonFactDataWriter getFactDataWriter() { return CarbonDataWriterFactory.getInstance().getFactDataWriter(version, model); } /** * This method will reset the block processing count */ private void resetBlockletProcessingCount() { blockletProcessingCount.set(0); } /** * This class will hold the table page data */ private final class TablePageList { /** * array of table page added by Producer and get by Consumer */ private TablePage[] tablePages; /** * flag to check whether the producer has completed processing for holder * object which is required to be picked form an index */ private AtomicBoolean available; /** * index from which data node holder object needs to be picked for writing */ private int currentIndex; private TablePageList() { tablePages = new TablePage[numberOfCores]; available = new AtomicBoolean(false); } /** * @return a node holder object * @throws InterruptedException if consumer thread is interrupted */ public synchronized TablePage get() throws InterruptedException { TablePage tablePage = tablePages[currentIndex]; // if node holder is null means producer thread processing the data which has to // be inserted at this current index has not completed yet if (null == tablePage && !processingComplete) { available.set(false); } while (!available.get()) { wait(); } tablePage = tablePages[currentIndex]; tablePages[currentIndex] = null; currentIndex++; // reset current index when it reaches length of node holder array if (currentIndex >= tablePages.length) { currentIndex = 0; } return tablePage; } /** * @param tablePage * @param index */ public synchronized void put(TablePage tablePage, int index) { tablePages[index] = tablePage; // notify the consumer thread when index at which object is to be inserted // becomes equal to current index from where data has to be picked for writing if (index == currentIndex) { available.set(true); notifyAll(); } } } /** * Producer which will process data equivalent to 1 blocklet size */ private final class Producer implements Callable<Void> { private TablePageList tablePageList; private List<CarbonRow> dataRows; private int pageId; private boolean isLastPage; private Producer(TablePageList tablePageList, List<CarbonRow> dataRows, int pageId, boolean isLastPage) { this.tablePageList = tablePageList; this.dataRows = dataRows; this.pageId = pageId; this.isLastPage = isLastPage; } /** * Computes a result, or throws an exception if unable to do so. * * @return computed result */ @Override public Void call() { try { TablePage tablePage = processDataRows(dataRows); dataRows = null; tablePage.setIsLastPage(isLastPage); // insert the object in array according to sequence number int indexInNodeHolderArray = (pageId - 1) % numberOfCores; tablePageList.put(tablePage, indexInNodeHolderArray); return null; } catch (Throwable throwable) { LOGGER.error("Error in producer", throwable); consumerExecutorService.shutdownNow(); resetBlockletProcessingCount(); throw new CarbonDataWriterException(throwable.getMessage(), throwable); } } } /** * Consumer class will get one blocklet data at a time and submit for writing */ private final class Consumer implements Callable<Void> { private TablePageList tablePageList; private Consumer(TablePageList tablePageList) { this.tablePageList = tablePageList; } /** * Computes a result, or throws an exception if unable to do so. * * @return computed result */ @Override public Void call() { while (!processingComplete || blockletProcessingCount.get() > 0) { TablePage tablePage = null; try { tablePage = tablePageList.get(); if (null != tablePage) { dataWriter.writeTablePage(tablePage); tablePage.freeMemory(); } blockletProcessingCount.decrementAndGet(); } catch (Throwable throwable) { if (!processingComplete || blockletProcessingCount.get() > 0) { producerExecutorService.shutdownNow(); resetBlockletProcessingCount(); LOGGER.error("Problem while writing the carbon data file", throwable); throw new CarbonDataWriterException(throwable); } } finally { semaphore.release(); } } return null; } } }
37.303989
100
0.688532
8fdbbe730959e627dedd2b07a2379fc33710341a
8,916
/* * 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.flink.streaming.connectors.kafka; import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.io.ratelimiting.FlinkConnectorRateLimiter; import org.apache.flink.api.common.io.ratelimiting.GuavaFlinkConnectorRateLimiter; import org.apache.flink.api.common.restartstrategy.RestartStrategies; import org.apache.flink.api.common.serialization.SimpleStringSchema; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.common.typeinfo.Types; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.core.memory.DataInputView; import org.apache.flink.core.memory.DataInputViewStreamWrapper; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.sink.DiscardingSink; import org.apache.flink.streaming.api.functions.source.SourceFunction; import org.apache.flink.streaming.util.serialization.KeyedDeserializationSchema; import org.junit.Assert; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Properties; /** * IT cases for Kafka 0.9 . */ public class Kafka09ITCase extends KafkaConsumerTestBase { // ------------------------------------------------------------------------ // Suite of Tests // ------------------------------------------------------------------------ @Test(timeout = 60000) public void testFailOnNoBroker() throws Exception { runFailOnNoBrokerTest(); } @Test(timeout = 60000) public void testConcurrentProducerConsumerTopology() throws Exception { runSimpleConcurrentProducerConsumerTopology(); } @Test(timeout = 60000) public void testKeyValueSupport() throws Exception { runKeyValueTest(); } // --- canceling / failures --- @Test(timeout = 60000) public void testCancelingEmptyTopic() throws Exception { runCancelingOnEmptyInputTest(); } @Test(timeout = 60000) public void testCancelingFullTopic() throws Exception { runCancelingOnFullInputTest(); } // --- source to partition mappings and exactly once --- @Test(timeout = 60000) public void testOneToOneSources() throws Exception { runOneToOneExactlyOnceTest(); } @Test(timeout = 60000) public void testOneSourceMultiplePartitions() throws Exception { runOneSourceMultiplePartitionsExactlyOnceTest(); } @Test(timeout = 60000) public void testMultipleSourcesOnePartition() throws Exception { runMultipleSourcesOnePartitionExactlyOnceTest(); } // --- broker failure --- @Test(timeout = 60000) public void testBrokerFailure() throws Exception { runBrokerFailureTest(); } // --- special executions --- @Test(timeout = 60000) public void testBigRecordJob() throws Exception { runBigRecordTestTopology(); } @Test(timeout = 60000) public void testMultipleTopics() throws Exception { runProduceConsumeMultipleTopics(true); } @Test(timeout = 60000) public void testAllDeletes() throws Exception { runAllDeletesTest(); } @Test(timeout = 60000) public void testEndOfStream() throws Exception { runEndOfStreamTest(); } @Test(timeout = 60000) public void testMetrics() throws Throwable { runMetricsTest(); } // --- startup mode --- @Test(timeout = 60000) public void testStartFromEarliestOffsets() throws Exception { runStartFromEarliestOffsets(); } @Test(timeout = 60000) public void testStartFromLatestOffsets() throws Exception { runStartFromLatestOffsets(); } @Test(timeout = 60000) public void testStartFromGroupOffsets() throws Exception { runStartFromGroupOffsets(); } @Test(timeout = 60000) public void testStartFromSpecificOffsets() throws Exception { runStartFromSpecificOffsets(); } // --- offset committing --- @Test(timeout = 60000) public void testCommitOffsetsToKafka() throws Exception { runCommitOffsetsToKafka(); } @Test(timeout = 60000) public void testAutoOffsetRetrievalAndCommitToKafka() throws Exception { runAutoOffsetRetrievalAndCommitToKafka(); } /** * Kafka09 specific RateLimiter test. This test produces 100 bytes of data to a test topic * and then runs a job with {@link FlinkKafkaConsumer09} as the source and a {@link GuavaFlinkConnectorRateLimiter} with * a desired rate of 3 bytes / second. Based on the execution time, the test asserts that this rate was not surpassed. * If no rate limiter is set on the consumer, the test should fail. */ @Test(timeout = 60000) public void testRateLimitedConsumer() throws Exception { final String testTopic = "testRateLimitedConsumer"; createTestTopic(testTopic, 3, 1); // ---------- Produce a stream into Kafka ------------------- StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); env.getConfig().setRestartStrategy(RestartStrategies.noRestart()); env.getConfig().disableSysoutLogging(); DataStream<String> stream = env.addSource(new SourceFunction<String>() { private static final long serialVersionUID = 1L; boolean running = true; @Override public void run(SourceContext<String> ctx) { long i = 0; while (running) { byte[] data = new byte[] {1}; synchronized (ctx.getCheckpointLock()) { ctx.collect(new String(data)); // 1 byte } if (i++ == 100L) { running = false; } } } @Override public void cancel() { running = false; } }); Properties producerProperties = new Properties(); producerProperties.putAll(standardProps); producerProperties.putAll(secureProps); producerProperties.put("retries", 3); stream.addSink(new FlinkKafkaProducer09<>(testTopic, new SimpleStringSchema(), producerProperties)); env.execute("Produce 100 bytes of data to test topic"); // ---------- Consumer from Kafka in a ratelimited way ----------- env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); env.getConfig().setRestartStrategy(RestartStrategies.noRestart()); env.getConfig().disableSysoutLogging(); // ---------- RateLimiter config ------------- final long globalRate = 10; // bytes/second FlinkKafkaConsumer09<String> consumer09 = new FlinkKafkaConsumer09<>(testTopic, new StringDeserializer(globalRate), standardProps); FlinkConnectorRateLimiter rateLimiter = new GuavaFlinkConnectorRateLimiter(); rateLimiter.setRate(globalRate); consumer09.setRateLimiter(rateLimiter); DataStream<String> stream1 = env.addSource(consumer09); stream1.addSink(new DiscardingSink<>()); env.execute("Consume 100 bytes of data from test topic"); // ------- Assertions -------------- Assert.assertNotNull(consumer09.getRateLimiter()); Assert.assertEquals(globalRate, consumer09.getRateLimiter().getRate()); deleteTestTopic(testTopic); } private static class StringDeserializer implements KeyedDeserializationSchema<String> { private static final long serialVersionUID = 1L; private final TypeInformation<String> ti; private final TypeSerializer<String> ser; long cnt = 0; long startTime; long endTime; long globalRate; public StringDeserializer(long rate) { this.ti = Types.STRING; this.ser = ti.createSerializer(new ExecutionConfig()); this.startTime = System.currentTimeMillis(); this.globalRate = rate; } @Override public TypeInformation<String> getProducedType() { return ti; } @Override public String deserialize(byte[] messageKey, byte[] message, String topic, int partition, long offset) throws IOException { cnt++; DataInputView in = new DataInputViewStreamWrapper(new ByteArrayInputStream(message)); String e = ser.deserialize(in); return e; } @Override public boolean isEndOfStream(String nextElement) { if (cnt > 100L) { endTime = System.currentTimeMillis(); // Approximate bytes/second read based on job execution time. long bytesPerSecond = 100 * 1000L / (endTime - startTime); Assert.assertTrue(bytesPerSecond > 0); Assert.assertTrue(bytesPerSecond <= globalRate); return true; } return false; } } }
31.284211
121
0.733401
bfb2566dce76debf01948ae3fa8ab212c6d4ac24
2,476
/* * Copyright 2013 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mortar; import android.os.Bundle; /** * A specialized scope that provides access to the Android Activity life cycle's persistence * bundle. */ public interface MortarActivityScope extends MortarScope { /** * <p>Extends {@link MortarScope#register(Scoped)} to register {@link Bundler} instances to have * {@link Bundler#onLoad} and {@link Bundler#onSave} called from {@link #onCreate} and {@link * #onSaveInstanceState}, respectively. * * <p>In addition to the calls from {@link #onCreate}, {@link Bundler#onLoad} is triggered by * registration. In most cases that initial {@link Bundler#onLoad} is made synchronously during * registration. However, if a {@link Bundler} is registered while an ancestor scope is loading * its own {@link Bundler}s, its {@link Bundler#onLoad} will be deferred until all ancestor * scopes have completed loading. This ensures that a {@link Bundler} can assume that any * dependency registered with a higher-level scope will have been initialized before its own * {@link Bundler#onLoad} method fires. * * <p>A redundant call to this method does not create a duplicate registration, but does trigger * another call to {@link Bundler#onLoad}. */ @Override void register(Scoped s); /** * To be called from the host {@link android.app.Activity}'s {@link * android.app.Activity#onCreate}. Calls the registered {@link Bundler}'s {@link Bundler#onLoad} * methods. To avoid redundant calls to {@link Presenter#onLoad} it's best to call this before * {@link android.app.Activity#setContentView}. */ void onCreate(Bundle savedInstanceState); /** * To be called from the host {@link android.app.Activity}'s {@link * android.app.Activity#onSaveInstanceState}. Calls the registrants' {@link Bundler#onSave} * methods. */ void onSaveInstanceState(Bundle outState); }
42.689655
98
0.725767
af93e5c9fabb2bd8924bcaf2b962edeb844870ad
1,597
package io.castle.client.model; import java.util.Properties; import io.castle.client.Castle; import io.castle.client.internal.config.PropertiesReader; import java.io.InputStream; /** * The reference to the current version of the SDK. */ public class CastleSdkRef { private String name = "castle-java"; private String version; private String platform; private String platformVersion; CastleSdkRef() { this.version = loadSdkVersion().getProperty("sdk.version"); this.platformVersion = getJavaVersion(); this.platform = getJavaPlatform(); } public String getName() { return name; } public String getVersion() { return version; } @Override public String toString() { return "CastleSdkRef{" + "name='" + name + '\'' + ", version='" + version + '\'' + ", platform='" + platform + '\'' + ", platformVersion='" + platformVersion + '\'' + '}'; } private Properties loadSdkVersion() { Properties versionProperties = new Properties(); PropertiesReader reader = new PropertiesReader(); InputStream resourceAsStream = Castle.class.getClassLoader().getResourceAsStream("version.properties"); return reader.loadPropertiesFromStream(versionProperties, resourceAsStream); } public static String getJavaVersion() { return System.getProperty("java.vm.version"); } public static String getJavaPlatform() { return System.getProperty("java.vm.name"); } }
28.017544
111
0.629931
f3d7a65c8527af00cb821657381496b64cf7e2de
12,460
package com.sailvan.easyexcel.test; import java.lang.reflect.Field; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.usermodel.Workbook; import org.junit.Test; import com.alibaba.fastjson.JSONObject; import com.sailvan.excel.EasyExcelUtil; import com.sailvan.excel.annotation.ExcelProperty; import com.sailvan.excel.context.AnalysisContext; import com.sailvan.excel.event.AnalysisEventListener; import com.sailvan.excel.event.WriteHandler; import com.sailvan.excel.metadata.BaseRowModel; import com.sailvan.excel.metadata.WriteInfo; import com.sailvan.excel.metadata.typeconvertor.AccountTypeConvertor; import com.sailvan.excel.metadata.typeconvertor.JsonTypeConvertor; /** * <p>easy excel demo</p> * * easyExcel 核心功能 * * 读任意大小的03、07版Excel不会OOM * 读Excel自动通过注解,把结果映射为java模型 * 读Excel时候是否对Excel内容做trim()增加容错 * 读Excel支持自定义行级回调,每读一行数据后进行自定义数据操作 * * 写任意大07版Excel不会OOM * 写Excel通过注解将JavaBean自动写入Excel * 写Excel可以自定义Excel样式 如:字体,加粗,表头颜色,数据内容颜色 * 写Excel支持sheet,row,cell级别的写入回调,可高度自定义写入样式 * Sheet提供多个自定义接口 * * 写入效率较之前提升30%左右 * * @author wujiaming * @version 1.0 * @since 2019/1/6 19:50 */ public class DemoTest { /** * 常用读取excel方式 */ @Test public void read() { List<List<String>> list = EasyExcelUtil.read("C:\\Users\\Draher\\Desktop\\sku_status_import_template.xlsx"); System.out.println(list.size()); } /** * 通过model读取excel */ @Test public void readByModel() { List<SkuStatusTO> list = EasyExcelUtil.read("C:\\Users\\Draher\\Desktop\\writeModel.xlsx", SkuStatusTO.class); System.out.println(list.size()); } /** * 自定义回调样式,实现AnalysisEventListener即可 */ @Test public void readByListen() { final List<String> lists = new ArrayList<String>(); EasyExcelUtil.read("C:\\Users\\Draher\\Desktop\\sku_status_import_template.xlsx", new AnalysisEventListener() { @Override @SuppressWarnings("unchecked") public void invoke(Object o, AnalysisContext analysisContext) { JSONObject obj = new JSONObject(); List<String> values = (List<String>) o; List<String> titles = Arrays.asList("plat", "wh", "account", "site", "spu", "sku", "onlineSku", "status", "reason"); for (int i = 0; i < titles.size(); i++) { obj.put(titles.get(i), values.get(i)); } lists.add(obj.toJSONString()); } @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { System.out.println(lists.size()); } }); } @Test public void writeByList() { List<List<Object>> list = new ArrayList<List<Object>>(); for (int i = 0; i < 1000; i++) { List<Object> da = new ArrayList<Object>(); da.add("字符串222222222222222222222222" + i); da.add(187837834L + i); da.add(2233 + i); da.add(2233.01 + i); da.add(2233.2f + i); da.add(new Date()); da.add(new BigDecimal("3434343433554545555555" + i)); da.add((short) i); list.add(da); } long start = System.currentTimeMillis(); EasyExcelUtil.write(list, Arrays.asList("第一列", "第二列", "第三列"), "hello world", "C:\\Users\\Draher\\Desktop\\string.xlsx"); long end = System.currentTimeMillis(); System.out.println("run times:" + (end - start)); } /** * 通过javaBean写入数据 */ @Test public void writeByBean() { long start = System.currentTimeMillis(); List<SkuStatusTO> list = createJavaMode(); EasyExcelUtil.writeByBean(list, SkuStatusTO.class, "hello world", "C:\\Users\\Draher\\Desktop\\writeModel.xlsx"); long end = System.currentTimeMillis(); System.out.println("总运行时间:" + ( end - start)); } /** * 通过pi原先类似的方式写excel * 通过封装WriteInfo对象, WriteInfo只能通过构建器Build创建 * @throws IllegalAccessException */ @Test public void write() throws IllegalAccessException { EasyExcelUtil.write(new WriteInfo.Builder() .title(new String[]{"平台", "仓库", "账号", "站点", "spu", "sku", "在线sku", "在线状态", "原因"}) .sheetName("hello") .contentTitle(new String[]{"plat", "wh", "account", "site", "spu", "sku", "onlineSku", "status", "reason"}) .contentList(createDbMapData()) .build(), "C:\\Users\\Draher\\Desktop\\writeInfo.xlsx"); } /** * 写入添加回调,如可将cell值为fail的单元格置为红色等 * @throws IllegalAccessException */ @Test public void writeWithHandle() throws IllegalAccessException { WriteInfo writeInfo = new WriteInfo.Builder() .title(new String[]{"平台", "仓库", "账号", "站点", "spu", "sku", "在线sku", "在线状态", "原因"}) .sheetName("hello") .contentTitle(new String[]{"plat", "wh", "account", "site", "spu", "sku", "onlineSku", "status", "reason"}) .contentList(createDbMapData()) .build(); EasyExcelUtil.write(writeInfo, "C:\\Users\\Draher\\Desktop\\writeInfo.xlsx", new WriteHandler() { @Override public void sheet(int sheetNo, Sheet sheet) { } @Override public void row(int rowNum, Row row) { } @Override public void cell(int cellNum, Cell cell, Object cellValue) { Workbook workbook = cell.getSheet().getWorkbook(); if (cellNum == 8 && cell.getRowIndex() > 0 && cellValue.equals("success1")) { CellStyle newCellStyle = workbook.createCellStyle(); newCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); newCellStyle.setAlignment(HorizontalAlignment.CENTER); newCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); newCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cell.setCellStyle(newCellStyle); } } }); } private List<SkuStatusTO> createJavaMode() { List<SkuStatusTO> list = new ArrayList<SkuStatusTO>(); for (int i = 0; i < 1000; i++) { SkuStatusTO skuStatusTO = new SkuStatusTO(); skuStatusTO.setPlat("amazon" + i); skuStatusTO.setWh("fba" + i); skuStatusTO.setAccount("avidlove11111111111111111111111" + i); skuStatusTO.setAccountId(1); skuStatusTO.setSite("us" + i); skuStatusTO.setSpu("aaa" + i); skuStatusTO.setSku("bbb" + i); skuStatusTO.setOnlineSku("abab" + i); skuStatusTO.setStatus("ccc" + i); skuStatusTO.setReason("success" + i); skuStatusTO.setObject(new JSONObject(){{put("name", "测试");}}); skuStatusTO.setDate(new Date()); list.add(skuStatusTO); } return list; } private List<Map<String, Object>> createDbMapData() throws IllegalAccessException { return BeanConvertUtil.listBean2Map(createJavaMode()); } /** * 用法类似fastJson的类注解 * * @see com.sailvan.excel.annotation.ExcelProperty 注解 * * index 数值对应列,默认值为9999 * value 对应表头,表头可设置为单行表头,或者多行的复合表头 * convertor 属性可实现类型转换,如accountId -> Account, 或 JSONObject -> jsonString提供自定义接口,实现TypeConvertor即可 * 底层使用反射实现,使用可能会稍微影响一点程序性能 * 因为MVC设计原则,Model层不依赖与任何业务逻辑,如果需要实现acccountId -> account的转换,这里涉及到DAO层操作(因为需要查询数据库当前的account), * 则需要在service层创建一个专门处理excel的model类(推荐静态内部类),才可以添加转换的TypeConvertor * format 对日期类型进行转换 * ignore 可忽略无需解析的字段,一般配合ExcelProperty注解使用在类名的情况 * order 字段排序,底层原理是重设index属性的变量,注意必须包含全部需要写入的字段,不然会抛出RunTimeException * * 如果未在类名上添加注解,则会按照有加注解的成员变量和index属性进行写入excel(仅处理有ExcelProperty注解的field); * 如果在类名添加注解,则默认所有属性都将进行写入excel,未指定表头名称的(即value属性),则按字段名设置表头,index值为字段的默认排序。 * orders属性会重排字段的index数值。 * */ @ExcelProperty(orders = {"wh", "plat", "account", "accountId", "site", "spu", "sku", "onlineSku", "status", "reason", "object", "date"}) public static class SkuStatusTO extends BaseRowModel { @ExcelProperty(value = "平台") private String plat; @ExcelProperty(value = "仓库") private String wh; @ExcelProperty(value = "账号") private String account; @ExcelProperty(value = "账号Id", convertor = AccountTypeConvertor.class) private Integer accountId; @ExcelProperty(value = "站点") private String site; private String spu; private String sku; @ExcelProperty(value = "在线sku") private String onlineSku; @ExcelProperty(value = "在线状态") private String status; @ExcelProperty(value = "原因") private String reason; @ExcelProperty(value = "序列号", convertor = JsonTypeConvertor.class) private JSONObject object; @ExcelProperty(value = "时间", format = "yyyy-MM-dd") private Date date; public String getPlat() { return plat; } public void setPlat(String plat) { this.plat = plat; } public String getWh() { return wh; } public void setWh(String wh) { this.wh = wh; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public Integer getAccountId() { return accountId; } public void setAccountId(Integer accountId) { this.accountId = accountId; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public String getSpu() { return spu; } public void setSpu(String spu) { this.spu = spu; } public String getSku() { return sku; } public void setSku(String sku) { this.sku = sku; } public String getOnlineSku() { return onlineSku; } public void setOnlineSku(String onlineSku) { this.onlineSku = onlineSku; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public JSONObject getObject() { return object; } public void setObject(JSONObject object) { this.object = object; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } public static class BeanConvertUtil { public static <T> Map<String, Object> bean2Map(T bean) throws IllegalAccessException { Map<String, Object> map = new HashMap<String, Object>(); Class<?> clazz = bean.getClass(); // 获取所有字段(不包括父类) Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); map.put(field.getName(), field.get(bean)); } return map; } public static <T> List<Map<String, Object>> listBean2Map(List<T> beanList) throws IllegalAccessException { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (T t : beanList) { list.add(bean2Map(t)); } return list; } } }
32.363636
140
0.589406
f7379402dc2d0d9f5a62cb3295d522db3ddfd8d4
4,336
package io.virtualapp.sys; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.lody.virtual.client.ipc.VActivityManager; import com.lody.virtual.client.ipc.VPackageManager; import java.util.List; import io.virtualapp.R; /** * author: weishu on 18/3/16. */ public class ShareBridgeActivity extends AppCompatActivity { private SharedAdapter mAdapter; private List<ResolveInfo> mShareComponents; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); intent.setComponent(null); if (!Intent.ACTION_SEND.equals(action)) { finish(); return; } try { mShareComponents = VPackageManager.get(). queryIntentActivities(new Intent(Intent.ACTION_SEND), type, 0, 0); // multi-user? } catch (Throwable ignored) { } if (mShareComponents == null || mShareComponents.size() == 0) { finish(); return; } setContentView(R.layout.activity_list); ListView mListView = (ListView) findViewById(R.id.list); mAdapter = new SharedAdapter(); mListView.setAdapter(mAdapter); mListView.setOnItemClickListener((parent, view, position, id) -> { try { ResolveInfo item = mAdapter.getItem(position); Intent t = new Intent(intent); t.setComponent(new ComponentName(item.activityInfo.packageName, item.activityInfo.name)); VActivityManager.get().startActivity(t, 0); } catch (Throwable e) { Toast.makeText(getApplicationContext(), R.string.shared_to_vxp_failed, Toast.LENGTH_SHORT).show(); } finish(); }); } private class SharedAdapter extends BaseAdapter { @Override public int getCount() { return mShareComponents.size(); } @Override public ResolveInfo getItem(int position) { return mShareComponents.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(getActivity(), parent); convertView = holder.root; convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } ResolveInfo item = getItem(position); PackageManager packageManager = getPackageManager(); try { holder.label.setText(item.loadLabel(packageManager)); } catch (Throwable e) { holder.label.setText(R.string.package_state_unknown); } try { holder.icon.setImageDrawable(item.loadIcon(packageManager)); } catch (Throwable e) { holder.icon.setImageDrawable(getResources().getDrawable(android.R.drawable.sym_def_app_icon)); } return convertView; } } static class ViewHolder { ImageView icon; TextView label; View root; ViewHolder(Context context, ViewGroup parent) { root = LayoutInflater.from(context).inflate(R.layout.item_share, parent, false); icon = root.findViewById(R.id.item_share_icon); label = root.findViewById(R.id.item_share_name); } } private Activity getActivity() { return this; } }
30.751773
114
0.62131
71aeaf5e138622bdfb52b3e562a6feac1656b9d8
4,612
/* BrainMaze: A Maze-Solving Game Copyright (C) 2008-2012 Eric Ahnell Any questions should be directed to the author via email at: [email protected] */ package com.puttysoftware.brainmaze.objects; import com.puttysoftware.brainmaze.Application; import com.puttysoftware.brainmaze.BrainMaze; import com.puttysoftware.brainmaze.game.InfiniteRecursionException; import com.puttysoftware.brainmaze.game.ObjectInventory; import com.puttysoftware.brainmaze.generic.GenericMovableObject; import com.puttysoftware.brainmaze.generic.MazeObject; import com.puttysoftware.brainmaze.maze.MazeConstants; import com.puttysoftware.brainmaze.resourcemanagers.SoundConstants; import com.puttysoftware.brainmaze.resourcemanagers.SoundManager; public class Pit extends StairsDown { // Constructors public Pit() { super(true); } @Override public String getName() { return "Pit"; } @Override public String getPluralName() { return "Pits"; } @Override public boolean preMoveAction(final boolean ie, final int dirX, final int dirY, final ObjectInventory inv) { return this.searchNestedPits(dirX, dirY, BrainMaze.getApplication() .getMazeManager().getMaze().getPlayerLocationZ() - 1, inv); } private boolean searchNestedPits(final int dirX, final int dirY, final int floor, final ObjectInventory inv) { final Application app = BrainMaze.getApplication(); // Stop infinite recursion final int lcl = -app.getMazeManager().getMaze().getFloors(); if (floor <= lcl) { throw new InfiniteRecursionException(); } if (app.getGameManager().doesFloorExist(floor)) { final MazeObject obj = app.getMazeManager().getMaze().getCell(dirX, dirY, floor, MazeConstants.LAYER_OBJECT); if (obj.isConditionallySolid(inv)) { return false; } else { if (obj.getName().equals("Pit") || obj.getName().equals("Invisible Pit")) { return this.searchNestedPits(dirX, dirY, floor - 1, inv); } else if (obj.getName().equals("Springboard") || obj.getName().equals("Invisible Springboard")) { return false; } else { return true; } } } else { return false; } } @Override public void postMoveAction(final boolean ie, final int dirX, final int dirY, final ObjectInventory inv) { final Application app = BrainMaze.getApplication(); app.getGameManager().updatePositionAbsolute(this.getDestinationRow(), this.getDestinationColumn(), this.getDestinationFloor()); SoundManager.playSound(SoundConstants.SOUND_CATEGORY_SOLVING_MAZE, SoundConstants.SOUND_FALL_INTO_PIT); } @Override public void pushIntoAction(final ObjectInventory inv, final MazeObject pushed, final int x, final int y, final int z) { final Application app = BrainMaze.getApplication(); try { this.searchNestedPits(x, y, z - 1, inv); if (pushed.isPushable()) { final GenericMovableObject pushedInto = (GenericMovableObject) pushed; app.getGameManager().updatePushedIntoPositionAbsolute(x, y, z - 1, x, y, z, pushedInto, this); SoundManager.playSound( SoundConstants.SOUND_CATEGORY_SOLVING_MAZE, SoundConstants.SOUND_FALL_INTO_PIT); } } catch (final InfiniteRecursionException ir) { SoundManager.playSound(SoundConstants.SOUND_CATEGORY_SOLVING_MAZE, SoundConstants.SOUND_FALL_INTO_PIT); BrainMaze.getApplication().getMazeManager().getMaze() .setCell(new Empty(), x, y, z, MazeConstants.LAYER_OBJECT); } } @Override public boolean isConditionallySolid(final ObjectInventory inv) { final Application app = BrainMaze.getApplication(); if (!app.getGameManager().isFloorBelow()) { return true; } else { return false; } } @Override public void editorPlaceHook() { // Do nothing } @Override public String getDescription() { return "Pits dump anything that wanders in to the floor below. If one of these is placed on the bottom-most floor, it is impassable."; } }
37.803279
142
0.62771
b5646009b025c5f84151edecee17326a0d6b8715
8,782
/* * 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.nifi.provenance.serialization; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.concurrent.atomic.AtomicLong; import org.apache.nifi.provenance.AbstractRecordWriter; import org.apache.nifi.provenance.ProvenanceEventRecord; import org.apache.nifi.provenance.toc.TocWriter; import org.apache.nifi.stream.io.ByteCountingOutputStream; import org.apache.nifi.stream.io.GZIPOutputStream; import org.apache.nifi.stream.io.NonCloseableOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class CompressableRecordWriter extends AbstractRecordWriter { private static final Logger logger = LoggerFactory.getLogger(CompressableRecordWriter.class); private final FileOutputStream fos; private final ByteCountingOutputStream rawOutStream; private final boolean compressed; private final int uncompressedBlockSize; private final AtomicLong idGenerator; private DataOutputStream out; private ByteCountingOutputStream byteCountingOut; private long blockStartOffset = 0L; private int recordCount = 0; public CompressableRecordWriter(final File file, final AtomicLong idGenerator, final TocWriter writer, final boolean compressed, final int uncompressedBlockSize) throws IOException { super(file, writer); logger.trace("Creating Record Writer for {}", file.getName()); this.compressed = compressed; this.fos = new FileOutputStream(file); rawOutStream = new ByteCountingOutputStream(fos); this.uncompressedBlockSize = uncompressedBlockSize; this.idGenerator = idGenerator; } public CompressableRecordWriter(final OutputStream out, final String storageLocation, final AtomicLong idGenerator, final TocWriter tocWriter, final boolean compressed, final int uncompressedBlockSize) throws IOException { super(storageLocation, tocWriter); this.fos = null; this.compressed = compressed; this.uncompressedBlockSize = uncompressedBlockSize; this.rawOutStream = new ByteCountingOutputStream(out); this.idGenerator = idGenerator; } protected AtomicLong getIdGenerator() { return idGenerator; } @Override public synchronized void writeHeader(final long firstEventId) throws IOException { if (isDirty()) { throw new IOException("Cannot update Provenance Repository because this Record Writer has already failed to write to the Repository"); } try { blockStartOffset = rawOutStream.getBytesWritten(); resetWriteStream(firstEventId); out.writeUTF(getSerializationName()); out.writeInt(getSerializationVersion()); writeHeader(firstEventId, out); out.flush(); blockStartOffset = getBytesWritten(); } catch (final IOException ioe) { markDirty(); throw ioe; } } /** * Resets the streams to prepare for a new block * * @param eventId the first id that will be written to the new block * @throws IOException if unable to flush/close the current streams properly */ protected void resetWriteStream(final Long eventId) throws IOException { try { if (out != null) { out.flush(); } final long byteOffset = (byteCountingOut == null) ? rawOutStream.getBytesWritten() : byteCountingOut.getBytesWritten(); final TocWriter tocWriter = getTocWriter(); final OutputStream writableStream; if (compressed) { // because of the way that GZIPOutputStream works, we need to call close() on it in order for it // to write its trailing bytes. But we don't want to close the underlying OutputStream, so we wrap // the underlying OutputStream in a NonCloseableOutputStream // We don't have to check if the writer is dirty because we will have already checked before calling this method. if (out != null) { out.close(); } if (tocWriter != null && eventId != null) { tocWriter.addBlockOffset(rawOutStream.getBytesWritten(), eventId); } writableStream = new BufferedOutputStream(new GZIPOutputStream(new NonCloseableOutputStream(rawOutStream), 1), 65536); } else { if (tocWriter != null && eventId != null) { tocWriter.addBlockOffset(rawOutStream.getBytesWritten(), eventId); } writableStream = new BufferedOutputStream(rawOutStream, 65536); } this.byteCountingOut = new ByteCountingOutputStream(writableStream, byteOffset); this.out = new DataOutputStream(byteCountingOut); resetDirtyFlag(); } catch (final IOException ioe) { markDirty(); throw ioe; } } protected synchronized void ensureStreamState(final long recordIdentifier, final long startBytes) throws IOException { // add a new block to the TOC if needed. if (getTocWriter() != null && (startBytes - blockStartOffset >= uncompressedBlockSize)) { blockStartOffset = startBytes; resetWriteStream(recordIdentifier); } } @Override public synchronized StorageSummary writeRecord(final ProvenanceEventRecord record) throws IOException { if (isDirty()) { throw new IOException("Cannot update Provenance Repository because this Record Writer has already failed to write to the Repository"); } try { final long recordIdentifier = record.getEventId() == -1L ? idGenerator.getAndIncrement() : record.getEventId(); final long startBytes = byteCountingOut.getBytesWritten(); ensureStreamState(recordIdentifier, startBytes); writeRecord(record, recordIdentifier, out); recordCount++; final long bytesWritten = byteCountingOut.getBytesWritten(); final long serializedLength = bytesWritten - startBytes; final TocWriter tocWriter = getTocWriter(); final Integer blockIndex = tocWriter == null ? null : tocWriter.getCurrentBlockIndex(); final String storageLocation = getStorageLocation(); return new StorageSummary(recordIdentifier, storageLocation, blockIndex, serializedLength, bytesWritten); } catch (final IOException ioe) { markDirty(); throw ioe; } } @Override public synchronized long getBytesWritten() { return byteCountingOut == null ? 0L : byteCountingOut.getBytesWritten(); } @Override public synchronized void flush() throws IOException { out.flush(); } @Override public synchronized int getRecordsWritten() { return recordCount; } @Override protected synchronized DataOutputStream getBufferedOutputStream() { return out; } @Override protected synchronized OutputStream getUnderlyingOutputStream() { return fos; } @Override protected synchronized void syncUnderlyingOutputStream() throws IOException { if (fos != null) { fos.getFD().sync(); } } protected boolean isCompressed() { return compressed; } protected abstract void writeRecord(final ProvenanceEventRecord event, final long eventId, final DataOutputStream out) throws IOException; protected abstract void writeHeader(final long firstEventId, final DataOutputStream out) throws IOException; protected abstract int getSerializationVersion(); protected abstract String getSerializationName(); }
38.687225
172
0.681052
05f85578bcd522e32a398695c7aad2283696957b
219
package com.NSL.ECGCertification.Movesense; /** * TODO: Add a class header comment! */ public interface BaseView<T extends com.NSL.ECGCertification.Movesense.BasePresenter> { void setPresenter(T presenter); }
18.25
87
0.753425