id
stringlengths
7
14
text
stringlengths
1
37.2k
26284658_0
public static byte[] serializeAvro(Schema schema, GenericRecord event) throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); BinaryEncoder binaryEncoder = EncoderFactory.get().binaryEncoder(stream, null); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(sch...
26308814_18
public static boolean isValid(String number) { checkLongerThan("The number must have at least 2 characters.", number, 2); checkIsDigitsOnly("Only digits are allowed", number); int length = number.length(); // We will study all the digits but the last char[] chars = number.substring(0, length - 1).t...
26311068_4
public User findUserByUserName(final String userName) { String sqlStr = " SELECT user_id,user_name " + " FROM t_user WHERE user_name =? "; final User user = new User(); jdbcTemplate.query(sqlStr, new Object[]{userName}, new RowCallbackHandler() { public void processRo...
26318789_1
private Response runApp(String clusterId, String appId, Map<String, Object> data, Boolean isUpdate) { try { String command = (String) data.get("cmd"); Integer port = (Integer) data.get("port"); Float cpus = null; if (data.get("cpus") != null) { cpus = Float.parseFloat(dat...
26323526_83
@Override public DataSet<GraphTransaction> getGraphTransactions() { DataSet<Tuple2<GradoopId, EPGMGraphElement>> graphVertexTuples = getVertices() .map(new Cast<>(EPGMGraphElement.class)) .returns(TypeExtractor.getForClass(EPGMGraphElement.class)) .flatMap(new GraphElementExpander<>()); DataSet<Tuple2<...
26344305_1
static int[][] SpiralMatrix(int n) { int[][] a = new int[n][n]; int c = 1, x = 0, y = 0; int d = 0; while (c <= n * n) { if (a[x][y] == 0) { a[x][y] = c++; } else { d++; d = d % 4; } switch (d) { case 0: if (y < n - 1 && a[x][y + 1] < 1) y++; else { d = 1; x++; } break; ...
26347416_4
@Override public List<String> getTargetClasses() { if (deltas != null) { return deltas; } final String[] resolvedIncludes = resolveIncludes(); final DirectoryScanner scanner = new DirectoryScanner(); if (resolvedIncludes != null && resolvedIncludes.length > 0) { scanner.setIncludes...
26402719_0
@Override protected void mutation(Genotype genotype) { Synapse synapse = selectSynapse(genotype); if (synapse != null) { synapse.setEnabled(false); Double weight = synapse.getWeight(); Neuron start = synapse.getStart(); Neuron end = synapse.getEnd(); Neuron neuron = ...
26403452_9
public void filterRequest(RequestFilterContext request) { for (RequestFilter filter : filterManager.getRequestFilters()) { filter.filter(request); } }
26408956_5
@RequestMapping(method = RequestMethod.POST) public String sendEmail(@Valid @ModelAttribute("contactForm") ContactForm contactForm, BindingResult results) { if (results.hasErrors()) { return "contact"; } String name = contactForm.getName(); String from = contactForm.getMail(); String messag...
26424110_10
public int[] solution001(int[] nums, int target) { final Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { final int delta = target - nums[i]; if (!map.containsKey(delta)) { map.put(nums[i], i); continue; } return new int[] {map.get(delta), i}; } r...
26442054_5
@Override public void serialize(MultipartReplyMessage message, ByteBuf outBuffer) { ByteBufUtils.writeOFHeader(MESSAGE_TYPE, message, outBuffer, EncodeConstants.EMPTY_LENGTH); outBuffer.writeShort(message.getType().getIntValue()); writeFlags(message.getFlags(), outBuffer); outBuffer.writeZero(PADDING); ...
26444805_0
@Override @SuppressWarnings("unchecked") public Map<String, Object> execute(Map<String, Object> input, ProgressListener monitor) throws ProcessException { SimpleFeatureCollection features = (SimpleFeatureCollection) Params.getValue(input, AreaProcessFactory.inputFeatures, null); Filter filte...
26461674_4
public static Iterable<String> splitRespectEscape(String s, char c) { String cs = shouldEscape(c) ? "\\" + c : Character.toString(c); Pattern p = Pattern.compile("[^\\\\]" + cs); //return Splitter.on(c).omitEmptyStrings().trimResults().split(s); return Splitter.on(p).omitEmptyStrings().trimResults().spl...
26480183_0
@POST @Path("/import/devoxx") public Response importDevoxx() { StringBuilder message = new StringBuilder(); try { utx.begin(); em.joinTransaction(); Conference conference = devoxxImporter.importConference(true); message.append("Devoxx conference with ") .append...
26525416_12
public XFact getXFactTable(String tableName) throws LensException { return getXFactTable(getFactTable(tableName)); }
26525663_6
@SuppressWarnings("unchecked") public void afterPropertiesSet() throws Exception { if (getServiceInterface() == null) { throw new IllegalArgumentException("Property 'serviceInterfaces' is required"); } // check all the target Factory beans must valid if (targetBeans == null) { throw new...
26554573_3
@POST @Produces(MediaType.APPLICATION_JSON) public Model postIt() { return new Model("todd", "http://www.toddfredrich.com/"); }
26558278_5
;
26574771_3
public Long getId() { return id; }
26628954_3
@Override public HttpServerResponse response() { return request.response(); }
26629839_7
@Override public ResponseData generate(Request request) throws IOException { MimeType format = request.headers.getValue(HTTPHeader.ACCEPT); if (format == null) { format = DEFAULT_OUTPUT_FORMAT; } if (!format.equals(MimeType.PNG) && !format.equals(MimeType.SVG)) { throw new IOException("...
26633479_0
public Value getConvert(IClass type) { Value newVal = value(type.getClassHolder(), value); convert(newVal, type); return newVal; }
26646135_10
public static String encodeToHex(byte[] bytes, boolean uppercase, boolean semicolons) { final char[] lookupTable = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; final int multiplier = semicolons ? 3 : 2; final char[] hexChars = new char[bytes.length * multiplier -...
26649305_0
public Pair calculate() { return calculate(new Comparator<T>() { @Override public int compare(T o1, T o2) { return ((Comparable<T>) o1).compareTo(o2); } }); }
26653760_4
public final boolean isSafe(String url) { final Map<String, String> formParameters = this.config.getParameters(); formParameters.put(PARAMETER_URL, url); boolean safe = true; try { final ResponseEntity<String> response = client.getForEntity( config.getApiUrl(), String.class, formPar...
26662929_0
@Override public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) { try { Optional<WebSocketAuthenticator> authenticator = Optional.ofNullable(environment.getAuthenticator()); Object authenticated = null; if (authenticator.isPresent()) { ...
26669439_0
public ArrayList<Contact> getContacts() { final Editable message = getEditableText(); ImageSpan[] spans = message.getSpans(0, message.length(), ImageSpan.class); Arrays.sort(spans, new Comparator<ImageSpan>() { @Override public int compare(ImageSpan lhs, ImageSpan rhs) { return m...
26686976_1
public RaftNode(Configuration conf) { this.conf = conf; memberManager = new ClusterMemberManager(conf); //serverInfo = ServerInfo.parseFromString(conf.getString("raft.server.local")); raftService = RaftRpcService.create(this, conf); raftLog= new DefaultRaftLog(this, conf); //initialize the term value to be ...
26698596_2
public T getTestConfig() { try { LOGGER.info(String.format("Loading config from: %s", configFileName)); final String substitutedString = substitutor.replace(new String( ByteStreams.toByteArray(this.getClass().getClassLoader().getResourceAsStream(configFileName)), Stan...
26727748_0
@Override public void onUnitsFetched(FetchUnitsEvent event) { units = new ArrayList<>(event.getUnits()); sortUnits(Unit.Properties.name, true); }
26727759_9
public void send() { model.sendPressed = true; if (validate()) { Completable observable = mailJetService.sendEmail( model.name + " <info@cosenonjaviste.it>", "info@cosenonjaviste.it", "Email from " + model.name, "Reply to: " + model.email +...
26745548_501
public GatewayContext resolve(GatewayConfigDocument gatewayConfigDoc) throws Exception { return resolve(gatewayConfigDoc, System.getProperties()); }
26768771_42
public int getNumWords() { return words == null ? 0 : words.length; }
26810298_359
public List<EntityObject> flatten(Object document) throws InvalidPathException { if (pathToEntity == null) { return Arrays.asList(new EntityObject(document)); } List<EntityObject> entityNodes = new ArrayList<>(entitiesPerDocument); EntityObject root = new EntityObject(document); flatten(root, pathToEntity, entit...
26842265_1
@Override public void write(int b) throws IOException { if (pos == buf.length) { finishChunk(false); } buf[pos++] = (byte) b; }
26845372_0
public JsonNode getValue() { return root.at(pointer); }
26861802_25
@Nonnegative @Override public <V> int appendValue(SingleFeatureBean feature, V value) { throw e.get(); }
26862250_20
@Override public ClientDetailsEntity updateClient(ClientDetailsEntity oldClient, ClientDetailsEntity newClient) throws IllegalArgumentException { if (oldClient != null && newClient != null) { for (String uri : newClient.getRegisteredRedirectUri()) { if (blacklistedSiteService.isBlacklisted(uri)) { throw new ...
26873147_130
@Override public CompletableFuture<Void> createTopic( String clusterId, String topicName, int partitionsCount, short replicationFactor, Map<String, String> configs) { requireNonNull(topicName); NewTopic createTopicRequest = new NewTopic(topicName, partitionsCount, replicationFactor).confi...
26888367_24
public OHCacheBuilder<K, V> segmentCount(int segmentCount) { if (segmentCount < -1) throw new IllegalArgumentException("segmentCount:" + segmentCount); this.segmentCount = segmentCount; return this; }
26902200_0
@Override public ServiceTemplate convertToYamlBean(String yamlString) throws ConverterException { if (yamlString == null || yamlString.equals("")) { throw new IllegalArgumentException("YAML string may not be empty!"); } final YamlReader reader = new YamlReader(yamlString); adjustConfig(reader.getConfig()); try {...
26904455_9
void shutdown() { monitoredStreams.values().stream().forEach(client -> client.ctx.close()); monitoredStreams.clear(); acksStreams.values().stream().forEach(client -> client.ctx.close()); acksStreams.clear(); }
26907542_0
public static Date dateConvert(String value) { if (value == null) { return null; } Map<String, String> formats = new HashMap<>(); formats.put("dd.MM.yyyy HH:mm", "^\\d{2}\\.\\d{2}\\.\\d{4}\\s+\\d{2}:\\d{2}$"); formats.put("dd-MM-yyyy HH:mm", "^\\d{2}-\\d{2}-\\d{4}\\s+\\d{2}:\\d{2}$"); ...
26917572_14
public InputStream getResourceAsInputStream(String resourcePath) throws IOException { InputStream stream = null; if (resourcePath == null) { throw new IllegalArgumentException("Resource path cannot be null."); } if (resourcePath.startsWith("classpath:")) { ClassLoader cl = Thread.curre...
26921116_545
public static SammonMapping of(double[][] proximity) { return of(proximity, new Properties()); }
26934626_0
public Program toProgram() { Program.Builder builder = new Program.Builder() .setAudioLanguages(getAudioLanguages()) .setBroadcastGenres(getBroadcastGenres()) .setCanonicalGenres(getCanonicalGenres()) .setChannelId(getChanne...
26949678_0
static Predicate<TargetInfo> createTargetFilterPredicate(Set<Integer> mmsis, Set<Area> baseAreas, Set<Area> areas) { Predicate<TargetInfo> mmsiPredicate = null; if (mmsis != null && mmsis.size() > 0) { mmsiPredicate = targetInfo -> mmsis.contains(targetInfo.getMmsi()); } Predicate<TargetInfo> ...
26951043_22
@Override public void process(JCas jcas) { Integer documentID = documentMapperService.saveDocument(jcas, analysisBatch, bStoreDocText, bStoreCAS, bInsertAnnotationContainmentLinks, setTypesToIgnore); if (documentID != null && xmiOutputDirectory != null && xmiOutputDirectory.length() > 0) { File dirOut = new F...
26956394_29
public static boolean endsWithJarOrApkExtension(@NonNull String filePath) { checkPreconditionsOnFilePath(filePath); int initialCharacterOfAnExtensionIndex = filePath.lastIndexOf(DOT_SEPARATOR); if (initialCharacterOfAnExtensionIndex == -1) return false; String fileExtension = filePath.substri...
26958185_99
public <T> T read(final Class<T> clazz, final String... nameMapping) throws IOException { if( clazz == null ) { throw new NullPointerException("clazz should not be null"); } else if( nameMapping == null ) { throw new NullPointerException("nameMapping should not be null"); } return readIntoBean(instantiateBe...
26971627_67
public long getWidth() { return getMetadata().getPixelBounds(getZoomlevel()).getWidth(); }
27013933_3
public static <T> List<Field> getDeclaredFields(Class<T> clazz, Class<? super T> upToExcluding){ return getAllFields(clazz, Optional.<Class<? super T>>ofNullable(upToExcluding), Predicates.alwaysTrue()); }
27024702_0
public static <T> Stream<List<T>> partition(final Stream<T> stream, final Predicate<T> partitionSeparator) { return new KeywordPartitioner<>(stream, partitionSeparator).asStream(); }
27099588_34
public static <T> List<T> paging(List<T> listToPage, int limit){ return paging(listToPage,0,limit); }
27135187_45
public XsdType getXsdType() { return _xsdType; }
27135253_0
@Override public void generateOutput(TestSuite input, String fileName) { new CVSExporter().generateOutput(input, fileName); try { JUnitTemplateWizard junitWizard = new JUnitTemplateWizard( PlatformUI.getWorkbench(), input, fileName); WizardDialog wd = new WizardDialog( Display.getDefault().getActiveShel...
27145359_0
public static String[] getConfigPaths() { return runKDE4Config("config"); }
27191143_8
public void add(Subscription subscription) { subscriptions.add(subscription); }
27195248_0
public void importData() throws IOException { String statementsWriter = getSettings().getProperty(STATEMENTS_WRITER_KEY, FileStatementsWriter.class.getSimpleName()); if (statementsWriter.indexOf('.') < 0) { statementsWriter = "org.fastnate.generator.statements." + statementsWriter; } try { log.info("Using {}...
27202384_1
public static ArrayList<Long> getRetweeters(long tweetID) throws Exception { return getUsers(tweetID, RETWEETERS_URL); }
27207708_1
public Map<String, List<String>> getDatasourceModels() { return datasourceModels; }
27217073_30
public DcSearchResponse search(final Map<String, Object> query) { Map<String, Object> requestQuery = null; if (query != null) { requestQuery = new HashMap<String, Object>(query); } else { requestQuery = new HashMap<String, Object>(); } if (!requestQuery.containsKey("size")) { ...
27224427_2
public XRoadMessage<XmlObject> extractData(WebServiceMessage response) throws IOException { Node kehaNode; try { SaajSoapMessage message = (SaajSoapMessage) response; SOAPMessage mes = message.getSaajMessage(); Element body = mes.getSOAPBody(); NodeList kehaNodes = body.getChildNodes(); kehaNode...
27284166_3
;
27287531_4
@VisibleForTesting @Nonnull static Rect newBounds(@Nonnull Rect bounds, double fraction, double priorFraction) { verify(fraction + priorFraction <= 1 + EPSILON, "fraction (%d) & prior fraction (%d) more than 1 + EPSILON ", fraction, priorFraction); if (bounds.isEmpty()) return bounds; Rect newBounds; ...
27292418_5
public Unification unify(Type type, TypeScope scope) { return generate(scope).unify_(type.generate(scope), scope); }
27344072_3
public static boolean isValidPart (@Nullable final String sPart) { return StringHelper.hasText (sPart) && RegExHelper.stringMatchesPattern (REGEX_PART, sPart); }
27377253_0
public DeltaExtras getDelta() { return delta; }
27392543_546
@Override public Dag<JobExecutionPlan> compileFlow(Spec spec) { Preconditions.checkNotNull(spec); Preconditions.checkArgument(spec instanceof FlowSpec, "MultiHopFlowCompiler only accepts FlowSpecs"); long startTime = System.nanoTime(); FlowSpec flowSpec = (FlowSpec) spec; String source = ConfigUtils.getStri...
27403772_0
@Override public int compare(@Nullable final String pStr1, @Nullable final String pStr2) { int result = 0; if (pStr1 == null) { if (pStr2 != null) { result = 1; } } else { if (pStr2 == null) { result = -1; } else { Matcher match...
27404315_0
public static String fixIPv6Address(String address) { try { InetAddress inetAdr = InetAddress.getByName(address); if (inetAdr instanceof Inet6Address) { return "[" + inetAdr.getHostName() + "]"; } return address; } catch (UnknownHostException e) { log.debug("Not InetAddress: " + address + " , resolved a...
27408825_1
public static String replaceVars(String msg, HashMap<String, String> vars){ boolean error = false; for(String s:vars.keySet()){ try{ msg.replace("{$"+s+"}", vars.get(s)); }catch(Exception e){ MessageManager.getInstance().debugConsole("Failed to replace string vars. Error ...
27416566_3
public void run(T configuration, Environment environment, JedisPool jedisPool) throws Exception { this.jedisPool = jedisPool; run(configuration, environment); }
27460436_26
public void setSeverityLevel(SeverityLevel severityLevel) { data.setSeverityLevel(severityLevel == null ? null : com.microsoft.applicationinsights.internal.schemav2.SeverityLevel.values()[severityLevel.getValue()]); }
27490105_0
public static Point2D getConnectorPosition(final GConnector connector, final SkinLookup skinLookup) { final GConnectorSkin connectorSkin = skinLookup.lookupConnector(connector); final GNode parent = connector.getParent(); final GNodeSkin nodeSkin = skinLookup.lookupNode(parent); if (nodeSkin == null) ...
27503648_8
public String generateTemporaryToken(String key, int secondsToLive) { return generateTemporaryToken(key, secondsToLive, null); }
27507850_2204
@VisibleForTesting @Nonnull static IpsecSession getIpsecSession( Configuration initiatorOwner, Configuration peerOwner, IpsecStaticPeerConfig initiator, IpsecPeerConfig candidatePeer) { IpsecSession.Builder ipsecSessionBuilder = IpsecSession.builder(); ipsecSessionBuilder.setCloud( IpsecSessi...
27514348_3
@Override public byte[] serialize(T event) { try { return objectMapper.writeValueAsBytes(event); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } }
27533072_1
public static String md5Hex (String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); return hex (md.digest(message.getBytes("CP1252"))); } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } return null; }
27534295_1
public static ExecutionContext create(Vertx vertx) { return new VertxEventLoopExecutionContext(vertx); }
27570630_0
public void process(Resource inputResource, Resource outputResource) { SXSSFWorkbook wb = new SXSSFWorkbook(flushSize); try { wb.setCompressTempFiles(true); // temp files will be gzipped final Sheet sh = wb.createSheet(); InputStreamReader is = new InputStreamReader(inputResource.getInp...
27583882_1
@Override public String computeHash(String password, String salt, int version) { int iterations = DEFAULT_ITERATIONS; if (version >= 0) { if (nonces == null) { // the nonce version is not available throw new VertxException("nonces are not available"); } if (version < nonces.size()) { ...
27590439_480
@Override protected BdfMessageContext validateMessage(Message m, Group g, BdfList body) throws FormatException { // Client states, update version checkSize(body, 2); // Client states BdfList states = body.getList(0); int size = states.size(); for (int i = 0; i < size; i++) { BdfList clientState = states.getLi...
27591666_3
static PCollection<KV<String, Integer>> applyPipelineToParseBooks(PCollection<String> p) { return p.apply( FlatMapElements.via((String doc) -> Splitter.on("\n").split(doc)) .withOutputType(new TypeDescriptor<String>() {})) .apply(Filter.byPredicate((String line) -> !line.isEmpty())) ...
27609596_139
AWSCredentialsProvider createCredentialsProvider(String name, String accountId) { final AWSCredentialsProvider dflt = new DefaultAWSCredentialsProviderChain(); final Config cfg = getConfig(name, "credentials"); if (cfg.hasPath("role-arn")) { return createAssumeRoleProvider(cfg, accountId, dflt); } else { ...
27622439_69
@Override public Stage<Void> stop() { if (!state.compareAndSet(ManagedState.STARTED, ManagedState.STOPPED)) { return stopFuture; } stopReferenceFuture.complete(this.reference.getAndSet(null)); // release self-reference. release(); return stopFuture; }
27653357_4
public boolean matches(String path) { return pathPattern.matcher(path).matches(); }
27674753_1
@SuppressWarnings("unchecked") public <T> Class<T> getClass(T entity) { // get the first class in the hierarchy that is actually in the index Class<T> clazz = (Class<T>) entity.getClass(); if ( !clazz.isAnnotationPresent( InIndex.class ) ) { while ( (clazz = (Class<T>) clazz.getSuperclass()) != null ) { if ( cl...
27683023_125
public BigDecimal getValue(WindSpeedUnit unit) { BigDecimal value = null; switch (unit) { case KNOTS: value = knots; break; case METRES_PER_SECOND: value = metresPerSecond; break; case KILOMETRES_PER_HOUR: value = kilometresPer...
27683112_56
private static Function parseVALUE(ConfigThingy conf, FunctionLibrary funcLib, DialogLibrary dialogLib, Map<Object, Object> context) { Function valueNameFun; // TODO doesn't work as described. Exception isn't thrown by 0 or more than 1 parameters. try { valueNameFun = parse(conf.getFirstChild(), funcLib...
27700791_0
@Override public String serialize(Object obj) throws Exception{ return super.serialize(obj); }
27715709_10
@Override public boolean implies(Permission p) { if (!(p instanceof ResourcePermission)) return false; ResourcePermission qp = (ResourcePermission) p; /* * Condition 1: The action flag of the queried permission was set in the granted permission */ int queriedActions = qp.actionsAsMask; if ((queriedActions & ...
27721932_273
public AbstractListAssert<?, List<? extends String>, String, ObjectAssert<String>> extractingText() { isNotNull(); List<String> values = new ArrayList<>(); for (Node node : actual) { String textContent = node.getTextContent(); if (textContent != null) { textContent = textConten...
27728683_0
static public int getMiddleIndex(int beginIndex, int endIndex) { return beginIndex + (endIndex - beginIndex) / 2; }
27764873_17
public TopicAndPartition getTopicAndPartition() { return topicAndPartition; }
27773224_0
@SuppressWarnings("unchecked") public static <T> Boxer<T> from(T object) { for(String target : defaultWrappers.keySet()){ try{ if(Class.forName(target).isAssignableFrom(object.getClass())){ return defaultWrappers.get(target).getDeclaredConstructor(object.getClass()).newInstance(o...
27785546_57
@Override public int read() throws IOException { snifferSocket.checkConnectionAllowed(0); long start = System.currentTimeMillis(); int bytesDown = 0; try { int read = delegate.read(); if (read != -1) bytesDown = 1; return read; } finally { sleepIfRequired(bytesDown); ...
27789592_28
public Optional<String> visitPath(ExecutableElement element) { String aggregatedPath = emptyToNull( aggregate( currentPath(element).orElse(""), element.getEnclosingElement() ) ); return Optional.ofNullable(aggregatedPath); }
27790789_56
public SchemaAndValue toConnectData(org.apache.avro.Schema avroSchema, Object value) { return toConnectData(avroSchema, value, null); }