id
stringlengths
7
14
text
stringlengths
1
37.2k
16162461_3
public SinaUserBaseInfoDaoImpl(List<String> tokens) { this.tokens = tokens; user = new Users(); }
16185077_9
public static AztecCode encode(byte[] data) { return encode(data, DEFAULT_EC_PERCENT, DEFAULT_AZTEC_LAYERS); }
16189524_3
@POST @Path("/{resource}") @Timed public Collection<Collection<MeasurementDTO>> getMeasurements( ResultDescriptorDTO descriptorDTO, @PathParam("resource") Resource resource, @QueryParam("start") Optional<TimestampParam> start, @QueryParam("end") Optional<TimestampParam> end, @Que...
16204287_28
public double probability(double theta, double[] iparam, int category, double D){ double t = numer(theta, iparam, category, D); double b = denom(theta, iparam, D); return t/b; }
16283971_24
public int[] sort(int[] m) { if (m.length <= 1) return m; int middle = m.length / 2; int[] left = Arrays.copyOf(m,middle); int[] right = Arrays.copyOfRange(m,middle,m.length); right = sort(right); left = sort(left); int[] result = merge(left, right); return result; }
16293572_17
@Override public String[] keys() { return this.lockTemplate.withReadLock(new LockTemplate.LockedOperation<String[]>() { @Override public String[] invoke() { try { Set<String> sessions = RedisStore.this.jedisClient.getSessions(getSessionKeyPrefix()); retur...
16294920_10
public CompletableFuture<byte[]> invoke(PrimitiveOperation operation) { CompletableFuture<byte[]> future = new CompletableFuture<>(); switch (operation.id().type()) { case COMMAND: context.execute(() -> invokeCommand(operation, future)); break; case QUERY: context.execute(() -> invokeQuery...
16310572_0
public static SingleDTGraph statements2Graph(Set<Statement> stmts, int literalOption, List<Resource> instances, boolean simplifyInstanceNodes) { List<DTNode<String,String>> instanceNodes = new ArrayList<DTNode<String,String>>(); DTGraph<String,String> graph = new LightDTGraph<String,String>(); Map<String, DTNode<St...
16319386_107
public static DefaultBuildContextState emptyState() { return new DefaultBuildContextState(Collections.<String, Serializable>emptyMap() // configuration , Collections.<Object, ResourceHolder<?>>emptyMap() // inputs // , Collections.<File>emptySet() // outputs // , Collections.<Object, Collection<File...
16338837_0
@Path("rest/upper/{param}") @GET public String toUpper(@PathParam("param") String param) { return param.toUpperCase(); }
16338894_1
@Override public <T> void subscribe(EventBusListener<T> listener) { subscribe(listener, true); }
16346614_1
public static boolean checkEssentiallyEqual(Transaction unsignedTransaction, Transaction signedTransaction) { // Check there are the same number of transactionInputs and transactionOutputs List<TransactionInput> unsignedTransactionInputs = unsignedTransaction.getInputs(); List<TransactionOutput> unsignedTransacti...
16362540_75
@Override public void registerDeserializer(MessageCodeKey key, OFGeneralDeserializer deserializer) { if ((key == null) || (deserializer == null)) { throw new IllegalArgumentException("MessageCodeKey or Deserializer is null"); } OFGeneralDeserializer desInRegistry = registry.put(key, deserializer); ...
16362553_65
@VisibleForTesting void updateInterfaces(Interface interfaceUpdate, final OvsdbTerminationPointAugmentationBuilder ovsdbTerminationPointBuilder) { Column<GenericTableSchema, String> typeColumn = interfaceUpdate.getTypeColumn(); String type = typeColumn.getData(); updateInterface(interfaceUpdate, ty...
16381579_0
public static boolean isEditionNewer(String testFW) { return isEditionNewer(testFW, getVersion()); }
16389681_7
@Override public long writeAll(Source source) throws IOException { if (source == null) throw new IllegalArgumentException("source == null"); long totalBytesRead = 0; for (long readCount; (readCount = source.read(buffer, Segment.SIZE)) != -1; ) { totalBytesRead += readCount; emitCompleteSegments(); } r...
16390035_19
public static ProxyRequireField parse(String fieldValue) { ProxyRequireField result = new ProxyRequireField(); result.addFeatures(RequireField.parseFeatures(fieldValue)); return result; }
16391713_2
@Nonnull @Override public byte[] getRawForm(@Nullable byte[] value) { if (value == null) { return "null".getBytes(StandardCharsets.UTF_8); } return value; }
16395045_211
public void start() { worker = new Thread(null, this, "SplitLogWorker-" + serverName); exitWorker = false; worker.start(); }
16404471_0
@Override public SubsetVectors[] getVectors(String[][] wordsets, SegmentationDefinition[] definitions) { SubsetProbabilities probabilities[] = supplier.getProbabilities(wordsets, definitions); return createVectors(wordsets, definitions, probabilities); }
16425010_23
public String toBpmnXml(FlowBuilder flowBuilder) { return toBpmnXml(flowBuilder.getDefinition()); }
16429916_0
public String getServerContext() throws AxisFault { try { String returnValue = ReadWSDLPrefix(); if (returnValue != null && !returnValue.isEmpty()) { return returnValue; } else { return stub.getServerContext(); } } catch (Exception e) { handleException(bundle.getString("failed.to.get.servercontext"), ...
16432662_0
static int computePartition(Object key, int numPartitions, int maxParallelism) { int group = murmurHash(key.hashCode()) % maxParallelism; return (group * numPartitions) / maxParallelism; }
16433054_3
@Override public Integer getValue() { return value; }
16442741_0
public static VersionCheckResult checkVersion(String localVersion) { String remoteVersion = getVersion(); if (remoteVersion == null || remoteVersion.isEmpty()) { return VersionCheckResult.error(); } Integer[] iLocalVersion = parseVersion(localVersion); Integer[] iRemoteVersion = parseVersi...
16446099_10
@Override public int compare(String version1, String version2) { // "Build metadata SHOULD be ignored when determining version precedence. // Thus two versions that differ only in the build metadata, have the same precedence." String v1WithoutBuildMetadata = StringUtils.substringBefore(version1, BUILD_SEP); String ...
16451749_4
public static String getOptionDescription(EasyJaSubInputOption optionIndex) { return InputOptions[optionIndex.ordinal()]; }
16458851_218
public void mutate() { Aspect aspect = aspects.get((int) (Math.random() * aspects.size())); aspect.setRandomly(this); }
16460789_6
@Override public void update(OwnedObject<Long, Armor> rowData) throws DataAccessException { try { beginTransaction(); itemDAO.update(OwnedObject.of(rowData.getOwnerId(), (Item) rowData.getObject())); super.update(rowData); setTransactionSuccessful(); } finally { endTransa...
16471584_58
public static JsonPrimitive validateNumeric(JsonObject inputObject, String value) throws ParserException, ValidatorException { Double multipleOf; if (value == null) { throw new ValidatorException("Expected a number but found null"); } //replacing enclosing quotes value = JsonProcesso...
16477640_0
public Book getFullBook(Book book) { if (book.getId() != null) { Book bookById = dao.getBookById(book.getId()); return bookById; } else if (book.getName() != null) { return dao.getBookByName(book.getName()); } else { return null; } }
16477702_5
public static Failed failed(XmlPullParser parser) throws XmlPullParserException, IOException { ParserUtils.assertAtStartTag(parser); String name; StanzaError.Condition condition = null; List<StanzaErrorTextElement> textElements = new ArrayList<>(4); outerloop: while (true) { XmlPullParse...
16479425_1
@Override public int getCount() { return fragments.size(); }
16481293_2
@Override public void setHistorySize(int size) { if(size < 1) { throw new IllegalArgumentException("History max size value invalid: " + size); } if(size > 50) { // warning log LOG.info("History size is configured to greater than 50! Ensure you have enough memory!!"); } if(m...
16492034_58
public TrackEvent processLine(FileInfo info, String line) { ApacheErrorLogEntry entry = new ApacheErrorLogEntry(); if (!entry.parse(line)) { return null; } return newTrackEvent(System.currentTimeMillis(), //XXX parse entry.timeStamp entry.level.toLowerCase(), ...
16501680_0
public static String buildPayloadString(Object o) { String queryString = ""; Class<?> clazz = o.getClass(); Field[] fields = clazz.getDeclaredFields(); for(int i=0; i<fields.length; i++) { fields[i].setAccessible(true); String fieldValue = getFieldValue(fields[i], o); fields[i]...
16511407_1
@Override public Object clone() { return new EmbeddedDescriptor(this); }
16516859_8
@Override public Principal authenticate(Credentials credentials) { // Make sure the timestamp has not expired - this is to protect against replay attacks if (!validateTimestamp(credentials.getTimestamp())) { LOG.info("Invalid timestamp"); return null; } // Get the principal identified b...
16538895_16
public static long selectCount() { String SELECT_COUNT = "SELECT COUNT(*) FROM CIFAR"; return Yank.queryScalar(SELECT_COUNT, Long.class, null); }
16547484_367
@Override public boolean monitorOneOf(ChangedCollections changedCollections) { SortedSet<String> collectionPathSet = convertSetToComparePath(changedCollections); return !Sets.intersection( Sets.newHashSet(Iterables.transform(getMonitoredCollections(), new Function<AnalysedSyncCollection, String>() { @Override ...
16563359_1
@Override public ComponentConfigurationResolver getConfigurationFactory(final String componentType) { ComponentConfigurationResolver factory = overrides.get(componentType); if (factory != null) return factory; return new ComponentConfigurationResolver() { @Override public Config...
16569959_4
@Override public String getContent() { if(hasBeenCalledBefore ){ return txt.toString(); }else{ hasBeenCalledBefore = true; } txt.append(this.getUri()); txt.append(getDocumentHead()); txt.append(this.getBody().getContent()); txt.append("\n</w:wordDocument>"); String fin...
16594787_20
public static Optional<GroupByElement> createGroupByElement(SqlQueryBuilderAccess queryBuilderAccess) { final QueryParameter queryParameter = queryBuilderAccess.getQueryParameter(); if (queryParameter.getGroups().isEmpty()) { return Optional.absent(); } GroupByElement groupByElement = new GroupB...
16641539_18
public URIBuilder setRawFragment(final String rawFragment) { _rawFragment = rawFragment; return this; }
16677474_0
public static boolean isAsynchronous(Object receiver, String method, Object... args) { Info i = store.get(); return i.receiver != null && receiver==i.receiver.get() && method.equals(i.method) && arrayShallowEquals(i.args, args); }
16687794_64
@Override public <T> T unwrap(Class<T> iface) throws SQLException { return targetDataSource.unwrap(iface); }
16695331_0
public static void generateSetter(File file, String className) throws IOException { String variableName = StringUtils.uncapitalize(className); System.out.println(className + " " + variableName + " = new " + className + "();"); BufferedReader fileReader = new BufferedReader(new FileReader(file)); while ...
16709732_2
@Override public boolean equals(Object obj) { if (obj instanceof MappingPattern) { MappingPattern otherPattern = (MappingPattern) obj; if (this.method.equals(otherPattern.getMethod()) && this.pattern.toString().equals(otherPattern.getPattern().toString())) { return true; } else {...
16709910_56
protected HttpResponse handleRegister(HttpRequest req) { HttpResponse response = null; try { ClientCredentials creds = auth.issueClientCredentials(req); ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(creds); log.debug("credentials:" + json...
16775240_20
@Override public boolean itemExists(String name) throws JMSException { initializeReading(); return map.containsKey(name); }
16777411_0
public static Keyframe parseKeyframe(ByteInputStream stream) throws PacketParseException { Keyframe keyframe = new Keyframe(); /* ### Keyframe Header ### */ if(stream.nextByte() != 0x03) throw new PacketParseException("Invalid keyframe header."); keyframe.setTimeStamp(stream.nextFloat()); s...
16791473_0
public String getName() { int firstComma = name.indexOf(","); return WordUtils.capitalizeFully(name.substring(firstComma + 1).trim() + " " + name.substring(0, firstComma).trim()); }
16810766_33
public ListenableFuture<Transaction> broadcast() { log.info("Waiting for {} peers required for broadcast ...", minConnections); ListenableFuture<PeerGroup> peerAvailabilityFuture = peerGroup.waitForPeers(minConnections); peerAvailabilityFuture.addListener(new EnoughAvailablePeers(), Threading.SAME_THREAD); ...
16811502_124
@SuppressWarnings("unchecked") public static Map<String, Object> normaliseAndValidateQuery(Map<String, Object> query) throws QueryException{ boolean isWildCard = false; if (query.isEmpty()) { isWildCard = true; } // First expand the query to include a leading compound predicate // if there ...
16841282_37
public void setImageUrl(String url, ImageLoader imageLoader) { mUrl = url; mImageLoader = imageLoader; // The URL has potentially changed. See if we need to load it. loadImageIfNecessary(false); }
16842086_1
public Network selectManagementNetworkWhiteAndBlackOnly(Computer computer) { List<Network> possibleNetworks = new ArrayList<>(); for (Network network : computer.getNetworks()) { if (!network.getIPAddress().isEmpty()) { if (isIpWhiteListed(network.getIPAddress()) && !isIpBlackListed(network.g...
16842589_1
public static ItemViewHolder createViewHolder(View view, Class<? extends ItemViewHolder> itemViewHolderClass) { try { Constructor<? extends ItemViewHolder> constructor = itemViewHolderClass.getConstructor(View.class); return constructor.newInstance(view); } catch (IllegalAccessException e) { ...
16858994_1
public static int normalizeSeconds(int secondsPerAlarm) { return pickerChoiceToSeconds(secondsToPickerChoice(secondsPerAlarm)); }
16863086_7
public void set(final int value) { mPreferences.edit().putInt(mKey, value).apply(); }
16888619_4
public void dealInitialCards() { if (state != GameState.BEFORE_INITIAL_DEAL) { throw new IllegalStateException(getID() + " initial deal has been already made"); } publish(new GameStartedEvent(getID(),tableId, player.getID(), nextSequenceId())); dealFor(player); dealFor(dealer); dealFor(player); dealFor(dealer)...
16942067_39
public static Tuple2<String[], Object[]> prepareTuple4CqlDriver(Tuple2<Cells, Cells> tuple) { Cells keys = tuple._1(); Cells columns = tuple._2(); String[] names = new String[keys.size() + columns.size()]; Object[] values = new Object[keys.size() + columns.size()]; for (int k = 0; k < keys.size();...
16945152_20
synchronized File createMessageFile(String baseName) throws IOException { int suffix = -1; File file; do { suffix++; StringBuilder sb = new StringBuilder(baseName); if (suffix > 0) { sb.append('-').append(suffix); } sb.append('.').append(getFilenameExtensi...
16946884_14
@Override public double getLineWidth(Canvas canvas) { return canvas.getGraphicsContext2D().getLineWidth(); }
16947368_1
List<String> getProvidedRepositories() { List<String> repositories = new ArrayList<>(); selectedEnvironments.entrySet() .stream() .map(Map.Entry::getValue) .forEach(repositories::addAll); return repositories; }
16970593_83
@Override public <T> List<ConstraintViolation<T>> validate( MonitoringValidationContext context, MetricEntityTypeDescriptor entity, DescriptorPathImpl path) { Preconditions.checkNotNull(context); Preconditions.checkNotNull(entity); Preconditions.checkNotNull(path); List<ConstraintViolation<T>> ret ...
16977479_503
@Override protected JwsSignatureVerifier getInitializedSignatureVerifier(JwsHeaders jwsHeaders) { Objects.requireNonNull(jwsHeaders.getKeyId()); final JwkHolder jwkHolder = jsonWebKeys.computeIfAbsent(jwsHeaders.getKeyId(), keyId -> updateJwk(keyId)); return jwkHolder != null ? jwkHolder.getJwsSignatureVeri...
16983824_3
@Override public Response execute(Request request) throws IOException { HttpURLConnection connection = openConnection(request); prepareRequest(connection, request); Response response = readResponse(connection); return followRedirectsIfNecessary(request, response); }
17025957_31
@Override public void processRow(Row currentRow) { this.unmappedFields = new HashMap<>(); Object targetObject = convert(this.target, currentRow); if (currentRow.hasChildren() && this.childrenType != null) { mapChildren(targetObject, currentRow.getChildren()); } this.consumer.accept(targetObj...
17033876_0
@Override public String getMasterTerm(String term) { if (StringUtils.isNullOrEmpty(term)) { return null; } final Cache<String, String> cache = getMasterTermCache(); String result; synchronized (cache) { result = cache.getIfPresent(term); if (result == null) { ...
17034809_78
public boolean isComparable(String str) { return str.matches("\\d+\\.\\d+(\\.\\d+)?(\\-[A-Z0-9]+)?"); }
17054757_0
@Override public String build() { ResourceType resourceType = null; if (metaData != null) { resourceType = metaData.getResourceType(); } String id = resourceIdentifier.getIdentifier(resourceType); clear(); return id; }
17090302_8
public List<Tune> getAll() { log.debug("Retrieve all items"); return tunesRepository.getTunes(); }
17132838_2
private boolean rotate() throws IOException { // rename the current file File oldFile = new File(mLogFile.toString() + ".old"); File newFile = new File(mLogFile.toString()); if (newFile.renameTo(oldFile)) { BufferedReader oldLog = null; FileWriter rotatedLog = null; try { ...
17169550_117
public String getSummaryData(TestSummary summary) { if (summary.hasFailed()) { StringBuffer sb = new StringBuffer("\n\n"); sb.append("Script: ").append(summary.getScriptName()); sb.append("\nFailures: ").append(summary.getFailures()); sb.append("\nErrors: ").append(summary.getErrors()); return sb....
17170044_13
public static Config parseConfig(String args, String ifc) { Pattern pattern = Pattern.compile( "^(?:((?:[\\w.]+)|(?:\\[.+])):)?" + // host name, or ipv4, or ipv6 address in brackets "(\\d{1,5}):" + // port "(.+)"); // config file ...
17182007_35
static public Field getEnumField(PMMLObject object, Enum<?> value){ Class<?> clazz = object.getClass(); while(clazz != null){ Field[] fields = clazz.getDeclaredFields(); for(Field field : fields){ if((field.getType()).equals(value.getClass())){ return field; } } clazz = clazz.getSuperclass(); }...
17186399_2
@RequestMapping(value="/{id}", method=RequestMethod.PUT) public Person updatePerson(@PathVariable(value="id")String id, @RequestBody Person person){ if(null == id || !id.equals(person.getId())){ throw new RequestConflictException("Id doesn't match model id"); } return this.personRepository.save(pers...
17194860_2
@Override protected void doFilter(HttpServletRequest request, HttpServletResponse response) { if(corsConfiguration.isEnabled()) { response.addHeader("Access-Control-Allow-Origin", corsConfiguration.getOrigin()); response.addHeader("Access-Control-Allow-Headers", corsConfiguration.getHeaders()); res...
17224370_806
public static GeneralAdminInp instanceForAddUser(final User user) throws JargonException { if (user == null) { throw new JargonException("null user"); } if (user.getName().isEmpty()) { throw new JargonException("blank user name"); } if (user.getUserType() == UserTypeEnum.RODS_UNKNOWN) { throw new JargonEx...
17224385_23
@Override public List<ConfigurationProperty> listConfigurationProperties() throws ConveyorExecutionException { log.info("listConfigurationProperties()"); try { return configurationPropertyDAO.findAll(); } catch (TransferDAOException e) { log.error("DAO exception", e); throw new ConveyorExecutionException(e);...
17250332_4
@Override @SuppressWarnings("SimplifiableIfStatement") public Result match(Ref ref, Ref contextRef) { Node propertyPattern = pattern.property(); Pattern parentPattern = pattern.parent(); if (parentPattern == null) { // this is a root (single node) pattern return matchRefWithRootPattern(ref...
17270540_24
String convert(int number) { throw new UnsupportedOperationException("Delete this statement and write your own implementation."); }
17273013_16
public CalculationBounds autoCalcAndSetDatesBounds(Date startDate, Date endDate) throws InvalidAlgorithmParameterException { endDateToLastEventConsistencyCheck(endDate); if (currentTunedConfEnd.equals(DateFactory.dateAtZero())) {//No previous calculation LOGGER.info( "New dates for...
17278009_94
@Override public Configuration loadResourceConfiguration() throws Exception { ConfigurationDefinition configDef = context.getResourceType().getResourceConfigurationDefinition(); if (configDef.getDefaultTemplate().getConfiguration().get(TYPE_CONFIGURATION) != null) { //__type is a fake property, do not ...
17288475_46
int getViewTypeCount() { return prototypes.size(); }
17310686_358
@Override public InputStream getContent() throws IOException { // If the wrapped stream is repeatable return it directly. if( replayBuffer == null ) { return wrappedEntity.getContent(); // Else if the buffer has overflowed } else if( finalStream != null ) { throw new IOException( "Existing stream alread...
17342981_0
public static String reverse(String text) { if (text == null) { return null; } return new StringBuilder(text).reverse().toString(); }
17363232_37
public <I> void parse(I input, NMEAObserver data, AISObserver aisData) throws IOException { parse(input, true, null, data, aisData); }
17403485_0
@Override public <O extends JsonElementWrapper> O wrap(JsonArray jsonElement) { throw new IllegalStateException("cannot wrap Typed Element with empty type"); }
17404938_337
public SqlNode parse() { outer: for (; ; ) { tokenType = tokenizer.next(); token = tokenizer.getToken(); switch (tokenType) { case WHITESPACE: { parseWhitespace(); break; } case WORD: case QUOTE: { parseWord(); break; ...
17416853_3
public ResponsibilityEntry.State getState() { return state; }
17430117_1
public Integer encode(String string) { if (string.length() > WORD_PART_LENGHT) throw new SuffixToLongException("Suffix length should not be greater then " + WORD_PART_LENGHT + " " + string); int result = 0; for (int i = 0; i < string.length(); i++) { int c = 0 + string.charAt(i) - RUSSIAN_SM...
17443465_20
public Oggetto extract(String text) { Oggetto risultato = null; if (this.operazione.equals("E-mails")) { risultato = getEmails(text); } else if (this.operazione.equals("numbers")) { risultato = getNumbers(text); } else if (this.operazione.equals("URLs")) { risultato = getSites(t...
17452733_36
@Override public TextEdgeWriter<Text, Text, Text> createEdgeWriter(TaskAttemptContext context) throws IOException, InterruptedException { DGALoggingUtil.setDGALogLevel(getConf()); return new TTTEdgeWriter(); }
17455532_49
public static int[] wordDistance(String s1, String s2, int chunkLen) { MinimalPerfectHash mph = new MinimalPerfectHash(true); // case sensitive TokenArray a1 = new TokenArray(mph, s1); TokenArray a2 = new TokenArray(mph, s2); EditSequence seq = new EditSequence(a1, a2, chunkLen); return new int[]{a1...
17477111_338
@Override protected int compare(OrderDependencyResult od1, OrderDependencyResult od2, String sortProperty) { if (LHS_COLUMN.equals(sortProperty)) { return od1.getLhs().toString() .compareTo(od2.getLhs().toString()); } if (RHS_COLUMN.equals(sortProperty)) { return od1.getRhs().t...
17488986_14
public static double getSquaredDistanceToSegment( final double pFromX, final double pFromY, final double pAX, final double pAY, final double pBX, final double pBY ) { return getSquaredDistanceToProjection(pFromX, pFromY, pAX, pAY, pBX, pBY, getProjectionFactorToSegment(pFromX, pFromY, pA...
17491095_19
@Override public SingleResult generate(Class<?> javaClass) throws SingleFileGeneratorException { List<String> constants = new ArrayList<>(); for (Enum constant : ((Class<Enum<?>>) javaClass).getEnumConstants()) { constants.add(constant.name()); } StjsJavaScriptClassBuilder builder = new StjsJavaScriptClassBuild...
17505473_57
@SuppressWarnings("unchecked") public List<String> update(UsergroupUpdateParam param) { if (param.getUsrgrpid() == null || param.getUsrgrpid().length() == 0) { throw new IllegalArgumentException("usrgrpid is required."); } JSONObject params = JSONObject.fromObject(param, defaultConfig); if (acc...
17517472_48
public String post(final String content) throws Exception { final var request = HttpRequest.newBuilder() .uri(URI.create(url)) .header("X-Meta-Var", "FooBar") .POST(BodyPublishers.ofString(content)) .build(); final var client = HttpClient.newHttpClient(); r...