repo_name
stringlengths
7
104
file_path
stringlengths
11
238
context
list
import_statement
stringlengths
103
6.85k
code
stringlengths
60
38.4k
next_line
stringlengths
10
824
gold_snippet_index
int32
0
8
HadoopGenomics/Hadoop-BAM
src/main/java/org/seqdoop/hadoop_bam/BAMInputFormat.java
[ "public class LinearBAMIndex extends CachingBAMFileIndex {\n\n public LinearBAMIndex(SeekableStream stream, SAMSequenceDictionary dict) {\n super(stream, dict);\n }\n \n public LinearIndex getLinearIndex(int idx) {\n return getQueryResults(idx).getLinearInde...
import htsjdk.samtools.AbstractBAMFileIndex; import htsjdk.samtools.BAMFileReader; import htsjdk.samtools.BAMFileSpan; import htsjdk.samtools.BAMIndex; import htsjdk.samtools.Chunk; import htsjdk.samtools.LinearBAMIndex; import htsjdk.samtools.LinearIndex; import htsjdk.samtools.QueryInterval; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMFileSpan; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.samtools.SamInputResource; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.util.Interval; import htsjdk.samtools.util.Locatable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.seqdoop.hadoop_bam.util.IntervalUtil; import org.seqdoop.hadoop_bam.util.NIOFileUtil; import org.seqdoop.hadoop_bam.util.SAMHeaderReader; import org.seqdoop.hadoop_bam.util.WrapSeekable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.ProviderNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import htsjdk.samtools.seekablestream.SeekableStream; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit;
// Copyright (c) 2010 Aalto University // // 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. // File created: 2010-08-03 11:50:19 package org.seqdoop.hadoop_bam; /** An {@link org.apache.hadoop.mapreduce.InputFormat} for BAM files. Values * are the individual records; see {@link BAMRecordReader} for the meaning of * the key. */ public class BAMInputFormat extends FileInputFormat<LongWritable,SAMRecordWritable> { private static final Logger logger = LoggerFactory.getLogger(BAMInputFormat.class); /** * If set to true, only include reads that overlap the given intervals (if specified), * and unplaced unmapped reads (if specified). For programmatic use * {@link #setTraversalParameters(Configuration, List, boolean)} should be preferred. */ public static final String BOUNDED_TRAVERSAL_PROPERTY = "hadoopbam.bam.bounded-traversal"; /** * If set to true, enables the use of BAM indices to calculate splits. * For programmatic use * {@link #setEnableBAISplitCalculator(Configuration, boolean)} should be preferred. * By default, this split calculator is disabled in favor of the splitting-bai calculator. */ public static final String ENABLE_BAI_SPLIT_CALCULATOR = "hadoopbam.bam.enable-bai-splitter"; /** * Filter by region, like <code>-L</code> in SAMtools. Takes a comma-separated * list of intervals, e.g. <code>chr1:1-20000,chr2:12000-20000</code>. For * programmatic use {@link #setIntervals(Configuration, List)} should be preferred. */ public static final String INTERVALS_PROPERTY = "hadoopbam.bam.intervals"; /** * If set to true, include unplaced unmapped reads (that is, unmapped reads with no * position). For programmatic use * {@link #setTraversalParameters(Configuration, List, boolean)} should be preferred. */ public static final String TRAVERSE_UNPLACED_UNMAPPED_PROPERTY = "hadoopbam.bam.traverse-unplaced-unmapped"; /** * If set to true, use the Intel inflater for decompressing DEFLATE compressed streams. * If set, the <a href="https://github.com/Intel-HLS/GKL">GKL library</a> must be * provided on the classpath. */ public static final String USE_INTEL_INFLATER_PROPERTY = "hadoopbam.bam.use-intel-inflater"; /** * Only include reads that overlap the given intervals. Unplaced unmapped reads are not * included. * @param conf the Hadoop configuration to set properties on * @param intervals the intervals to filter by * @param <T> the {@link Locatable} type */ public static <T extends Locatable> void setIntervals(Configuration conf, List<T> intervals) { setTraversalParameters(conf, intervals, false); } /** * Enables or disables the split calculator that uses the BAM index to calculate splits. */ public static void setEnableBAISplitCalculator(Configuration conf, boolean setEnabled) { conf.setBoolean(ENABLE_BAI_SPLIT_CALCULATOR, setEnabled); } /** * Only include reads that overlap the given intervals (if specified) and unplaced * unmapped reads (if <code>true</code>). * @param conf the Hadoop configuration to set properties on * @param intervals the intervals to filter by, or <code>null</code> if all reads * are to be included (in which case <code>traverseUnplacedUnmapped</code> must be * <code>true</code>) * @param traverseUnplacedUnmapped whether to included unplaced unampped reads * @param <T> the {@link Locatable} type */ public static <T extends Locatable> void setTraversalParameters(Configuration conf, List<T> intervals, boolean traverseUnplacedUnmapped) { if (intervals == null && !traverseUnplacedUnmapped) { throw new IllegalArgumentException("Traversing mapped reads only is not supported."); } conf.setBoolean(BOUNDED_TRAVERSAL_PROPERTY, true); if (intervals != null) { StringBuilder sb = new StringBuilder(); for (Iterator<T> it = intervals.iterator(); it.hasNext(); ) { Locatable l = it.next(); sb.append(String.format("%s:%d-%d", l.getContig(), l.getStart(), l.getEnd())); if (it.hasNext()) { sb.append(","); } } conf.set(INTERVALS_PROPERTY, sb.toString()); } conf.setBoolean(TRAVERSE_UNPLACED_UNMAPPED_PROPERTY, traverseUnplacedUnmapped); } /** * Reset traversal parameters so that all reads are included. * @param conf the Hadoop configuration to set properties on */ public static void unsetTraversalParameters(Configuration conf) { conf.unset(BOUNDED_TRAVERSAL_PROPERTY); conf.unset(INTERVALS_PROPERTY); conf.unset(TRAVERSE_UNPLACED_UNMAPPED_PROPERTY); } static boolean isBoundedTraversal(Configuration conf) { return conf.getBoolean(BOUNDED_TRAVERSAL_PROPERTY, false) || conf.get(INTERVALS_PROPERTY) != null; // backwards compatibility } static boolean traverseUnplacedUnmapped(Configuration conf) { return conf.getBoolean(TRAVERSE_UNPLACED_UNMAPPED_PROPERTY, false); } static List<Interval> getIntervals(Configuration conf) { return IntervalUtil.getIntervals(conf, INTERVALS_PROPERTY); } static boolean useIntelInflater(Configuration conf) { return conf.getBoolean(USE_INTEL_INFLATER_PROPERTY, false); } static Path getIdxPath(Path path) { return path.suffix(SplittingBAMIndexer.OUTPUT_FILE_EXTENSION); } static List<InputSplit> removeIndexFiles(List<InputSplit> splits) { // Remove any splitting bai files return splits.stream() .filter(split -> !((FileSplit) split).getPath().getName().endsWith( SplittingBAMIndexer.OUTPUT_FILE_EXTENSION)) .filter(split -> !((FileSplit) split).getPath().getName().endsWith( BAMIndex.BAMIndexSuffix)) .collect(Collectors.toList()); } static Path getBAIPath(Path path) { return path.suffix(BAMIndex.BAMIndexSuffix); } /** Returns a {@link BAMRecordReader} initialized with the parameters. */ @Override public RecordReader<LongWritable,SAMRecordWritable> createRecordReader(InputSplit split, TaskAttemptContext ctx) throws InterruptedException, IOException { final RecordReader<LongWritable,SAMRecordWritable> rr = new BAMRecordReader(); rr.initialize(split, ctx); return rr; } /** The splits returned are {@link FileVirtualSplit FileVirtualSplits}. */ @Override public List<InputSplit> getSplits(JobContext job) throws IOException { return getSplits(super.getSplits(job), job.getConfiguration()); } public List<InputSplit> getSplits( List<InputSplit> splits, Configuration cfg) throws IOException { final List<InputSplit> origSplits = removeIndexFiles(splits); // Align the splits so that they don't cross blocks. // addIndexedSplits() requires the given splits to be sorted by file // path, so do so. Although FileInputFormat.getSplits() does, at the time // of writing this, generate them in that order, we shouldn't rely on it. Collections.sort(origSplits, new Comparator<InputSplit>() { public int compare(InputSplit a, InputSplit b) { FileSplit fa = (FileSplit)a, fb = (FileSplit)b; return fa.getPath().compareTo(fb.getPath()); } }); final List<InputSplit> newSplits = new ArrayList<InputSplit>(origSplits.size()); for (int i = 0; i < origSplits.size();) { try { i = addIndexedSplits (origSplits, i, newSplits, cfg); } catch (IOException | ProviderNotFoundException e) { if (cfg.getBoolean(ENABLE_BAI_SPLIT_CALCULATOR, false)) { try { i = addBAISplits (origSplits, i, newSplits, cfg); } catch (IOException | ProviderNotFoundException e2) { i = addProbabilisticSplits (origSplits, i, newSplits, cfg); } } else { i = addProbabilisticSplits (origSplits, i, newSplits, cfg); } } } return filterByInterval(newSplits, cfg); } // Handles all the splits that share the Path of the one at index i, // returning the next index to be used. private int addIndexedSplits( List<InputSplit> splits, int i, List<InputSplit> newSplits, Configuration cfg) throws IOException { final Path file = ((FileSplit)splits.get(i)).getPath(); List<InputSplit> potentialSplits = new ArrayList<InputSplit>(); final SplittingBAMIndex idx = new SplittingBAMIndex( file.getFileSystem(cfg).open(getIdxPath(file))); int splitsEnd = splits.size(); for (int j = i; j < splitsEnd; ++j) if (!file.equals(((FileSplit)splits.get(j)).getPath())) splitsEnd = j; if (idx.size() == 1) { // no alignments, only the file size, so no splits to add return splitsEnd; } for (int j = i; j < splitsEnd; ++j) { final FileSplit fileSplit = (FileSplit)splits.get(j); final long start = fileSplit.getStart(); final long end = start + fileSplit.getLength(); final Long blockStart = idx.nextAlignment(start); // The last split needs to end where the last alignment ends, but the // index doesn't store that data (whoops); we only know where the last // alignment begins. Fortunately there's no need to change the index // format for this: we can just set the end to the maximal length of // the final BGZF block (0xffff), and then read until BAMRecordCodec // hits EOF. Long blockEnd; if (j == splitsEnd - 1) { blockEnd = idx.prevAlignment(end) | 0xffff; } else { blockEnd = idx.nextAlignment(end); } if (blockStart == null || blockEnd == null) { logger.warn("Index for {} was not good. Generating probabilistic splits.", file); return addProbabilisticSplits(splits, i, newSplits, cfg); } potentialSplits.add(new FileVirtualSplit( file, blockStart, blockEnd, fileSplit.getLocations())); } for (InputSplit s : potentialSplits) { newSplits.add(s); } return splitsEnd; } // Handles all the splits that share the Path of the one at index i, // returning the next index to be used. private int addBAISplits(List<InputSplit> splits, int i, List<InputSplit> newSplits, Configuration conf) throws IOException { int splitsEnd = i; final Path path = ((FileSplit)splits.get(i)).getPath(); final Path baiPath = getBAIPath(path); final FileSystem fs = path.getFileSystem(conf); final Path sinPath; if (fs.exists(baiPath)) { sinPath = baiPath; } else { sinPath = new Path(path.toString().replaceFirst("\\.bam$", BAMIndex.BAMIndexSuffix)); } try (final FSDataInputStream in = fs.open(path); final SeekableStream guesserSin = WrapSeekable.openPath(fs, path); final SeekableStream sin = WrapSeekable.openPath(fs, sinPath)) {
SAMFileHeader header = SAMHeaderReader.readSAMHeaderFrom(in, conf);
3
contentful/contentful.java
src/test/java/com/contentful/java/cda/integration/IntegrationWithMasterEnvironment.java
[ "public class CDAAsset extends LocalizedResource {\n\n private static final long serialVersionUID = -4645571481643616657L;\n\n /**\n * @return title of this asset.\n */\n public String title() {\n return getField(\"title\");\n }\n\n /**\n * @return url to the file of this asset.\n */\n public Strin...
import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAClient; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDALocale; import com.contentful.java.cda.CDASpace; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.util.List; import static com.contentful.java.cda.CDAType.SPACE; import static com.contentful.java.cda.SyncType.onlyDeletedAssets; import static com.google.common.truth.Truth.assertThat;
package com.contentful.java.cda.integration; public class IntegrationWithMasterEnvironment extends Integration { @Override public void setUp() { client = CDAClient.builder() .setSpace("5s4tdjmyjfpl") .setToken("84017d3a5da6d3ae9c733c6c210c55eebc3da033730b4e5093a6e6aa099b4995") .setEnvironment("master") .build(); } // space id and so on changed on master @Override public void fetchSpace() { CDASpace space = client.fetchSpace(); assertThat(space.name()).isEqualTo("Contentful Example API with En"); assertThat(space.id()).isEqualTo("5s4tdjmyjfpl"); assertThat(space.type()).isEqualTo(SPACE); } // asset url changed between master and staging @Override public void fetchSpecificAsset() { CDAAsset entry = client.fetch(CDAAsset.class).one("nyancat"); assertThat(entry.url()).isEqualTo("//images.ctfassets.net/5s4tdjmyjfpl/nyancat/" + "28850673d35cacb94192832b5f5c1960/Nyan_cat_250px_frame.png"); } // locales have different ids @Override public void fetchOneLocale() { final CDALocale found = client.fetch(CDALocale.class).one("4pPeIa89F7KD3G1q47eViY"); assertThat(found.code()).isEqualTo("en-US"); assertThat(found.name()).isEqualTo("English"); assertThat(found.fallbackLocaleCode()).isNull(); assertThat(found.isDefaultLocale()).isTrue(); } @Override void assertNyanCat(CDAEntry entry) { assertThat(entry.id()).isEqualTo("nyancat"); assertThat(entry.<String>getField("name")).isEqualTo("Nyan Cat"); assertThat(entry.<String>getField("color")).isEqualTo("rainbow"); assertThat(entry.<String>getField("birthday")).isEqualTo("2011-04-04T22:00+00:00"); assertThat(entry.<Double>getField("lives")).isEqualTo(1337.0); List<String> likes = entry.getField("likes"); assertThat(likes).containsExactly("rainbows", "fish"); Object bestFriend = entry.getField("bestFriend"); assertThat(bestFriend).isInstanceOf(CDAEntry.class); assertThat(entry).isSameAs(((CDAEntry) bestFriend).getField("bestFriend")); // Localization final LocalizedResource.Localizer localized = entry.localize("tlh"); assertThat(localized.<String>getField("color")).isEqualTo("rainbow"); assertThat(localized.<Object>getField("non-existing-does-not-throw")).isNull(); } @Override public void syncTypeOfDeletedAssets() {
final SynchronizedSpace space = client.sync(onlyDeletedAssets()).fetch();
6
jenkinsci/priority-sorter-plugin
src/main/java/jenkins/advancedqueue/PrioritySorterConfiguration.java
[ "public static class PriorityStrategyHolder {\n\tprivate int id = 0;\n\tprivate PriorityStrategy priorityStrategy;\n\n\tpublic PriorityStrategyHolder() {\n\t}\n\n\t@DataBoundConstructor\n\tpublic PriorityStrategyHolder(int id, PriorityStrategy priorityStrategy) {\n\t\tthis.id = id;\n\t\tthis.priorityStrategy = prio...
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Job; import hudson.security.ACL; import hudson.security.ACLContext; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import jenkins.advancedqueue.JobGroup.PriorityStrategyHolder; import jenkins.advancedqueue.priority.strategy.PriorityJobProperty; import jenkins.advancedqueue.sorter.SorterStrategy; import jenkins.advancedqueue.sorter.SorterStrategyDescriptor; import jenkins.advancedqueue.sorter.strategy.AbsoluteStrategy; import jenkins.advancedqueue.sorter.strategy.MultiBucketStrategy; import jenkins.advancedqueue.util.PrioritySorterUtil; import jenkins.model.GlobalConfiguration; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest;
/* * The MIT License * * Copyright (c) 2013, Magnus Sandberg * * 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 jenkins.advancedqueue; /** * @author Magnus Sandberg * @since 2.0 */ @Extension public class PrioritySorterConfiguration extends GlobalConfiguration { private final static Logger LOGGER = Logger.getLogger(PrioritySorterConfiguration.class.getName()); private final static SorterStrategy DEFAULT_STRATEGY = new AbsoluteStrategy( MultiBucketStrategy.DEFAULT_PRIORITIES_NUMBER, MultiBucketStrategy.DEFAULT_PRIORITY); /** * @deprecated used in 2.x - replaces with XXX */ @Deprecated private boolean allowPriorityOnJobs; private boolean onlyAdminsMayEditPriorityConfiguration = false; private SorterStrategy strategy; public PrioritySorterConfiguration() { } public static void init() { PrioritySorterConfiguration prioritySorterConfiguration = PrioritySorterConfiguration.get(); // Make sure default is good for updating from legacy prioritySorterConfiguration.strategy = DEFAULT_STRATEGY; // TODO: replace with class ref prioritySorterConfiguration.allowPriorityOnJobs = false; prioritySorterConfiguration.load(); } @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { int prevNumberOfPriorities = strategy.getNumberOfPriorities(); strategy = req.bindJSON(SorterStrategy.class, json.getJSONObject("strategy")); int newNumberOfPriorities = strategy.getNumberOfPriorities(); FormValidation numberOfPrioritiesCheck = doCheckNumberOfPriorities(String.valueOf(newNumberOfPriorities)); if (numberOfPrioritiesCheck.kind != FormValidation.Kind.OK) { throw new FormException(numberOfPrioritiesCheck.getMessage(), "numberOfPriorities"); } // onlyAdminsMayEditPriorityConfiguration = json.getBoolean("onlyAdminsMayEditPriorityConfiguration"); // updatePriorities(prevNumberOfPriorities); // save(); return true; } public boolean getOnlyAdminsMayEditPriorityConfiguration() { return onlyAdminsMayEditPriorityConfiguration; } public SorterStrategy getStrategy() { return strategy; } public ListBoxModel doFillStrategyItems() { ListBoxModel strategies = new ListBoxModel();
List<SorterStrategyDescriptor> values = SorterStrategy.getAllSorterStrategies();
3
ni3po42/traction.mvc
traction/src/main/java/traction/mvc/implementations/ui/menubinding/MenuBinding.java
[ "public class BindingInventory\n extends ObservableObject\n{\n\t/**\n\t * patterns for parsing property chains\n\t */\n\tprivate final static Pattern pathPattern = Pattern.compile(\"(\\\\\\\\|[\\\\.]*)(.+)\");\n\tprivate final static Pattern split = Pattern.compile(\"\\\\.\");\n\n\t//used for determining a range...
import android.view.MenuItem; import android.view.View; import org.json.JSONException; import org.json.JSONObject; import traction.mvc.observables.BindingInventory; import traction.mvc.implementations.ui.UIEvent; import traction.mvc.implementations.ui.UIHandler; import traction.mvc.implementations.ui.UIProperty; import traction.mvc.implementations.ui.viewbinding.ViewBindingHelper; import traction.mvc.interfaces.IProxyViewBinding; import traction.mvc.interfaces.IUIElement; import traction.mvc.interfaces.IViewBinding;
/* Copyright 2013 Tim Stratton 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 traction.mvc.implementations.ui.menubinding; /** * Defines the ui elements that can bind a model/view-model to a menu item * @author Tim Stratton * */ public class MenuBinding implements MenuItem.OnMenuItemClickListener, IProxyViewBinding { public final UIProperty<Boolean> IsVisible; public final UIEvent OnClick; private final MenuItem menuItem; private JSONObject tagProperties; private final ViewBindingHelper<View> helper; public MenuBinding(MenuItem item, String tag) { this.menuItem = item; try { this.tagProperties = new JSONObject(tag); } catch (JSONException ex) { } helper = new ViewBindingHelper<View>() { @Override public View getWidget() { return menuItem.getActionView(); } @Override public void detachBindings() { super.detachBindings(); MenuBinding.this.detachBindings(); } @Override
public void initialise(View notUsed, UIHandler uiHandler, BindingInventory inventory, int bindingFlags)
2
achellies/AtlasForAndroid
src/android/taobao/atlas/hack/AtlasHacks.java
[ "public static interface AssertionFailureHandler {\n boolean onAssertionFailure(HackAssertionException hackAssertionException);\n}", "public static abstract class HackDeclaration {\n\n public static class HackAssertionException extends Throwable {\n private static final long serialVersionUID = 1;\n ...
import android.app.Application; import android.app.Instrumentation; import android.app.Service; import android.content.Context; import android.content.ContextWrapper; import android.content.res.AssetManager; import android.content.res.Resources; import android.content.res.Resources.Theme; import android.os.Build.VERSION; import android.taobao.atlas.hack.Hack.AssertionFailureHandler; import android.taobao.atlas.hack.Hack.HackDeclaration; import android.taobao.atlas.hack.Hack.HackDeclaration.HackAssertionException; import android.taobao.atlas.hack.Hack.HackedClass; import android.taobao.atlas.hack.Hack.HackedField; import android.taobao.atlas.hack.Hack.HackedMethod; import android.taobao.atlas.log.Logger; import android.taobao.atlas.log.LoggerFactory; import android.view.ContextThemeWrapper; import dalvik.system.DexClassLoader; import java.util.ArrayList; import java.util.Map;
package android.taobao.atlas.hack; public class AtlasHacks extends HackDeclaration implements AssertionFailureHandler { public static HackedClass<Object> ActivityThread;
public static HackedMethod ActivityThread_currentActivityThread;
5
mariok/pinemup
src/main/java/net/sourceforge/pinemup/ui/swing/tray/TrayMenuUpdater.java
[ "public class CategoryAddedEvent extends EventObject {\n private static final long serialVersionUID = 3366814253028410097L;\n\n private final Category addedCategory;\n\n public CategoryAddedEvent(PinBoard source, Category addedCategory) {\n super(source);\n this.addedCategory = addedCategory;\n }\...
import net.sourceforge.pinemup.core.model.CategoryAddedEvent; import net.sourceforge.pinemup.core.model.CategoryAddedEventListener; import net.sourceforge.pinemup.core.model.CategoryChangedEvent; import net.sourceforge.pinemup.core.model.CategoryChangedEventListener; import net.sourceforge.pinemup.core.model.CategoryRemovedEvent; import net.sourceforge.pinemup.core.model.CategoryRemovedEventListener; import net.sourceforge.pinemup.core.settings.UserSettingsChangedEvent; import net.sourceforge.pinemup.core.settings.UserSettingsChangedEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package net.sourceforge.pinemup.ui.swing.tray; public class TrayMenuUpdater implements CategoryChangedEventListener, UserSettingsChangedEventListener, CategoryAddedEventListener, CategoryRemovedEventListener { private static final Logger LOG = LoggerFactory.getLogger(TrayMenuUpdater.class); private final TrayMenu trayMenu; public TrayMenuUpdater(TrayMenu trayMenu) { this.trayMenu = trayMenu; } @Override public void settingsChanged(UserSettingsChangedEvent event) { trayMenu.initWithNewLanguage(); } @Override
public void categoryChanged(CategoryChangedEvent event) {
2
PearsonEducation/StatsPoller
src/main/java/com/pearson/statspoller/internal_metric_collectors/InternalCollectorFramework.java
[ "public class ApplicationConfiguration {\n\n private static final Logger logger = LoggerFactory.getLogger(ApplicationConfiguration.class.getName());\n \n public static final int VALUE_NOT_SET_CODE = -4444;\n \n private static boolean isInitializeSuccess_ = false; \n \n private static Hierarchic...
import com.pearson.statspoller.globals.ApplicationConfiguration; import com.pearson.statspoller.globals.GlobalVariables; import java.util.List; import com.pearson.statspoller.metric_formats.graphite.GraphiteMetric; import com.pearson.statspoller.metric_formats.opentsdb.OpenTsdbMetric; import com.pearson.statspoller.utilities.core_utils.StackTrace; import com.pearson.statspoller.utilities.core_utils.Threads; import com.pearson.statspoller.utilities.file_utils.FileIo; import java.util.ArrayList; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.pearson.statspoller.internal_metric_collectors; /** * @author Jeffrey Schmidt */ public abstract class InternalCollectorFramework { private static final Logger logger = LoggerFactory.getLogger(InternalCollectorFramework.class.getName()); protected final int NUM_FILE_WRITE_RETRIES = 3; protected final int DELAY_BETWEEN_WRITE_RETRIES_IN_MS = 100; private final boolean isEnabled_; private final long collectionInterval_; private final String internalCollectorMetricPrefix_; private final String outputFilePathAndFilename_; private final boolean writeOutputFiles_; private final String linuxProcFileSystemLocation_ = removeTrailingSlash(ApplicationConfiguration.getLinuxProcLocation()); private final String linuxSysFileSystemLocation_ = removeTrailingSlash(ApplicationConfiguration.getLinuxSysLocation()); private String fullInternalCollectorMetricPrefix_ = null; private String finalOutputFilePathAndFilename_ = null; public InternalCollectorFramework(boolean isEnabled, long collectionInterval, String internalCollectorMetricPrefix, String outputFilePathAndFilename, boolean writeOutputFiles) { this.isEnabled_ = isEnabled; this.collectionInterval_ = collectionInterval; this.internalCollectorMetricPrefix_ = internalCollectorMetricPrefix; this.outputFilePathAndFilename_ = outputFilePathAndFilename; this.writeOutputFiles_ = writeOutputFiles; createFullInternalCollectorMetricPrefix(); this.finalOutputFilePathAndFilename_ = this.outputFilePathAndFilename_; } public void outputGraphiteMetrics(List<GraphiteMetric> graphiteMetrics) { if (graphiteMetrics == null) return; for (GraphiteMetric graphiteMetric : graphiteMetrics) { try { if (graphiteMetric == null) continue; String graphiteMetricPathWithPrefix = fullInternalCollectorMetricPrefix_ + graphiteMetric.getMetricPath(); GraphiteMetric outputGraphiteMetric = new GraphiteMetric(graphiteMetricPathWithPrefix, graphiteMetric.getMetricValue(), graphiteMetric.getMetricTimestampInSeconds()); outputGraphiteMetric.setHashKey(GlobalVariables.metricHashKeyGenerator.incrementAndGet()); GlobalVariables.graphiteMetrics.put(outputGraphiteMetric.getHashKey(), outputGraphiteMetric); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } } if (writeOutputFiles_) { String outputString = buildGraphiteMetricsFile(graphiteMetrics, true, fullInternalCollectorMetricPrefix_); writeGraphiteMetricsToFile(outputString); } } public void outputOpentsdbMetricsAsGraphiteMetrics(List<OpenTsdbMetric> openTsdbMetrics) { if (openTsdbMetrics == null) return; for (OpenTsdbMetric openTsdbMetric : openTsdbMetrics) { try { if (openTsdbMetric == null) continue; String metricNameWithPrefix = fullInternalCollectorMetricPrefix_ + openTsdbMetric.getMetric(); GraphiteMetric outputGraphiteMetric = new GraphiteMetric(metricNameWithPrefix, openTsdbMetric.getMetricValue(), openTsdbMetric.getMetricTimestampInSeconds()); outputGraphiteMetric.setHashKey(GlobalVariables.metricHashKeyGenerator.incrementAndGet()); GlobalVariables.graphiteMetrics.put(outputGraphiteMetric.getHashKey(), outputGraphiteMetric); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } } if (writeOutputFiles_) { List<GraphiteMetric> graphiteMetrics = new ArrayList<>(); for (OpenTsdbMetric openTsdbMetric : openTsdbMetrics) { try { if (openTsdbMetric == null) continue; GraphiteMetric graphiteMetric = new GraphiteMetric(openTsdbMetric.getMetric(), openTsdbMetric.getMetricValue(), openTsdbMetric.getMetricTimestampInSeconds()); graphiteMetrics.add(graphiteMetric); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } } String outputString = buildGraphiteMetricsFile(graphiteMetrics, true, fullInternalCollectorMetricPrefix_); writeGraphiteMetricsToFile(outputString); } } public void outputOpenTsdbMetrics(List<OpenTsdbMetric> openTsdbMetrics) { if (openTsdbMetrics == null) return; for (OpenTsdbMetric openTsdbMetric : openTsdbMetrics) { try { if (openTsdbMetric == null) continue; String metricNameWithPrefix = fullInternalCollectorMetricPrefix_ + openTsdbMetric.getMetric(); OpenTsdbMetric outputOpenTsdbMetric = new OpenTsdbMetric(metricNameWithPrefix, openTsdbMetric.getMetricTimestampInMilliseconds(), openTsdbMetric.getMetricValue(), openTsdbMetric.getTags()); outputOpenTsdbMetric.setHashKey(GlobalVariables.metricHashKeyGenerator.incrementAndGet()); GlobalVariables.openTsdbMetrics.put(outputOpenTsdbMetric.getHashKey(), outputOpenTsdbMetric); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } } if (writeOutputFiles_) { String outputString = buildOpenTsdbMetricsFile(openTsdbMetrics, true, fullInternalCollectorMetricPrefix_); writeGraphiteMetricsToFile(outputString); } } private void writeGraphiteMetricsToFile(String output) { if ((output == null) || output.isEmpty()) { return; } boolean isSuccessfulWrite; try { for (int i = 0; i <= NUM_FILE_WRITE_RETRIES; i++) { isSuccessfulWrite = FileIo.saveStringToFile(finalOutputFilePathAndFilename_, output); if (isSuccessfulWrite) break;
else Threads.sleepMilliseconds(DELAY_BETWEEN_WRITE_RETRIES_IN_MS);
5
Terracotta-OSS/offheap-store
src/test/java/org/terracotta/offheapstore/paging/EvictionRefusalStealingIT.java
[ "public class UpfrontAllocatingPageSource implements PageSource {\n\n public static final String ALLOCATION_LOG_LOCATION = UpfrontAllocatingPageSource.class.getName() + \".allocationDump\";\n\n private static final Logger LOGGER = LoggerFactory.getLogger(UpfrontAllocatingPageSource.class);\n private static...
import org.terracotta.offheapstore.paging.UnlimitedPageSource; import org.terracotta.offheapstore.paging.UpfrontAllocatingPageSource; import org.terracotta.offheapstore.paging.PageSource; import java.util.Map; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Assert; import org.junit.Test; import org.terracotta.offheapstore.OffHeapHashMap; import org.terracotta.offheapstore.ReadWriteLockedOffHeapClockCache; import org.terracotta.offheapstore.WriteLockedOffHeapClockCache; import org.terracotta.offheapstore.buffersource.HeapBufferSource; import org.terracotta.offheapstore.concurrent.AbstractConcurrentOffHeapCache; import org.terracotta.offheapstore.concurrent.ConcurrentOffHeapHashMap; import org.terracotta.offheapstore.exceptions.OversizeMappingException; import org.terracotta.offheapstore.storage.IntegerStorageEngine; import org.terracotta.offheapstore.storage.OffHeapBufferHalfStorageEngine; import org.terracotta.offheapstore.storage.SplitStorageEngine; import org.terracotta.offheapstore.storage.StorageEngine; import org.terracotta.offheapstore.storage.portability.ByteArrayPortability; import org.terracotta.offheapstore.util.Factory;
/* * Copyright 2015 Terracotta, Inc., a Software AG company. * * 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.terracotta.offheapstore.paging; public class EvictionRefusalStealingIT { @Test public void testDataSpaceIsStolen() { long seed = System.nanoTime(); System.out.println("EvictionRefusalStealingTest.testDataSpaceIsStolen seed = " + seed); Random rndm = new Random(seed);
PageSource source = new UpfrontAllocatingPageSource(new HeapBufferSource(), 1024 * 1024, 1024 * 1024);
0
ralscha/wampspring
src/test/java/ch/rasc/wampspring/method/WampMessageTypeMessageConditionTest.java
[ "public class CallMessage extends WampMessage {\n\tprivate final String callID;\n\n\tprivate final String procURI;\n\n\tprivate final List<Object> arguments;\n\n\tpublic CallMessage(String callID, String procURI, Object... arguments) {\n\t\tsuper(WampMessageType.CALL);\n\t\tthis.callID = callID;\n\t\tthis.procURI =...
import static org.assertj.core.api.Assertions.assertThat; import java.util.Collection; import org.junit.Test; import ch.rasc.wampspring.message.CallMessage; import ch.rasc.wampspring.message.PublishMessage; import ch.rasc.wampspring.message.SubscribeMessage; import ch.rasc.wampspring.message.UnsubscribeMessage; import ch.rasc.wampspring.message.WampMessageType;
/** * Copyright 2014-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.wampspring.method; public class WampMessageTypeMessageConditionTest { @Test public void testGetMessageType() { assertThat(WampMessageTypeMessageCondition.CALL.getMessageType()) .isEqualTo(WampMessageType.CALL); assertThat(WampMessageTypeMessageCondition.PUBLISH.getMessageType()) .isEqualTo(WampMessageType.PUBLISH); assertThat(WampMessageTypeMessageCondition.SUBSCRIBE.getMessageType()) .isEqualTo(WampMessageType.SUBSCRIBE); assertThat(WampMessageTypeMessageCondition.UNSUBSCRIBE.getMessageType()) .isEqualTo(WampMessageType.UNSUBSCRIBE); WampMessageTypeMessageCondition cond = new WampMessageTypeMessageCondition( WampMessageType.CALL); assertThat(cond.getMessageType()).isEqualTo(WampMessageType.CALL); } @SuppressWarnings("unchecked") @Test public void testGetContent() { assertThat((Collection<WampMessageType>) WampMessageTypeMessageCondition.CALL .getContent()).hasSize(1).containsExactly(WampMessageType.CALL); assertThat((Collection<WampMessageType>) WampMessageTypeMessageCondition.PUBLISH .getContent()).hasSize(1).containsExactly(WampMessageType.PUBLISH); assertThat((Collection<WampMessageType>) WampMessageTypeMessageCondition.SUBSCRIBE .getContent()).hasSize(1).containsExactly(WampMessageType.SUBSCRIBE); assertThat( (Collection<WampMessageType>) WampMessageTypeMessageCondition.UNSUBSCRIBE .getContent()).hasSize(1) .containsExactly(WampMessageType.UNSUBSCRIBE); WampMessageTypeMessageCondition cond = new WampMessageTypeMessageCondition( WampMessageType.CALL); assertThat((Collection<WampMessageType>) cond.getContent()).hasSize(1) .containsExactly(WampMessageType.CALL); } @Test public void testGetMatchingCondition() { CallMessage cm = new CallMessage("1", "proc");
SubscribeMessage sm = new SubscribeMessage("proc");
2
lemberg/d8androidsdk
sample/src/main/java/com/ls/drupal8demo/adapters/CategoryArticlesListAdapter.java
[ "public abstract class AbstractBaseDrupalEntity implements DrupalClient.OnResponseListener, ICharsetItem\n{\n\ttransient private DrupalClient drupalClient; \n\n\ttransient private Snapshot snapshot;\n\n\t/**\n\t * In case of request canceling - no method will be triggered.\n\t * \n\t * @author lemberg\n\t * \n\t */...
import com.android.volley.RequestQueue; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.ImageLoader.ImageCache; import com.android.volley.toolbox.Volley; import com.ls.drupal.AbstractBaseDrupalEntity; import com.ls.drupal.AbstractBaseDrupalEntity.OnEntityRequestListener; import com.ls.drupal.DrupalClient; import com.ls.drupal8demo.R; import com.ls.drupal8demo.article.ArticlePreview; import com.ls.drupal8demo.article.Page; import com.ls.http.base.ResponseData; import com.ls.util.L; import com.ls.util.image.DrupalImageView; import android.content.Context; import android.graphics.Bitmap; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.List;
/** * The MIT License (MIT) * Copyright (c) 2014 Lemberg Solutions Limited * 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 com.ls.drupal8demo.adapters; public class CategoryArticlesListAdapter extends BaseAdapter implements OnEntityRequestListener { private final static int PRE_LOADING_PAGE_OFFSET = 4; private int mPagesLoaded = 0; private boolean mCanLoadMore; private Page mArticlePreviews; private final DrupalClient mDrupalClient; private final LayoutInflater mInflater; private ImageLoader mImageLoader; private String mCategoryId; private View mEmptyView; private final List<ArticlePreview> mArticlePreviewList; public CategoryArticlesListAdapter(String theCategoryId, DrupalClient theClient, Context theContext, View emptyView) { mEmptyView = emptyView; mArticlePreviewList = new ArrayList<ArticlePreview>(); mInflater = LayoutInflater.from(theContext); mDrupalClient = theClient; setCanLoadMore(true); mCategoryId = theCategoryId; initImageLoader(theContext); loadNextPage(); } private void initImageLoader(Context theContext) { RequestQueue queue = Volley.newRequestQueue(theContext); mImageLoader = new ImageLoader(queue, new ImageCache() { @Override public void putBitmap(String url, Bitmap bitmap) { } @Override public Bitmap getBitmap(String url) { return null; } }); } @Override public int getCount() { return mArticlePreviewList.size(); } @Override public ArticlePreview getItem(int position) { return mArticlePreviewList.get(position); } @Override public long getItemId(int position) { return position; } public void setCanLoadMore(boolean canLoadMore) { mCanLoadMore = canLoadMore; if (!mCanLoadMore && mArticlePreviewList.isEmpty()) { mEmptyView.setVisibility(View.VISIBLE); } else { mEmptyView.setVisibility(View.INVISIBLE); } } @Override public View getView(int position, View convertView, ViewGroup parent) { if (position > mArticlePreviewList.size() - PRE_LOADING_PAGE_OFFSET) { loadNextPage(); } if (convertView == null) { convertView = mInflater.inflate(R.layout.list_item_article, null); } ArticlePreview item = mArticlePreviewList.get(position); if (item != null) { TextView title = (TextView) convertView.findViewById(R.id.title); title.setText(Html.fromHtml(item.getTitle()).toString()); TextView author = (TextView) convertView.findViewById(R.id.author); View byView = convertView.findViewById(R.id.by); String authorName = item.getAuthor(); if (authorName != null && !authorName.isEmpty()) { author.setText(authorName); byView.setVisibility(View.VISIBLE); author.setVisibility(View.VISIBLE); } else { byView.setVisibility(View.INVISIBLE); author.setVisibility(View.INVISIBLE); } TextView date = (TextView) convertView.findViewById(R.id.date); date.setText(item.getDate()); TextView description = (TextView) convertView.findViewById(R.id.description); String body = item.getBody(); CharSequence spannedBody = null; if(body != null) { spannedBody = Html.fromHtml(body); } description.setText(spannedBody);
DrupalImageView imageView = (DrupalImageView) convertView.findViewById(R.id.image);
7
tecsinapse/tecsinapse-data-io
src/main/java/br/com/tecsinapse/dataio/type/FileType.java
[ "public static final String MIME_XLS = \"application/vnd.ms-excel\";", "public static final String MIME_XLSM = \"application/vnd.ms-excel.sheet.macroEnabled.12\";", "public static final String MIME_XLSX = \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\";", "public static final String MSG_...
import static br.com.tecsinapse.dataio.util.Constants.MIME_XLS; import static br.com.tecsinapse.dataio.util.Constants.MIME_XLSM; import static br.com.tecsinapse.dataio.util.Constants.MIME_XLSX; import static br.com.tecsinapse.dataio.util.Constants.MSG_IGNORED; import java.io.IOException; import java.io.InputStream; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import lombok.AllArgsConstructor; import lombok.Getter; import br.com.tecsinapse.dataio.util.ExporterDateUtils;
/* * Tecsinapse Data Input and Output * * License: GNU Lesser General Public License (LGPL), version 3 or later * See the LICENSE file in the root directory or <http://www.gnu.org/licenses/lgpl-3.0.html>. */ package br.com.tecsinapse.dataio.type; @Getter @AllArgsConstructor public enum FileType {
XLS("MS Excel file (.xls)", MIME_XLS, ".xls") {
0
cloud-software-foundation/c5-replicator
c5-replicator-log/src/test/java/c5db/log/LogFileServiceTest.java
[ "public class C5CommonTestUtil {\n protected static final Logger LOG = LoggerFactory.getLogger(C5CommonTestUtil.class);\n\n public C5CommonTestUtil() {\n }\n\n /**\n * System property key to get base test directory value\n */\n public static final String BASE_TEST_DIRECTORY_KEY =\n \"test.build.data.b...
import c5db.C5CommonTestUtil; import c5db.MiscMatchers; import c5db.interfaces.replication.QuorumConfiguration; import c5db.log.generated.OLogHeader; import c5db.replication.generated.QuorumConfigurationMessage; import c5db.util.CheckedSupplier; import com.google.common.collect.Iterables; import com.google.common.primitives.Longs; import org.hamcrest.Matcher; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.file.Path; import java.util.List; import static c5db.log.EntryEncodingUtil.decodeAndCheckCrc; import static c5db.log.EntryEncodingUtil.encodeWithLengthAndCrc; import static c5db.log.LogMatchers.equalToHeader; import static c5db.log.LogPersistenceService.BytePersistence; import static c5db.log.ReplicatorLogGenericTestUtil.term; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue;
/* * Copyright 2014 WANdisco * * WANdisco 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 c5db.log; public class LogFileServiceTest { private static final String QUORUM_ID = "q"; private final Path testDirectory = (new C5CommonTestUtil()).getDataTestDir("log-file-service-test"); private LogFileService logFileService; @Before public void createTestObject() throws Exception { logFileService = new LogFileService(testDirectory); } @Test(expected = IOException.class) public void throwsAnIOExceptionIfAttemptingToAppendToTheFileAfterClosingIt() throws Exception { try (FilePersistence persistence = logFileService.create(QUORUM_ID)) { persistence.close(); persistence.append(serializedHeader(anOLogHeader())); } } @Test public void returnsNullWhenCallingGetCurrentWhenThereAreNoLogs() throws Exception { assertThat(logFileService.getCurrent(QUORUM_ID), nullValue()); } @Test public void returnsTheLatestAppendedPersistenceForAGivenQuorum() throws Exception { final OLogHeader header = anOLogHeader(); havingAppendedAPersistenceContainingHeader(header); try (BytePersistence persistence = logFileService.getCurrent(QUORUM_ID)) { assertThat(deserializedHeader(persistence), is(equalToHeader(header))); } } @Test public void returnsANewEmptyPersistenceOnEachCallToCreate() throws Exception { havingAppendedAPersistenceContainingHeader(anOLogHeader()); try (BytePersistence aSecondPersistence = logFileService.create(QUORUM_ID)) { assertThat(aSecondPersistence, isEmpty()); } } @Test public void appendsANewPersistenceSoThatItWillBeReturnedByFutureCallsToGetCurrent() throws Exception { final OLogHeader secondHeader; final long anArbitrarySeqNum = 1210; final long aGreaterArbitrarySeqNum = 1815; havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(anArbitrarySeqNum)); havingAppendedAPersistenceContainingHeader(secondHeader = anOLogHeaderWithSeqNum(aGreaterArbitrarySeqNum)); try (BytePersistence primaryPersistence = logFileService.getCurrent(QUORUM_ID)) { assertThat(deserializedHeader(primaryPersistence), is(equalToHeader(secondHeader))); } } @Test public void anExistingPersistenceRemainsUsableAfterBeingAppended() throws Exception { final OLogHeader header = anOLogHeader(); try (FilePersistence persistence = logFileService.create(QUORUM_ID)) { persistence.append(serializedHeader(header)); logFileService.append(QUORUM_ID, persistence); assertThat(deserializedHeader(persistence), is(equalToHeader(header))); } } @Test public void removesTheMostRecentAppendedDataStoreWhenTruncateIsCalled() throws Exception { final OLogHeader firstHeader; final long anArbitrarySeqNum = 1210; final long aGreaterArbitrarySeqNum = 1815; havingAppendedAPersistenceContainingHeader(firstHeader = anOLogHeaderWithSeqNum(anArbitrarySeqNum)); havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(aGreaterArbitrarySeqNum)); logFileService.truncate(QUORUM_ID); try (FilePersistence persistence = logFileService.getCurrent(QUORUM_ID)) { assertThat(deserializedHeader(persistence), is(equalToHeader(firstHeader))); } } @Test public void listsDataStoresInOrderOfMostRecentToLeastRecent() throws Exception { havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(1)); havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(2)); havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(3)); assertThat(logFileService.getList(QUORUM_ID), is(aListOfPersistencesWithSeqNums(3, 2, 1))); } @Test public void canArchiveAllButTheMostRecentFile() throws Exception { havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(1)); havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(2)); havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(3)); logFileService.archiveAllButCurrent(QUORUM_ID); assertThat(logFileService.getList(QUORUM_ID), is(aListOfPersistencesWithSeqNums(3))); } private void havingAppendedAPersistenceContainingHeader(OLogHeader header) throws Exception { try (FilePersistence persistenceToReplacePrimary = logFileService.create(QUORUM_ID)) { persistenceToReplacePrimary.append(serializedHeader(header)); logFileService.append(QUORUM_ID, persistenceToReplacePrimary); } } private static OLogHeader anOLogHeader() { return anOLogHeaderWithSeqNum(1); } private static OLogHeader anOLogHeaderWithSeqNum(long seqNum) { return new OLogHeader(term(1), seqNum, configurationOf(1, 2, 3)); } private ByteBuffer[] serializedHeader(OLogHeader header) {
List<ByteBuffer> buffers = encodeWithLengthAndCrc(OLogHeader.getSchema(), header);
4
PreibischLab/BigStitcher
src/main/java/net/preibisch/stitcher/gui/popup/RefineWithICPPopup.java
[ "public class SpimDataFilteringAndGrouping < AS extends AbstractSpimData< ? > >\n{\n\n\tpublic static List<Class<? extends Entity>> entityClasses = new ArrayList<>();\n\tstatic \n\t{\n\t\tentityClasses.add( TimePoint.class );\n\t\tentityClasses.add( Channel.class );\n\t\tentityClasses.add( Illumination.class );\n\t...
import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import mpicbg.spim.data.generic.AbstractSpimData; import mpicbg.spim.data.generic.sequence.AbstractSequenceDescription; import net.preibisch.legacy.io.IOFunctions; import net.preibisch.mvrecon.fiji.plugin.util.MouseOverPopUpStateChanger; import net.preibisch.mvrecon.fiji.plugin.util.MouseOverPopUpStateChanger.StateChanger; import net.preibisch.mvrecon.fiji.spimdata.SpimData2; import net.preibisch.mvrecon.fiji.spimdata.explorer.ExplorerWindow; import net.preibisch.mvrecon.fiji.spimdata.explorer.FilteredAndGroupedExplorerPanel; import net.preibisch.mvrecon.fiji.spimdata.explorer.GroupedRowWindow; import net.preibisch.mvrecon.fiji.spimdata.explorer.popup.ExplorerWindowSetable; import net.preibisch.mvrecon.fiji.spimdata.explorer.popup.Separator; import net.preibisch.stitcher.algorithm.SpimDataFilteringAndGrouping; import net.preibisch.stitcher.gui.overlay.DemoLinkOverlay; import net.preibisch.stitcher.process.ICPRefinement; import net.preibisch.stitcher.process.ICPRefinement.ICPRefinementParameters; import net.preibisch.stitcher.process.ICPRefinement.ICPType;
/*- * #%L * Multiview stitching of large datasets. * %% * Copyright (C) 2016 - 2021 Big Stitcher developers. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package net.preibisch.stitcher.gui.popup; public class RefineWithICPPopup extends JMenu implements ExplorerWindowSetable { private static final long serialVersionUID = 1L;
DemoLinkOverlay overlay;
1
i2p/i2p.itoopie
src/net/i2p/itoopie/i2pcontrol/methods/GetI2PControl.java
[ "public class InvalidParametersException extends Exception {\n\n\t/**\n\t * Signifies that the paramers we sent were invalid for the used JSONRPC2\n\t * method.\n\t */\n\tprivate static final long serialVersionUID = 4044188679464846005L;\n\n}", "public class InvalidPasswordException extends Exception {\n\n\t/**\n...
import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import net.i2p.itoopie.i2pcontrol.InvalidParametersException; import net.i2p.itoopie.i2pcontrol.InvalidPasswordException; import net.i2p.itoopie.i2pcontrol.JSONRPC2Interface; import net.i2p.itoopie.i2pcontrol.UnrecoverableFailedRequestException; import net.i2p.itoopie.i2pcontrol.methods.I2PControl.I2P_CONTROL; import com.thetransactioncompany.jsonrpc2.JSONRPC2Request; import com.thetransactioncompany.jsonrpc2.JSONRPC2Response; import com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException;
package net.i2p.itoopie.i2pcontrol.methods; public class GetI2PControl { public static EnumMap<I2P_CONTROL, Object> execute(I2P_CONTROL ... settings) throws InvalidPasswordException, JSONRPC2SessionException{
JSONRPC2Request req = new JSONRPC2Request("I2PControl", JSONRPC2Interface.incrNonce());
2
cfg4j/cfg4j
cfg4j-core/src/test/java/org/cfg4j/source/classpath/ClasspathConfigurationSourceTest.java
[ "public class DefaultEnvironment extends ImmutableEnvironment {\n /**\n * Constructs environment named \"\" (empty string).\n */\n public DefaultEnvironment() {\n super(\"\");\n }\n\n @Override\n public String toString() {\n return \"DefaultEnvironment{}\";\n }\n}", "public interface Environment {...
import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.assertj.core.data.MapEntry; import org.cfg4j.source.context.environment.DefaultEnvironment; import org.cfg4j.source.context.environment.Environment; import org.cfg4j.source.context.environment.ImmutableEnvironment; import org.cfg4j.source.context.environment.MissingEnvironmentException; import org.cfg4j.source.context.filesprovider.ConfigFilesProvider; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension;
/* * Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl) * * 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.cfg4j.source.classpath; @ExtendWith(MockitoExtension.class) class ClasspathConfigurationSourceTest { private TempConfigurationClasspathRepo classpathRepo; private ConfigFilesProvider configFilesProvider; private ClasspathConfigurationSource source; @BeforeEach void setUp() { classpathRepo = new TempConfigurationClasspathRepo(); source = new ClasspathConfigurationSource(); source.init(); } @AfterEach void tearDown() throws Exception { classpathRepo.close(); } @Test void getConfigurationReadsFromGivenPath() { Environment environment = new ImmutableEnvironment("otherApplicationConfigs"); assertThat(source.getConfiguration(environment)).containsOnly(MapEntry.entry("some.setting", "otherAppSetting")); } @Test void getConfigurationDisallowsLeadingSlashInClasspathLocation() { Environment environment = new ImmutableEnvironment("/otherApplicationConfigs"); assertThatThrownBy(() -> source.getConfiguration(environment)).isExactlyInstanceOf(MissingEnvironmentException.class); } @Test void getConfigurationReadsFromGivenFiles() { configFilesProvider = () -> Arrays.asList( Paths.get("application.properties"), Paths.get("otherConfig.properties") ); source = new ClasspathConfigurationSource(configFilesProvider);
assertThat(source.getConfiguration(new DefaultEnvironment())).containsOnlyKeys("some.setting", "otherConfig.setting");
0
maofw/anetty_client
src/com/netty/client/android/handler/NettyProcessorHandler.java
[ "public class ClientBroadcastReceiver extends BroadcastReceiver {\n\t// 消息通知\n\tpublic static final String NOTIFICATION_ACTION = \"com.netty.NOTIFICATION\";\n\t// 注册成功广播通知\n\tpublic static final String REG_ACTION = \"com.netty.REG\";\n\n\t@Override\n\tpublic void onReceive(Context context, Intent intent) {\n\t\ttry...
import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.Toast; import com.netty.client.android.broadcast.ClientBroadcastReceiver; import com.netty.client.android.listener.INettyHandlerListener; import com.netty.client.android.service.RemoteService; import com.netty.client.consts.SystemConsts; import com.netty.client.context.ApplicationContextClient; import com.xwtec.protoc.CommandProtoc;
package com.netty.client.android.handler; public class NettyProcessorHandler extends Handler { public static final int REGISTRATION_RESULT = 100; public static final int DEVICE_ONLINE_RESULT = 101; public static final int DEVICE_OFFLINE_RESULT = 102; public static final int MESSAGE = 103; private Context context; private ApplicationContextClient applicationContextClient; public NettyProcessorHandler(Context context) { this.context = context; this.applicationContextClient = RemoteService.getApplicationContextClient(); } /** * 消息处理方法 */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void handleMessage(Message msg) { if (msg != null) { Log.i(getClass().getName(), "-handleMessage:msg.what=" + msg.what); MessageObject mo = (MessageObject) msg.obj; if (mo == null) { return; }
INettyHandlerListener listener = applicationContextClient.getNettyHandlerListener(mo.getAppPackage(), msg.what);
1
azinik/ADRMine
release/v1/java_src/ADRMine/src/main/java/edu/asu/diego/adrmine/features/TokenClauseFeatures.java
[ "public class Negation {\n\t\n\tstatic ArrayList<String> modifier_rels = new ArrayList<String>(Arrays.asList(\"det\",\"neg\",\"amod\",\"advmod\",\"dep\",\"nn\",\"prep\"));\n\t\n\tpublic static ArrayList<String> getNegationModifierRelations()\n\t{\n\t\treturn modifier_rels;\n\t}\n\tpublic static boolean isWordNegate...
import java.util.List; import edu.asu.diego.adrmine.utils.Negation; import rainbownlp.core.Artifact; import rainbownlp.core.FeatureValuePair; import rainbownlp.core.FeatureValuePair.FeatureName; import rainbownlp.machineLearning.IFeatureCalculator; import rainbownlp.machineLearning.MLExample; import rainbownlp.machineLearning.MLExampleFeature; import rainbownlp.util.HibernateUtil;
/** * */ package edu.asu.diego.adrmine.features; /** * @author Azadeh * */ public class TokenClauseFeatures implements IFeatureCalculator { public static void main (String[] args) throws Exception { // String experimentgroup = TokenSequenceExampleBuilder.ExperimentGroupADRConcepts; String experimentgroup = args[0]; // List<MLExample> trainExamples = // MLExample.getAllExamples(experimentgroup, true); // int count=0; // // for (MLExample example:trainExamples) // { // // TokenClauseFeatures lbf = new TokenClauseFeatures(); // lbf.calculateFeatures(example); //// TokenDeepClusterFeatures cf = new TokenDeepClusterFeatures(); //// cf.calculateFeatures(example); // // count++; // // System.out.println("***train "+count+"/"+trainExamples.size()); // // } // HibernateUtil.clearLoaderSession(); //Test int count=0; List<MLExample> testExamples = MLExample.getAllExamples(experimentgroup, false); for (MLExample example:testExamples) { TokenClauseFeatures lbf = new TokenClauseFeatures(); lbf.calculateFeatures(example); // TokenDeepClusterFeatures cf = new TokenDeepClusterFeatures(); // cf.calculateFeatures(example); count++; System.out.println("***test "+count+"/"+testExamples.size()); } } @Override public void calculateFeatures(MLExample exampleToProcess) throws Exception { //get related artifact Artifact relatedArtifact = exampleToProcess.getRelatedArtifact(); // boolean is_negated_expanded = Negation.isWordNegatedExpanded(relatedArtifact, relatedArtifact.getParentArtifact()); boolean is_negated = Negation.isWordNegated(relatedArtifact, relatedArtifact.getParentArtifact()); // FeatureValuePair is_negated_exp_feature = FeatureValuePair.getInstance // (FeatureName.isTokenNegatedExpanded, is_negated_expanded?"1":"0"); // MLExampleFeature.setFeatureExample(exampleToProcess, is_negated_exp_feature); ////////
FeatureValuePair is_negated_feature = FeatureValuePair.getInstance
2
mariok/pinemup
src/main/java/net/sourceforge/pinemup/ui/swing/tray/TrayMenu.java
[ "public final class CategoryManager {\n /** The pinboard, which contains all notes. **/\n private PinBoard pinBoard = new PinBoard();\n\n /** Listeners, which will be added per default to new notes. **/\n private final Collection<NoteChangedEventListener> defaultNoteChangedEventListeners = new LinkedList<>(...
import java.awt.MenuItem; import java.awt.PopupMenu; import java.util.ArrayList; import java.util.List; import net.sourceforge.pinemup.core.CategoryManager; import net.sourceforge.pinemup.core.i18n.I18N; import net.sourceforge.pinemup.core.model.Category; import net.sourceforge.pinemup.ui.swing.menus.logic.CategoryMenuLogic; import net.sourceforge.pinemup.ui.swing.menus.logic.CategoryMenuLogic.CategoryAction; import net.sourceforge.pinemup.ui.swing.menus.logic.GeneralMenuLogic; import net.sourceforge.pinemup.ui.swing.menus.logic.GeneralMenuLogic.GeneralAction; import java.awt.Menu;
/* * pin 'em up * * Copyright (C) 2007-2013 by Mario Ködding * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package net.sourceforge.pinemup.ui.swing.tray; public class TrayMenu extends PopupMenu { private static final long serialVersionUID = 4859510599893727949L; private Menu categoriesMenu; private MenuItem manageCategoriesItem; private final TrayMenuLogic trayMenuLogic; public TrayMenu(TrayMenuLogic trayMenuLogic) { super("pin 'em up"); this.trayMenuLogic = trayMenuLogic; initWithNewLanguage(); } public final void initWithNewLanguage() { removeAll(); // add basic items for (MenuItem item : getBasicMenuItems()) { add(item); } addSeparator(); // categories menus categoriesMenu = new Menu(I18N.getInstance().getString("menu.categorymenu")); add(categoriesMenu); // category actions manageCategoriesItem = new MenuItem(I18N.getInstance().getString("menu.categorymenu.managecategoriesitem")); manageCategoriesItem.setActionCommand(TrayMenuLogic.ACTION_MANAGE_CATEGORIES); manageCategoriesItem.addActionListener(trayMenuLogic); createCategoriesMenu(); // im-/export menu addSeparator(); Menu imExMenu = new Menu(I18N.getInstance().getString("menu.notesimexport")); MenuItem serverUploadItem = new MenuItem(I18N.getInstance().getString("menu.notesimexport.serveruploaditem")); serverUploadItem.setActionCommand(TrayMenuLogic.ACTION_UPLOAD_TO_SERVER); serverUploadItem.addActionListener(trayMenuLogic); imExMenu.add(serverUploadItem); MenuItem serverDownloadItem = new MenuItem(I18N.getInstance().getString("menu.notesimexport.serverdownloaditem")); serverDownloadItem.setActionCommand(TrayMenuLogic.ACTION_DOWNLOAD_FROM_SERVER); serverDownloadItem.addActionListener(trayMenuLogic); imExMenu.add(serverDownloadItem); imExMenu.addSeparator(); MenuItem exportItem = new MenuItem(I18N.getInstance().getString("menu.notesimexport.textexportitem")); exportItem.setActionCommand(TrayMenuLogic.ACTION_EXPORT); exportItem.addActionListener(trayMenuLogic); imExMenu.add(exportItem); add(imExMenu); // other items addSeparator(); MenuItem showSettingsDialogItem = new MenuItem(I18N.getInstance().getString("menu.settingsitem")); showSettingsDialogItem.setActionCommand(TrayMenuLogic.ACTION_SHOW_SETTINGS_DIALOG); showSettingsDialogItem.addActionListener(trayMenuLogic); add(showSettingsDialogItem); // help menu Menu helpMenu = new Menu(I18N.getInstance().getString("menu.help")); MenuItem updateItem = new MenuItem(I18N.getInstance().getString("menu.help.updatecheckitem")); updateItem.setActionCommand(TrayMenuLogic.ACTION_CHECK_FOR_UPDATES); updateItem.addActionListener(trayMenuLogic); helpMenu.add(updateItem); helpMenu.addSeparator(); MenuItem aboutItem = new MenuItem(I18N.getInstance().getString("menu.help.aboutitem")); aboutItem.setActionCommand(TrayMenuLogic.ACTION_SHOW_ABOUT_DIALOG); aboutItem.addActionListener(trayMenuLogic); helpMenu.add(aboutItem); add(helpMenu); addSeparator(); // close item MenuItem closeItem = new MenuItem(I18N.getInstance().getString("menu.exititem")); closeItem.setActionCommand(TrayMenuLogic.ACTION_EXIT_APPLICATION); closeItem.addActionListener(trayMenuLogic); add(closeItem); } public void createCategoriesMenu() { categoriesMenu.removeAll(); for (Menu m : getCategoryMenus()) { categoriesMenu.add(m); } categoriesMenu.addSeparator(); categoriesMenu.add(manageCategoriesItem); } private List<Menu> getCategoryMenus() { List<Menu> categoryMenus = new ArrayList<>();
for (Category cat : CategoryManager.getInstance().getCategories()) {
2
synapticloop/routemaster
src/main/java/synapticloop/nanohttpd/servant/StaticFileServant.java
[ "public abstract class Handler {\n\t/**\n\t * Return whether this handler can serve the requested URI\n\t * \n\t * @param uri the URI to check\n\t * \n\t * @return whether this handler can serve the requested URI\n\t */\n\tpublic abstract boolean canServeUri(String uri);\n\t\n\t/**\n\t * If the handler can serve th...
import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.NanoHTTPD.IHTTPSession; import fi.iki.elonen.NanoHTTPD.Response; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import synapticloop.nanohttpd.handler.Handler; import synapticloop.nanohttpd.router.Routable; import synapticloop.nanohttpd.router.RouteMaster; import synapticloop.nanohttpd.utils.HttpUtils; import synapticloop.nanohttpd.utils.MimeTypeMapper;
package synapticloop.nanohttpd.servant; /* * Copyright (c) 2013-2020 synapticloop. * * All rights reserved. * * This source code and any derived binaries are covered by the terms and * conditions of the Licence agreement ("the Licence"). You may not use this * source code or any derived binaries except in compliance with the Licence. * A copy of the Licence is available in the file named LICENCE shipped with * this source code or binaries. * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * Licence for the specific language governing permissions and limitations * under the Licence. */ public class StaticFileServant extends Routable { private static final Logger LOGGER = Logger.getLogger(StaticFileServant.class.getSimpleName()); public StaticFileServant(String routeContext) { super(routeContext); } @Override
public Response serve(File rootDir, IHTTPSession httpSession) {
7
dima767/inspektr
inspektr-audit/src/main/java/com/github/inspektr/audit/AuditTrailManagementAspect.java
[ "public interface AuditActionResolver {\n\t\n\n /**\n * Resolve the action for the audit event.\n * \n * @param auditableTarget\n * @param retval\tThe returned value\n * @param audit the Audit annotation that may contain additional information.\n * @return\tThe resource String\n */\n ...
import com.github.inspektr.common.spi.PrincipalResolver; import com.github.inspektr.common.spi.ClientInfoResolver; import com.github.inspektr.common.spi.DefaultClientInfoResolver; import com.github.inspektr.common.web.ClientInfo; import java.util.Date; import java.util.List; import java.util.Map; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Aspect; import com.github.inspektr.audit.annotation.Audit; import com.github.inspektr.audit.annotation.Audits; import com.github.inspektr.audit.spi.AuditActionResolver; import com.github.inspektr.audit.spi.AuditResourceResolver;
/** * Licensed to Inspektr under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Inspektr licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.github.inspektr.audit; /** * A POJO style aspect modularizing management of an audit trail data concern. * * @author Dmitriy Kopylenko * @author Scott Battaglia * @version $Revision$ $Date$ * @since 1.0 */ @Aspect public final class AuditTrailManagementAspect { private final PrincipalResolver auditPrincipalResolver; private final Map<String, AuditActionResolver> auditActionResolvers; private final Map<String, AuditResourceResolver> auditResourceResolvers; private final List<AuditTrailManager> auditTrailManagers; private final String applicationCode;
private ClientInfoResolver clientInfoResolver = new DefaultClientInfoResolver();
3
bitcraze/crazyflie-android-client
src/se/bitcraze/crazyfliecontrol/bootloader/BootloaderActivity.java
[ "public class BootVersion {\n\n public final static int CF1_PROTO_VER_0 = 0x00;\n public final static int CF1_PROTO_VER_1 = 0x01;\n public final static int CF2_PROTO_VER = 0x10;\n\n public static String toVersionString(int ver) {\n if (ver == BootVersion.CF1_PROTO_VER_0 || ver == BootVersion.CF1_...
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import se.bitcraze.crazyflie.lib.bootloader.BootVersion; import se.bitcraze.crazyflie.lib.bootloader.Bootloader; import se.bitcraze.crazyflie.lib.bootloader.Bootloader.BootloaderListener; import se.bitcraze.crazyflie.lib.bootloader.FirmwareRelease; import se.bitcraze.crazyflie.lib.crazyradio.RadioDriver; import se.bitcraze.crazyfliecontrol2.MainActivity; import se.bitcraze.crazyfliecontrol2.R; import se.bitcraze.crazyfliecontrol2.UsbLinkAndroid; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.os.AsyncTask; import android.os.AsyncTask.Status; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.text.Spannable; import android.text.style.ForegroundColorSpan; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import javax.net.ssl.HttpsURLConnection;
int fileLength = connection.getContentLength(); // download the file File outputFile = new File(BootloaderActivity.this.getExternalFilesDir(null) + "/" + BootloaderActivity.BOOTLOADER_DIR + "/" + tagName + "/", fileName); outputFile.getParentFile().mkdirs(); input = connection.getInputStream(); output = new FileOutputStream(outputFile); byte data[] = new byte[4096]; long total = 0; int count; while ((count = input.read(data)) != -1) { // allow canceling if (isCancelled()) { input.close(); return null; } total += count; // publishing the progress.... if (fileLength > 0) { // only if total length is known publishProgress((int) (total * 100 / fileLength)); } output.write(data, 0, count); } } catch (Exception e) { return e.toString(); } finally { try { if (output != null) { output.close(); } if (input != null) { input.close(); } } catch (IOException ignored) { } if (connection != null) { connection.disconnect(); } } return null; } @Override protected String doInBackground(FirmwareRelease... sFirmwareRelease) { mSelectedFirmwareRelease = sFirmwareRelease[0]; if (mSelectedFirmwareRelease != null) { if (mFirmwareDownloader.isFileAlreadyDownloaded(mSelectedFirmwareRelease.getTagName() + "/" + mSelectedFirmwareRelease.getAssetName())) { mAlreadyDownloaded = true; return null; } String browserDownloadUrl = mSelectedFirmwareRelease.getBrowserDownloadUrl(); if (mFirmwareDownloader.isNetworkAvailable()) { return downloadFile(browserDownloadUrl, mSelectedFirmwareRelease.getAssetName(), mSelectedFirmwareRelease.getTagName()); } else { Log.d(LOG_TAG, "Network connection not available."); return "No network connection available.\nPlease check your connectivity."; } } else { return "Selected firmware does not have assets."; } } @Override protected void onPreExecute() { super.onPreExecute(); // take CPU lock to prevent CPU from going off if the user presses the power button during download PowerManager pm = (PowerManager) BootloaderActivity.this.getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName()); mWakeLock.acquire(); mProgressBar.setProgress(0); } @Override protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress); // if we get here, length is known, now set indeterminate to false mProgressBar.setIndeterminate(false); mProgressBar.setMax(100); mProgressBar.setProgress(progress[0]); } @Override protected void onPostExecute(String result) { mWakeLock.release(); if (result != null) { //flash firmware once firmware is downloaded appendConsole("Firmware download failed: " + result); stopFlashProcess(false); } else { //flash firmware once firmware is downloaded if (mAlreadyDownloaded) { appendConsole("Firmware file already downloaded."); } else { appendConsole("Firmware downloaded."); } startBootloader(); } } } private void startBootloader() { if (!mFirmwareDownloader.isFileAlreadyDownloaded(mSelectedFirmwareRelease.getTagName() + "/" + mSelectedFirmwareRelease.getAssetName())) { appendConsoleError("Firmware file can not be found."); stopFlashProcess(false); return; } try { //fail quickly, when Crazyradio is not connected //TODO: fix when BLE is used as well //TODO: extract this to RadioDriver class? if (!MainActivity.isCrazyradioAvailable(this)) { appendConsoleError("Please make sure that a Crazyradio (PA) is connected."); stopFlashProcess(false); return; }
mBootloader = new Bootloader(new RadioDriver(new UsbLinkAndroid(BootloaderActivity.this)));
6
icecondor/android
src/com/icecondor/nest/service/AlarmReceiver.java
[ "public class Condor extends Service {\n\n private Client api;\n private boolean clientAuthenticated;\n private String authApiCall;\n private Database db;\n private Prefs prefs;\n private PendingIntent wake_alarm_intent;\n private AlarmManager alarmManager;\n private BatteryReceiver batteryR...
import java.util.Date; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.util.Log; import com.icecondor.nest.Condor; import com.icecondor.nest.Constants; import com.icecondor.nest.Prefs; import com.icecondor.nest.db.activity.GpsLocation; import com.icecondor.nest.db.activity.HeartBeat;
package com.icecondor.nest.service; public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // can we always assume context is Condor? Condor condor = (Condor)context; String action = intent.getAction(); if (action.equals(Constants.ACTION_WAKE_ALARM)) { Log.i(Constants.APP_TAG, "AlarmReceiver onReceive "+ context.getClass().getSimpleName()+" now "+new Date()); HeartBeat heartBeat = new HeartBeat(""); heartBeat.setCellData(condor.isDataActive(ConnectivityManager.TYPE_MOBILE)); heartBeat.setWifiData(condor.isDataActive(ConnectivityManager.TYPE_WIFI)); if(condor.isBatteryValid()){ heartBeat.setBatteryPercentage(condor.getBattPercent()); heartBeat.setPower(condor.getBattAc()); } else { Log.i(Constants.APP_TAG, "AlarmReceiver onReceive Warning Batt not valid"); } condor.getDb().append(heartBeat); condor.binder.onNewActivity();
GpsLocation lastLocation = condor.getLastLocation();
3
SEMERU-WM/ChangeScribe
CommitSummarizer/CommitSummarizer.core/src/main/java/co/edu/unal/colswe/changescribe/core/textgenerator/phrase/NounPhrase.java
[ "public class Constants {\n\n\tpublic static final String RENAME = \"RENAME\";\n\tpublic static final String TREE = \"^{tree}\";\n\tpublic static final String DELETE = \"DELETE\";\n\tpublic static final String REMOVE = \"REMOVE\";\n\tpublic static final String ADD = \"ADD\";\n\tpublic static final String MODIFY = \...
import java.util.LinkedList; import java.util.List; import co.edu.unal.colswe.changescribe.core.Constants; import co.edu.unal.colswe.changescribe.core.textgenerator.phrase.util.StringUtils; import co.edu.unal.colswe.changescribe.core.textgenerator.pos.POSTagger; import co.edu.unal.colswe.changescribe.core.textgenerator.pos.TaggedTerm; import co.edu.unal.colswe.changescribe.core.textgenerator.tokenizer.Tokenizer;
package co.edu.unal.colswe.changescribe.core.textgenerator.phrase; public class NounPhrase extends Phrase { private StringBuilder phrase; private List<Parameter> parameters; private String connector; private StringBuilder complementPhrase; public NounPhrase(String name) {
super(POSTagger.tag(Tokenizer.split(name)));
4
ashqal/NightOwl
app/src/main/java/com/asha/nightowl/MainApplication.java
[ "@OwlHandle(CardView.class)\npublic class CardViewHandler extends AbsSkinHandler implements OwlCustomTable.OwlCardView {\n\n @Override\n protected void onAfterCollect(View view, Context context, AttributeSet attrs, ColorBox box) {\n Object[] objects = box.get(R.styleable.NightOwl_CardView_night_cardBac...
import android.app.Activity; import android.app.Application; import android.content.SharedPreferences; import android.support.v4.content.SharedPreferencesCompat; import com.asha.nightowl.custom.CardViewHandler; import com.asha.nightowl.custom.CollapsingToolbarLayoutHandler; import com.asha.nightowl.custom.OwlCustomTable; import com.asha.nightowl.custom.TabLayoutHandler; import com.asha.nightowl.custom.ToolbarHandler; import com.asha.nightowllib.NightOwl; import com.asha.nightowllib.observer.IOwlObserver;
package com.asha.nightowl; /** * Created by hzqiujiadi on 15/11/6. * hzqiujiadi ashqalcn@gmail.com */ public class MainApplication extends Application { @Override public void onCreate() { super.onCreate(); SharedPreferences preferences = getSharedPreferences("NightOwlDemo",Activity.MODE_PRIVATE); int mode = preferences.getInt("mode",0); NightOwl.builder().subscribedBy(new SkinObserver()).defaultMode(mode).create(); NightOwl.owlRegisterHandler(TabLayoutHandler.class, OwlCustomTable.OwlTabLayout.class);
NightOwl.owlRegisterHandler(ToolbarHandler.class, OwlCustomTable.OwlToolbar.class);
4
TeamCohen/SEAL
src/com/rcwang/seal/expand/IterativeSeal.java
[ "public class EvalResult {\r\n public int trialID = 0;\r\n public int numGoldEntity = 0;\r\n public int numGoldSynonym = 0;\r\n public double numCorrectSynonym = 0;\r\n public double numCorrectEntity = 0;\r\n public double numResultsAboveThreshold = 0;\r\n public double maxF1Precision = 0;\r\n public double...
import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import com.rcwang.seal.eval.EvalResult; import com.rcwang.seal.eval.Evaluator; import com.rcwang.seal.fetch.DocumentSet; import com.rcwang.seal.rank.Ranker.Feature; import com.rcwang.seal.util.GlobalVar; import com.rcwang.seal.util.Helper;
/************************************************************************** * Developed by Language Technologies Institute, Carnegie Mellon University * Written by Richard Wang (rcwang#cs,cmu,edu) **************************************************************************/ package com.rcwang.seal.expand; public class IterativeSeal { public static Logger log = Logger.getLogger(IterativeSeal.class);
public static GlobalVar gv = GlobalVar.getGlobalVar();
4
nimble-platform/identity-service
identity-service/src/test/java/eu/nimble/core/infrastructure/identity/config/DefaultTestConfiguration.java
[ "@Service\r\n@SuppressWarnings(\"Duplicates\")\r\npublic class EmailService {\r\n\r\n private static final Logger logger = LoggerFactory.getLogger(EmailService.class);\r\n\r\n @Autowired\r\n private JavaMailSender emailSender;\r\n\r\n @Autowired\r\n private UblUtils ublUtils;\r\n\r\n @Autowired\r\...
import eu.nimble.core.infrastructure.identity.mail.EmailService; import eu.nimble.core.infrastructure.identity.service.IdentityService; import eu.nimble.core.infrastructure.identity.entity.UaaUser; import eu.nimble.core.infrastructure.identity.uaa.KeycloakAdmin; import eu.nimble.core.infrastructure.identity.uaa.OAuthClient; import eu.nimble.service.model.ubl.commonaggregatecomponents.PartyType; import eu.nimble.utility.persistence.initalizer.CustomDbInitializer; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Optional; import java.util.Random; import static eu.nimble.core.infrastructure.identity.system.IdentityController.REFRESH_TOKEN_SESSION_KEY; import static org.mockito.Matchers.*; import static org.mockito.Mockito.when;
package eu.nimble.core.infrastructure.identity.config; /** * Created by Johannes Innerbichler on 09.08.18. */ @Profile("test") @TestConfiguration public class DefaultTestConfiguration { @Bean @Primary public IdentityService identityResolver() throws IOException { IdentityService identityServiceMock = Mockito.mock(IdentityService.class); // mock user query when(identityServiceMock.getUserfromBearer(anyString())).thenReturn(new UaaUser()); // mock company query when(identityServiceMock.getCompanyOfUser(anyObject())).then((Answer<Optional<PartyType>>) invocationOnMock -> { PartyType mockParty = new PartyType(); return Optional.of(mockParty); }); // mock verification of roles when(identityServiceMock.hasAnyRole(any(), anyVararg())).thenReturn(true); return identityServiceMock; } @Bean @Primary public KeycloakAdmin keycloakAdmin() { return Mockito.mock(KeycloakAdmin.class); } @Bean @Primary public EmailService emailService() { return Mockito.mock(EmailService.class); } @Bean @Primary
public OAuthClient oAuthClient() {
4
noctarius/castmapr
src/main/java/com/noctarius/castmapr/core/operation/IListMapReduceOperation.java
[ "public class CollectorImpl<Key, Value>\n implements Collector<Key, Value>\n{\n\n public final Map<Key, List<Value>> emitted = new HashMap<Key, List<Value>>();\n\n @Override\n public void emit( Key key, Value value )\n {\n List<Value> values = emitted.get( key );\n if ( values == null )...
import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.hazelcast.collection.CollectionContainer; import com.hazelcast.collection.CollectionProxyId; import com.hazelcast.collection.CollectionProxyType; import com.hazelcast.collection.CollectionRecord; import com.hazelcast.collection.CollectionService; import com.hazelcast.collection.CollectionWrapper; import com.hazelcast.collection.list.ObjectListProxy; import com.hazelcast.core.IList; import com.hazelcast.nio.serialization.Data; import com.hazelcast.spi.ProxyService; import com.hazelcast.spi.impl.NodeEngineImpl; import com.noctarius.castmapr.core.CollectorImpl; import com.noctarius.castmapr.spi.IListAware; import com.noctarius.castmapr.spi.Mapper; import com.noctarius.castmapr.spi.PartitionIdAware; import com.noctarius.castmapr.spi.Reducer;
/* * 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.noctarius.castmapr.core.operation; public class IListMapReduceOperation<KeyIn, ValueIn, KeyOut, ValueOut> extends AbstractMapReduceOperation<KeyIn, ValueIn, KeyOut, ValueOut> { public IListMapReduceOperation() { } public IListMapReduceOperation( String name, Mapper<KeyIn, ValueIn, KeyOut, ValueOut> mapper,
Reducer<KeyOut, ValueOut> reducer )
4
christ66/cobertura
cobertura/src/main/java/net/sourceforge/cobertura/instrument/CoberturaInstrumenter.java
[ "@CoverageIgnore\npublic class ProjectData extends CoverageDataContainer {\n\tprivate static final Logger logger = Logger.getLogger(ProjectData.class\n\t\t\t.getCanonicalName());\n\tprivate static final long serialVersionUID = 6;\n\n\tprivate static ProjectData globalProjectData = null;\n\n\tprivate static Thread s...
import net.sourceforge.cobertura.util.IOUtil; import org.apache.log4j.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.util.CheckClassAdapter; import java.io.*; import java.util.*; import java.util.regex.Pattern; import net.sourceforge.cobertura.coveragedata.ProjectData; import net.sourceforge.cobertura.instrument.pass1.DetectDuplicatedCodeClassVisitor; import net.sourceforge.cobertura.instrument.pass1.DetectIgnoredCodeClassVisitor; import net.sourceforge.cobertura.instrument.pass2.BuildClassMapClassVisitor; import net.sourceforge.cobertura.instrument.pass3.InjectCodeClassInstrumenter;
/* * Cobertura - http://cobertura.sourceforge.net/ * * Copyright (C) 2011 Piotr Tabor * * Note: This file is dual licensed under the GPL and the Apache * Source License (so that it can be used from both the main * Cobertura classes and the ant tasks). * * Cobertura is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * Cobertura is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.instrument; /** * Class that is responsible for the whole process of instrumentation of a single class. * <p/> * The class is instrumented in tree passes: * <ol> * <li>Read only: {@link DetectDuplicatedCodeClassVisitor} - we look for the same ASM code snippets * rendered in different places of destination code</li> * <li>Read only: {@link BuildClassMapClassVisitor} - finds all touch-points and other interesting * information that are in the class and store it in {@link ClassMap}. * <li>Real instrumentation: {@link InjectCodeClassInstrumenter}. Uses {#link ClassMap} to inject * code into the class</li> * </ol> * * @author piotr.tabor@gmail.com */ public class CoberturaInstrumenter { private static final Logger logger = Logger .getLogger(CoberturaInstrumenter.class); /** * During the instrumentation process we are feeling {@link ProjectData}, to generate from * it the *.ser file. * <p/> * We now (1.10+) don't need to generate the file (it is not necessery for reporting), but we still * do it for backward compatibility (for example maven-cobertura-plugin expects it). We should avoid * this some day. */ private ProjectData projectData; /** * The root directory for instrumented classes. If it is null, the instrumented classes are overwritten. */ private File destinationDirectory; /** * List of patterns to know that we don't want trace lines that are calls to some methods */ private Collection<Pattern> ignoreRegexes = new Vector<Pattern>(); /** * Methods annotated by this annotations will be ignored during coverage measurement */ private Set<String> ignoreMethodAnnotations = new HashSet<String>(); /** * If true: Getters, Setters and simple initialization will be ignored by coverage measurement */ private boolean ignoreTrivial; /** * If true: The process is interrupted when first error occurred. */ private boolean failOnError; /** * If true: We make sure to keep track of test unit that execute which individual line. */ private boolean individualTest; /** * Setting to true causes cobertura to use more strict threadsafe model that is significantly * slower, but guarantees that number of hits counted for each line will be precise in multithread-environment. * <p/> * The option does not change measured coverage. * <p/> * In implementation it means that AtomicIntegerArray will be used instead of int[]. */ private boolean threadsafeRigorous; /** * Used for storing all the test unit locations. */ private List<File> testUnitFilePath; /** * Analyzes and instruments class given by path. * <p/> * <p>Also the {@link #projectData} structure is filled with information about the found touch-points</p> * * @param file - path to class that should be instrumented * * @return instrumentation result structure or null in case of problems */ public InstrumentationResult instrumentClass(File file) { InputStream inputStream = null; try { logger.debug("Working on file:" + file.getAbsolutePath()); inputStream = new FileInputStream(file); return instrumentClass(inputStream); } catch (Throwable t) { logger.warn("Unable to instrument file " + file.getAbsolutePath(), t); if (failOnError) { throw new RuntimeException( "Warning detected and failOnError is true", t); } else { return null; } } finally { IOUtil.closeInputStream(inputStream); } } /** * Analyzes and instruments class given by inputStream * <p/> * <p>Also the {@link #projectData} structure is filled with information about the found touch-points</p> * * @param inputStream - source of class to instrument * * * @return instrumentation result structure or null in case of problems */ public InstrumentationResult instrumentClass(InputStream inputStream) throws IOException { if (testUnitFilePath != null && testUnitFilePath.size() > 0 && individualTest) { new TestUnitInstrumenter(testUnitFilePath); } ClassReader cr0 = new ClassReader(inputStream); ClassWriter cw0 = new ClassWriter(0); DetectIgnoredCodeClassVisitor detectIgnoredCv = new DetectIgnoredCodeClassVisitor( cw0, ignoreTrivial, ignoreMethodAnnotations); DetectDuplicatedCodeClassVisitor cv0 = new DetectDuplicatedCodeClassVisitor( detectIgnoredCv); cr0.accept(cv0, 0); ClassReader cr = new ClassReader(cw0.toByteArray()); ClassWriter cw = new ClassWriter(0); BuildClassMapClassVisitor cv = new BuildClassMapClassVisitor(cw, ignoreRegexes, cv0.getDuplicatesLinesCollector(), detectIgnoredCv.getIgnoredMethodNamesAndSignatures()); cr.accept(cv, ClassReader.EXPAND_FRAMES); if (logger.isDebugEnabled()) { logger .debug("=============== Detected duplicated code ============="); Map<Integer, Map<Integer, Integer>> l = cv0 .getDuplicatesLinesCollector(); for (Map.Entry<Integer, Map<Integer, Integer>> m : l.entrySet()) { if (m.getValue() != null) { for (Map.Entry<Integer, Integer> pair : m.getValue() .entrySet()) { logger.debug(cv.getClassMap().getClassName() + ":" + m.getKey() + " " + pair.getKey() + "->" + pair.getValue()); } } } logger .debug("=============== End of detected duplicated code ======"); } //TODO(ptab): Don't like the idea, but we have to be compatible (hope to remove the line in future release) logger .debug("Migrating classmap in projectData to store in *.ser file: " + cv.getClassMap().getClassName()); cv.getClassMap().applyOnProjectData(projectData, cv.shouldBeInstrumented()); if (cv.shouldBeInstrumented()) { /* * BuildClassMapClassInstrumenter and DetectDuplicatedCodeClassVisitor has not modificated bytecode, * so we can use any bytecode representation of that class. */ ClassReader cr2 = new ClassReader(cw0.toByteArray()); ClassWriter cw2 = new CoberturaClassWriter( ClassWriter.COMPUTE_FRAMES); cv.getClassMap().assignCounterIds(); logger.debug("Assigned " + cv.getClassMap().getMaxCounterId() + " counters for class:" + cv.getClassMap().getClassName());
InjectCodeClassInstrumenter cv2 = new InjectCodeClassInstrumenter(
3
Atmosphere/wasync
wasync/src/main/java/org/atmosphere/wasync/serial/SerialSocketRuntime.java
[ "public class FunctionWrapper {\n\n private final String functionName;\n private final Function<?> function;\n\n public FunctionWrapper(String functionName, Function<?> function) {\n this.functionName = functionName;\n this.function = function;\n }\n\n public Function<?> function(){\n ...
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.SettableFuture; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.List; import org.asynchttpclient.Response; import org.atmosphere.wasync.FunctionWrapper; import org.atmosphere.wasync.Future; import org.atmosphere.wasync.Options; import org.atmosphere.wasync.Request; import org.atmosphere.wasync.Transport; import org.atmosphere.wasync.impl.DefaultFuture; import org.atmosphere.wasync.impl.SocketRuntime; import org.atmosphere.wasync.transport.WebSocketTransport; import org.atmosphere.wasync.util.FutureProxy;
/* * Copyright 2008-2022 Async-IO.org * * 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.atmosphere.wasync.serial; /** * Serial extension for the {@link SocketRuntime} * * @author Jeanfrancois Arcand */ public class SerialSocketRuntime extends SocketRuntime { private final static Logger logger = LoggerFactory.getLogger(SerialSocketRuntime.class); private final SerializedSocket serializedSocket;
public SerialSocketRuntime(Transport transport, Options options, DefaultFuture rootFuture, SerializedSocket serializedSocket, List<FunctionWrapper> functions) {
0
tteguayco/JITRAX
src/es/ull/etsii/jitrax/database/DatabaseComparator.java
[ "public class Attribute {\n\n\tprivate String name;\n\tprivate DataType dataType;\n\t\n\tpublic Attribute(String aName, DataType aDataType) {\n\t\tname = aName;\n\t\tdataType = aDataType;\n\t}\n\t\n\tpublic boolean equals(Object object) {\n\t\tif (object != null && object instanceof Attribute) {\n\t\t\tAttribute an...
import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import es.ull.etsii.jitrax.adt.Attribute; import es.ull.etsii.jitrax.adt.DataType; import es.ull.etsii.jitrax.adt.Database; import es.ull.etsii.jitrax.adt.Datum; import es.ull.etsii.jitrax.adt.Row; import es.ull.etsii.jitrax.adt.Table;
// Getting the number of rows returned (number of attributes in the current table) // and storing it in the 'numberOfAttributesForRemote' if (attrResultSet != null) { attrResultSet.beforeFirst(); attrResultSet.last(); numberOfAttributesForRemote = attrResultSet.getRow(); attrResultSet.beforeFirst(); } // If the number of attributes differs, databases are not compatibles if (currentLocalTable.getNumOfColumns() != numberOfAttributesForRemote) { return false; } // COMPARING ATTRIBUTES while (attrResultSet.next()) { String attrName = attrResultSet.getString("COLUMN_NAME"); String attrType = attrResultSet.getString("TYPE_NAME"); DataType attrDataType; // Comparing data types if (attrType.contains("varchar")) { attrDataType = DataType.STRING; } else if (attrType.contains("char")) { attrDataType = DataType.CHAR; } else if (attrType.contains("int")) { attrDataType = DataType.INT; } else if (attrType.contains("float")) { attrDataType = DataType.FLOAT; } else if (attrType.contains("date")) { attrDataType = DataType.DATE; } else { attrDataType = null; } // Check if the attribute exists on the current table if (!currentLocalTable.attributeExists(attrName, attrDataType)) { return false; } } } } tablesResultSet.isBeforeFirst(); } catch (SQLException e) { e.printStackTrace(); } return true; } private boolean tablesContentsCoincide() { Table currentLocalTable; // COMPARING ROWS for (int tableIndex = 0; tableIndex < localTablesOnDbms.size(); tableIndex++) { currentLocalTable = localTablesOnDbms.get(tableIndex); try { for (int i = 0; i < getDatabase().getNumOfTables(); i++) { int numOfRows = 0; Statement st = getDbmsConnection().createStatement(); ResultSet countRS = st.executeQuery("SELECT COUNT(*) FROM " + currentLocalTable.getName()); countRS.next(); numOfRows = countRS.getInt(1); // Check matching between number of rows (on DBMS and locally) if (currentLocalTable.getNumOfRows() != numOfRows) { return false; } // Compare contents String[][] rowsData = currentLocalTable.getRowsData(); for (int j = 0; j < rowsData.length; j++) { String query = "SELECT * FROM " + currentLocalTable.getName() + " WHERE "; for (int k = 0; k < rowsData[j].length; k++) { query += currentLocalTable.getAttributes().get(k).getName() + "="; query += rowsData[j][k]; if (k < rowsData[j].length - 1) { query += " AND "; } } ResultSet rs = st.executeQuery(query); //System.out.println(query); if (!rs.next()) { return false; } } } } catch (SQLException e) { e.printStackTrace(); } } return true; } private void insertDbmsRowsToLocalTable() throws SQLException { tablesResultSet.beforeFirst(); // For each table on the DBMS while (tablesResultSet.next()) { String remoteTableName = tablesResultSet.getString("TABLE_NAME"); Table localTable = database.getTableByName(remoteTableName); if (localTable != null) { // Getting all the rows Statement st = getDbmsConnection().createStatement(); ResultSet rowsRS = st.executeQuery("SELECT * FROM " + remoteTableName); // Insert them locally if they not exist ArrayList<Attribute> attrs = localTable.getAttributes(); ArrayList<Datum> data;
Row newRow = null;
4
xpush/lib-xpush-android
sample/src/main/java/io/xpush/sampleChat/fragments/ChatFragment.java
[ "public class Constants {\n public static final int REQUEST_SIGNUP = 100;\n\n public static final int REQUEST_EDIT_IMAGE = 111;\n public static final int REQUEST_EDIT_NICKNAME = 112;\n public static final int REQUEST_EDIT_STATUS_MESSAGE = 113;\n\n public static final int REQUEST_INVITE_USER = 201;\n\...
import android.app.Activity; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import butterknife.Bind; import butterknife.ButterKnife; import io.xpush.chat.common.Constants; import io.xpush.chat.core.CallbackEvent; import io.xpush.chat.core.XPushCore; import io.xpush.chat.fragments.XPushChatFragment; import io.xpush.chat.models.XPushMessage; import io.xpush.chat.util.ContentUtils; import io.xpush.chat.view.adapters.MessageListAdapter; import io.xpush.sampleChat.R; import io.xpush.sampleChat.activities.ImageViewerActivity; import io.xpush.sampleChat.activities.SelectFriendActivity;
package io.xpush.sampleChat.fragments; public class ChatFragment extends XPushChatFragment { public static final String TAG = ChatFragment.class.getSimpleName(); @Bind(R.id.action_chat_plus) ImageView mChatPlus; @Bind(R.id.hidden_panel) RelativeLayout mHiddenPannel; @Bind(R.id.grid_chat_plus) GridView mGridView; private Integer[] mThumbIds = { R.drawable.ic_photo_black, R.drawable.ic_camera_black }; private Integer[] mTitles = { R.string.action_select_photo, R.string.action_take_photo }; private String mCurrentPhotoPath; @Override public void onAttach(Activity activity) { super.onAttach(activity); super.mAdapter.setOnItemClickListener(new MessageListAdapter.MessageClickListener() { @Override public void onMessageClick(String message, int type) { if( type == XPushMessage.TYPE_RECEIVE_IMAGE || type == XPushMessage.TYPE_SEND_IMAGE ){ Intent intent = new Intent(mActivity, ImageViewerActivity.class); intent.putExtra("selectedImage", message); intent.putStringArrayListExtra("imageList", getImageList() ); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); mActivity.startActivity(intent); } } @Override public void onMessageLongClick(String message, int type) { Log.d(TAG, "long clicked : " + message ); if( type == XPushMessage.TYPE_RECEIVE_MESSAGE || type == XPushMessage.TYPE_SEND_MESSAGE ){ ClipboardManager cm = (ClipboardManager)mActivity.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText( " Chat Message : ", message ); cm.setPrimaryClip(clip); Toast.makeText(mActivity, "Copied to clipboard", Toast.LENGTH_SHORT).show(); } } }); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_chat_new, menu); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); mGridView.setAdapter(new ChatMenuAdapter()); mChatPlus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mHiddenPannel.getVisibility() == View.GONE) { mHiddenPannel.setVisibility(View.VISIBLE); mChatPlus.setImageResource(R.drawable.ic_close_black); } else { mHiddenPannel.setVisibility(View.GONE); mChatPlus.setImageResource(R.drawable.ic_add_black); } } }); mGridView.setNumColumns(mTitles.length); mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> listView, View view, int position, long id) { if (position == 0) { openGallery(); } else if (position == 1) { takePicture(); } } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_leave) { AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); builder.setTitle(mActivity.getString(R.string.action_leave_dialog_title)) .setMessage(mActivity.getString(R.string.action_leave_dialog_description)) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { channelLeave(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); AlertDialog dialog = builder.create(); // 알림창 객체 생성 dialog.show(); // 알림창 띄우기 return true; } else if (id == R.id.action_invite) {
Intent intent = new Intent(mActivity, SelectFriendActivity.class);
8
christophersmith/summer-mqtt
summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/AutomaticReconnectTest.java
[ "public enum MqttClientConnectionType\n{\n /**\n * Represents a connection type that can only publish messages.\n */\n PUBLISHER,\n /**\n * Represents a connection type that can both publish and receive messages.\n */\n PUBSUB,\n /**\n * Rep...
import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.paho.client.mqttv3.MqttException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.netcrusher.core.reactor.NioReactor; import org.netcrusher.tcp.TcpCrusher; import org.netcrusher.tcp.TcpCrusherBuilder; import org.springframework.context.ApplicationListener; import org.springframework.context.support.StaticApplicationContext; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.ExecutorSubscribableChannel; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler; import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType; import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService; import com.github.christophersmith.summer.mqtt.core.event.MqttClientConnectedEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttClientConnectionFailureEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttClientConnectionLostEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttClientDisconnectedEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttConnectionStatusEvent; import com.github.christophersmith.summer.mqtt.paho.service.util.BrokerHelper; import com.github.christophersmith.summer.mqtt.paho.service.util.DefaultReconnectService;
/******************************************************************************* * Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith * * 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.github.christophersmith.summer.mqtt.paho.service; public class AutomaticReconnectTest implements ApplicationListener<MqttConnectionStatusEvent> { private static NioReactor REACTOR; private static TcpCrusher CRUSHER_PROXY; private AtomicInteger clientConnectedCount = new AtomicInteger(0); private AtomicInteger clientDisconnectedCount = new AtomicInteger(0); private AtomicInteger clientLostConnectionCount = new AtomicInteger(0); private AtomicInteger clientFailedConnectionCount = new AtomicInteger(0); @BeforeClass public static void initialize() throws IOException { REACTOR = new NioReactor(); CRUSHER_PROXY = TcpCrusherBuilder.builder().withReactor(REACTOR) .withBindAddress(BrokerHelper.getProxyHostName(), BrokerHelper.getProxyPort()) .withConnectAddress(BrokerHelper.getBrokerHostName(), BrokerHelper.getBrokerPort()) .buildAndOpen(); } @AfterClass public static void shutdown() { CRUSHER_PROXY.close(); REACTOR.close(); } private StaticApplicationContext getStaticApplicationContext() { clientConnectedCount.set(0); clientDisconnectedCount.set(0); clientLostConnectionCount.set(0); clientFailedConnectionCount.set(0); StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.addApplicationListener(this); applicationContext.refresh(); applicationContext.start(); return applicationContext; } @Test public void testGoodConnection() throws MqttException { StaticApplicationContext applicationContext = getStaticApplicationContext(); MessageChannel inboundMessageChannel = new ExecutorSubscribableChannel(); PahoAsyncMqttClientService service = new PahoAsyncMqttClientService( BrokerHelper.getProxyUri(), BrokerHelper.getClientId(), MqttClientConnectionType.PUBSUB, null); service.setApplicationEventPublisher(applicationContext); service.setInboundMessageChannel(inboundMessageChannel); service.subscribe(String.format("client/%s", BrokerHelper.getClientId()),
MqttQualityOfService.QOS_0);
1
gejiaheng/Protein
app/src/main/java/com/ge/protein/comment/CommentListRepository.java
[ "public final class ApiConstants {\n\n private ApiConstants() {\n throw new AssertionError(\"No construction for constant class\");\n }\n\n // general constants of Dribbble API\n public static final String DRIBBBLE_V1_BASE_URL = \"https://api.dribbble.com\";\n public static final String DRIBBB...
import com.ge.protein.data.api.ApiConstants; import com.ge.protein.data.api.ServiceGenerator; import com.ge.protein.data.api.service.ShotsService; import com.ge.protein.data.model.Comment; import com.ge.protein.util.AccountManager; import java.util.List; import io.reactivex.Observable; import retrofit2.Response;
/* * Copyright 2017 Jiaheng Ge * * 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.ge.protein.comment; class CommentListRepository { private ShotsService shotsService; CommentListRepository() { shotsService = ServiceGenerator.createService(ShotsService.class, AccountManager.getInstance().getAccessToken()); }
Observable<Response<List<Comment>>> getCommentsForShot(long shotId) {
3
Sefford/material-in-30-minutes
app/src/main/java/com/sefford/material/sample/contacts/details/ui/presenters/ContactDetailPresenter.java
[ "@Module(injects = {ContactListActivity.class,\n ContactDetailsActivity.class},\n library = true,\n complete = false)\npublic class LocalBusModule {\n\n public static final String LOCAL_BUS = \"Local\";\n\n @Singleton\n @Provides\n @Named(LOCAL_BUS)\n public Bus provideLocalBus(B...
import com.sefford.material.sample.common.injection.modules.LocalBusModule; import com.sefford.material.sample.common.internal.Bus; import com.sefford.material.sample.contacts.details.interactors.GetContact; import com.sefford.material.sample.contacts.details.responses.GetContactResponse; import com.sefford.material.sample.contacts.details.ui.views.ContactDetailView; import javax.inject.Inject; import javax.inject.Named;
/* * Copyright (C) 2015 Saúl Díaz * * 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.sefford.material.sample.contacts.details.ui.presenters; /** * Presenter that absorbs all the UI-related lifecycle for {@link com.sefford.material.sample.contacts.details.ui.activities.ContactDetailsActivity ContactDetailActivity} */ public class ContactDetailPresenter { final Bus bus;
final GetContact getContact;
2
kwon37xi/hibernate4-memcached
hibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/regions/EntityMemcachedRegion.java
[ "public class CacheNamespace implements Serializable {\n /**\n * name of region\n */\n private String name;\n\n /**\n * if this value is true, the memcached adapter should implement namespace pattern\n * or ignore namespace pattern.\n * <p/>\n * see <a href=\"https://code.google.com...
import kr.pe.kwonnam.hibernate4memcached.memcached.CacheNamespace; import kr.pe.kwonnam.hibernate4memcached.memcached.MemcachedAdapter; import kr.pe.kwonnam.hibernate4memcached.strategies.NonstrictReadWriteEntityRegionAccessStrategy; import kr.pe.kwonnam.hibernate4memcached.strategies.ReadOnlyEntityRegionAccessStrategy; import kr.pe.kwonnam.hibernate4memcached.timestamper.HibernateCacheTimestamper; import kr.pe.kwonnam.hibernate4memcached.util.OverridableReadOnlyProperties; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.CacheDataDescription; import org.hibernate.cache.spi.EntityRegion; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.EntityRegionAccessStrategy; import org.hibernate.cfg.Settings;
package kr.pe.kwonnam.hibernate4memcached.regions; /** * @author KwonNam Son (kwon37xi@gmail.com) */ public class EntityMemcachedRegion extends TransactionalDataMemcachedRegion implements EntityRegion { public EntityMemcachedRegion(String regionName, OverridableReadOnlyProperties properties, CacheDataDescription metadata, Settings settings, MemcachedAdapter memcachedAdapter, HibernateCacheTimestamper hibernateCacheTimestamper) {
super(new CacheNamespace(regionName, true), properties, metadata, settings, memcachedAdapter, hibernateCacheTimestamper);
0
gyf-dev/ImmersionBar
immersionbar-sample/src/main/java/com/gyf/immersionbar/sample/activity/DialogActivity.java
[ "@TargetApi(Build.VERSION_CODES.KITKAT)\npublic final class ImmersionBar implements ImmersionCallback {\n\n private final Activity mActivity;\n private Fragment mSupportFragment;\n private android.app.Fragment mFragment;\n private Dialog mDialog;\n private Window mWindow;\n private ViewGroup mDeco...
import android.content.DialogInterface; import android.content.res.Configuration; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.Toolbar; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.gyf.immersionbar.ImmersionBar; import com.gyf.immersionbar.sample.AppManager; import com.gyf.immersionbar.sample.R; import com.gyf.immersionbar.sample.fragment.dialog.BottomDialogFragment; import com.gyf.immersionbar.sample.fragment.dialog.FullDialogFragment; import com.gyf.immersionbar.sample.fragment.dialog.LeftDialogFragment; import com.gyf.immersionbar.sample.fragment.dialog.RightDialogFragment; import com.gyf.immersionbar.sample.fragment.dialog.TopDialogFragment; import com.gyf.immersionbar.sample.utils.Utils; import butterknife.BindView; import butterknife.OnClick;
package com.gyf.immersionbar.sample.activity; /** * @author geyifeng * @date 2017/7/31 */ public class DialogActivity extends BaseActivity implements DialogInterface.OnDismissListener { @BindView(R.id.btn_full_fragment) Button btnFullFragment; @BindView(R.id.btn_top_fragment) Button btnTopFragment; @BindView(R.id.btn_bottom_fragment) Button btnBottomFragment; @BindView(R.id.btn_left_fragment) Button btnLeftFragment; @BindView(R.id.btn_right_fragment) Button btnRightFragment; private AlertDialog mAlertDialog; private Window mDialogWindow; private int mId = 0; @Override protected int getLayoutId() { return R.layout.activity_dialog; } @Override protected void initImmersionBar() { super.initImmersionBar(); ImmersionBar.with(this).titleBar(R.id.toolbar).keyboardEnable(true).init(); } @Override protected void setListener() { btnFullFragment.setOnClickListener(v -> { FullDialogFragment fullDialogFragment = new FullDialogFragment(); fullDialogFragment.show(getSupportFragmentManager(), FullDialogFragment.class.getSimpleName()); }); btnTopFragment.setOnClickListener(v -> {
TopDialogFragment fullDialogFragment = new TopDialogFragment();
6
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/application/ReelyAwareApplicationCallback.java
[ "public class BleService extends Service {\n public static final String KEY_FILTER = \"filter\";\n public static final String KEY_EVENT_DATA = \"event_data\";\n final ScanCallback callback = new ScanCallback();\n final ScanSettings lowPowerScan = new ScanSettings.Builder() //\n .setCallbackTy...
import android.Manifest; import android.app.Activity; import android.app.Application; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.os.Build; import android.os.IBinder; import android.os.ParcelUuid; import android.support.v4.content.ContextCompat; import com.reelyactive.blesdk.service.BleService; import com.reelyactive.blesdk.service.BleServiceCallback; import com.reelyactive.blesdk.support.ble.ScanFilter; import com.reelyactive.blesdk.support.ble.ScanResult; import com.reelyactive.blesdk.support.ble.util.Logger; import java.util.concurrent.atomic.AtomicInteger;
package com.reelyactive.blesdk.application; /** * This class provides a convenient way to make your application aware of any Reelceivers. * <p> * Register it using {@link android.app.Application#registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks)}<br/> * <p> * Extend it to customize the behaviour of your application. * <p> * The default behaviour is to bind to the {@link BleService} as soon as the app is created. * * @see android.app.Application.ActivityLifecycleCallbacks */ @SuppressWarnings("unused") public abstract class ReelyAwareApplicationCallback implements Application.ActivityLifecycleCallbacks, BleServiceCallback { private static final String TAG = ReelyAwareApplicationCallback.class.getSimpleName(); private final Context context; private final ServiceConnection serviceConnection; private final AtomicInteger activityCount = new AtomicInteger(); private boolean bound = false; private Activity current; private BleService service; /** * As soon as the component is created, we bindBleService to the {@link BleService} * * @param context The application's {@link Context} */ public ReelyAwareApplicationCallback(Context context) { this.context = context; this.serviceConnection = new BleServiceConnection(); bindBleService(); } /** * Find out if an {@link Activity} implements {@link ReelyAwareActivity} * * @param activity The {@link Activity} * @return true if the {@link Activity} implements {@link ReelyAwareActivity}, false if not. */ protected static boolean isReelyAware(Activity activity) { return activity != null && ReelyAwareActivity.class.isInstance(activity); } /** * The default behaviour is to check if a {@link ReelyAwareActivity} is running, and call a scan if so.<br/> * See {@link #startScan()} and {@link #getScanType()} * * @param activity The resumed {@link Activity} */ @Override public void onActivityResumed(Activity activity) { current = activity; activityCount.incrementAndGet(); if (!startScan()) { stopScan(); } } /** * The default behaviour is to check if any {@link ReelyAwareActivity} is still running, and call a scan if so.<br/> * See {@link #startScan()} and {@link #getScanType()} * * @param activity The resumed {@link Activity}. */ @Override public void onActivityPaused(Activity activity) { current = null; activityCount.decrementAndGet(); if (!startScan()) { stopScan(); } } /** * This method sends a scan request to the {@link BleService}. * * @return True if the service has started, false otherwise. */ protected boolean startScan() { if (isBound() && hasScanPermissions() && shouldStartScan()) { updateScanType(getScanType()); updateScanFilter(getScanFilter()); getBleService().startScan(); return true; } return false; } /** * This method requests the {@link BleService} to stop scanning. */ protected void stopScan() { if (isBound()) { getBleService().stopScan(); } } /** * This method sets the scan type of the {@link BleService}. * * @param scanType The {@link BleService.ScanType scan type} */ protected void updateScanType(BleService.ScanType scanType) { Logger.logInfo("Updating scan type to " + scanType); getBleService().setScanType(scanType); } /** * This method sets the scan filter of the {@link BleService}. * * @param scanFilter The {@link ScanFilter scan filter} */ protected void updateScanFilter(ScanFilter scanFilter) { getBleService().setScanFilter(scanFilter); } /** * Override this in order to chose which scan filter is to be used before {@link #startScan} is called when the service starts. * * @return The {@link ScanFilter} to be used in the current application state. */ protected ScanFilter getScanFilter() { return new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString("7265656C-7941-6374-6976-652055554944")).build(); } /** * Override this in order to chose which kind of scan is to be used before {@link #startScan} is called when the service starts. * * @return The {@link BleService.ScanType} to be used in the current application state. */ protected BleService.ScanType getScanType() { return getActivityCount() == 0 ? BleService.ScanType.LOW_POWER : BleService.ScanType.ACTIVE; } /** * Called by the class in order to check if a scan should be started.<br> * Override this method if you need to change the behaviour of the scan. * * @return true if the conditions for a scan are present, false otherwise. */ protected boolean shouldStartScan() { return isReelyAware(getCurrentActivity()); } protected boolean hasScanPermissions() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if ( ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) { return false; // Don't start scanning if we are not allowed to use the location. } } return true; } /** * This method is called when a {@link BleService.Event} is received.<br/> * Its default behaviour is to notify the currently running {@link ReelyAwareActivity} (if any).<br/> * Override this and you can customize the behaviour of the application. * * @param event The {@link BleService.Event} received from the {@link BleService}. * @return true if the event was processed, false otherwise; */ @Override public boolean onBleEvent(BleService.Event event, Object data) { boolean processed = isReelyAware(getCurrentActivity()); switch (event) { case IN_REGION: if (processed) {
((ReelyAwareActivity) getCurrentActivity()).onEnterRegion((ScanResult) data);
3
syvaidya/openstego
src/main/java/com/openstego/desktop/plugin/dwtdugad/DWTDugadPlugin.java
[ "public class OpenStegoException extends Exception {\n private static final long serialVersionUID = 668241029491685413L;\n\n /**\n * Error Code - Unhandled exception\n */\n static final int UNHANDLED_EXCEPTION = 0;\n\n /**\n * Map to store error code to message key mapping\n */\n priv...
import com.openstego.desktop.OpenStegoException; import com.openstego.desktop.plugin.template.image.WMImagePluginTemplate; import com.openstego.desktop.util.ImageHolder; import com.openstego.desktop.util.ImageUtil; import com.openstego.desktop.util.LabelUtil; import com.openstego.desktop.util.StringUtil; import com.openstego.desktop.util.dwt.DWT; import com.openstego.desktop.util.dwt.Image; import com.openstego.desktop.util.dwt.ImageTree; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Random;
/* * Steganography utility to hide messages into cover files * Author: Samir Vaidya (mailto:syvaidya@gmail.com) * Copyright (c) Samir Vaidya */ package com.openstego.desktop.plugin.dwtdugad; /** * Plugin for OpenStego which implements the DWT based algorithm by Dugad. * <p> * This class is based on the code provided by Peter Meerwald at: <a * href="http://www.cosy.sbg.ac.at/~pmeerw/Watermarking/">http://www.cosy.sbg.ac.at/~pmeerw/Watermarking/</a> * <p> * Refer to his thesis on watermarking: Peter Meerwald, Digital Image Watermarking in the Wavelet Transfer Domain, * Master's Thesis, Department of Scientific Computing, University of Salzburg, Austria, January 2001. */ public class DWTDugadPlugin extends WMImagePluginTemplate { /** * LabelUtil instance to retrieve labels */ private static final LabelUtil labelUtil = LabelUtil.getInstance(DWTDugadPlugin.NAMESPACE); /** * Constant for Namespace to use for this plugin */ public final static String NAMESPACE = "DWTDUGAD"; private static final String SIG_MARKER = "DGSG"; private static final String WM_MARKER = "DGWM"; /** * Default constructor */ public DWTDugadPlugin() { LabelUtil.addNamespace(NAMESPACE, "i18n.DWTDugadPluginLabels"); DWTDugadErrors.init(); // Initialize error codes } /** * Gives the name of the plugin * * @return Name of the plugin */ @Override public String getName() { return "DWTDugad"; } /** * Gives a short description of the plugin * * @return Short description of the plugin */ @Override public String getDescription() { return labelUtil.getString("plugin.description"); } /** * Method to embed the message into the cover data * * @param msg Message to be embedded * @param msgFileName Name of the message file. If this value is provided, then the filename should be embedded in * the cover data * @param cover Cover data into which message needs to be embedded * @param coverFileName Name of the cover file * @param stegoFileName Name of the output stego file * @return Stego data containing the message * @throws OpenStegoException Processing issues */ @Override public byte[] embedData(byte[] msg, String msgFileName, byte[] cover, String coverFileName, String stegoFileName) throws OpenStegoException {
ImageHolder image;
2
comtel2000/mokka7
mokka7-samples/src/main/java/org/comtel2000/mokka7/clone/HearbeatSample2.java
[ "public abstract class ClientRunner {\n\n protected static byte[] buffer = new byte[1024];\n\n protected static final Logger logger = LoggerFactory.getLogger(ClientRunner.class);\n\n private static final String host = \"127.0.0.1\";\n private static final int rack = 0;\n private static final int slot...
import java.util.Arrays; import org.comtel2000.mokka7.ClientRunner; import org.comtel2000.mokka7.S7Client; import org.comtel2000.mokka7.type.AreaType; import org.comtel2000.mokka7.type.DataType; import org.comtel2000.mokka7.util.S7;
/* * PROJECT Mokka7 (fork of Snap7/Moka7) * * Copyright (c) 2017 J.Zimmermann (comtel2000) * * All rights reserved. This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Mokka7 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE whatever license you * decide to adopt. * * Contributors: J.Zimmermann - Mokka7 fork * */ package org.comtel2000.mokka7.clone; /** * Clone bit of DB200.DBX34.0 to DB200.DBX34.1 * * @author comtel * */ public class HearbeatSample2 extends ClientRunner { public HearbeatSample2() { super(); } @Override
public void call(S7Client client) throws Exception {
1
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/presenter/SearchPresenter.java
[ "public class FilterUtils {\n public static boolean underSupport(String type) {\n return !((Constants.ARTICLE_TYPE_THEME.equals(type)) || (Constants.ARTICLE_TYPE_MAGAZINE.equals(type)) || (Constants.ARTICLE_TYPE_MAGAZINE_V2.equals(type)) || (Constants.ARTICLE_TYPE_SUBJECT.equals(type)));\n }\n \n ...
import java.util.ArrayList; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import nich.work.aequorea.R; import nich.work.aequorea.common.utils.FilterUtils; import nich.work.aequorea.common.utils.NetworkUtils; import nich.work.aequorea.model.entity.Data; import nich.work.aequorea.model.entity.Datum; import nich.work.aequorea.model.entity.search.Content; import nich.work.aequorea.model.entity.search.SearchData; import nich.work.aequorea.model.entity.search.SearchDatum;
package nich.work.aequorea.presenter; public class SearchPresenter extends SimpleArticleListPresenter { @Override public void load() { if (!NetworkUtils.isNetworkAvailable()) { onError(new Throwable(getString(R.string.please_connect_to_the_internet))); return; } if (mPage > mTotalPage || mBaseView.getModel().isLoading()) { return; } mBaseView.getModel().setLoading(true); mComposite.add(mService.getArticleListWithKeyword(mPage, 20, mBaseView.getModel() .getKey(), false, "article") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<SearchData>() { @Override public void accept(SearchData data) throws Exception { onSearchDataLoaded(data); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { onError(throwable); } })); } private void onSearchDataLoaded(SearchData searchData) { Data data = transferSearchDataIntoNormalData(searchData); super.onDataLoaded(data); } // fuck this api designer private Data transferSearchDataIntoNormalData(SearchData searchData) { Data data = new Data(); List<SearchDatum> searchDataList = searchData.getData(); int size = searchDataList.size(); if (size != 0) { List<Datum> dataList = new ArrayList<>(); for (int i = 0; i < size; i++) { Content content = searchDataList.get(i).getContent();
if (FilterUtils.underSupport(content.getArticleType())) {
0
grennis/MongoExplorer
app/src/main/java/com/innodroid/mongobrowser/ui/DocumentDetailFragment.java
[ "public class Events {\n public static void postAddConnection() {\n EventBus.getDefault().post(new AddConnection());\n }\n\n public static void postConnectionSelected(long connectionID) {\n EventBus.getDefault().post(new ConnectionSelected(connectionID));\n }\n\n public static void post...
import android.os.Bundle; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.innodroid.mongobrowser.Events; import com.innodroid.mongobrowser.data.MongoData; import com.innodroid.mongobrowser.util.MongoHelper; import com.innodroid.mongobrowser.Constants; import com.innodroid.mongobrowser.R; import com.innodroid.mongobrowser.util.JsonUtils; import com.innodroid.mongobrowser.util.SafeAsyncTask; import com.innodroid.mongobrowser.util.UiUtils; import com.innodroid.mongobrowser.util.UiUtils.ConfirmCallbacks; import butterknife.Bind;
package com.innodroid.mongobrowser.ui; public class DocumentDetailFragment extends BaseFragment { @Bind(R.id.document_detail_content) TextView mContentText; private String mRawText; public DocumentDetailFragment() { } @NonNull public static DocumentDetailFragment newInstance(int collectionIndex, int documentIndex) { Bundle arguments = new Bundle(); DocumentDetailFragment fragment = new DocumentDetailFragment(); arguments.putInt(Constants.ARG_COLLECTION_INDEX, collectionIndex); arguments.putInt(Constants.ARG_DOCUMENT_INDEX, documentIndex); fragment.setArguments(arguments); return fragment; } @Override public int getTitleText() { return R.string.document; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(R.layout.fragment_document_detail, inflater, container, savedInstanceState); updateContent(); return view; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.document_detail_menu, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_document_detail_edit: if (mRawText != null)
Events.postEditDocument(getArguments().getInt(Constants.ARG_DOCUMENT_INDEX));
0
NuVotifier/NuVotifier
common/src/test/java/com/vexsoftware/votifier/net/protocol/VotifierProtocol2DecoderTest.java
[ "public interface VotifierPlugin extends VoteHandler {\n AttributeKey<VotifierPlugin> KEY = AttributeKey.valueOf(\"votifier_plugin\");\n\n Map<String, Key> getTokens();\n\n KeyPair getProtocolV1Key();\n\n LoggingAdapter getPluginLogger();\n\n VotifierScheduler getScheduler();\n\n default boolean i...
import com.google.gson.JsonObject; import com.vexsoftware.votifier.platform.VotifierPlugin; import com.vexsoftware.votifier.model.Vote; import com.vexsoftware.votifier.net.VotifierSession; import com.vexsoftware.votifier.util.GsonInst; import com.vexsoftware.votifier.util.KeyCreator; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.CorruptedFrameException; import io.netty.handler.codec.DecoderException; import org.json.JSONObject; import org.junit.jupiter.api.Test; import javax.crypto.Mac; import java.nio.charset.StandardCharsets; import java.security.Key; import java.util.Base64; import static org.junit.jupiter.api.Assertions.*;
package com.vexsoftware.votifier.net.protocol; public class VotifierProtocol2DecoderTest { private static final VotifierSession SESSION = new VotifierSession(); private EmbeddedChannel createChannel() { EmbeddedChannel channel = new EmbeddedChannel(new VotifierProtocol2Decoder()); channel.attr(VotifierSession.KEY).set(SESSION);
channel.attr(VotifierPlugin.KEY).set(TestVotifierPlugin.getI());
0
sastix/cms
common/services/src/test/com/sastix/cms/common/services/ApiVersionControllerTest.java
[ "public interface Constants {\n\n /**\n * Rest API Version.\n */\n static String REST_API_1_0 = \"1.0\";\n String GET_API_VERSION = \"/apiversion\";\n String DEFAULT_LANGUAGE = \"en\";\n\n /**\n * CONTENT API ENDPOINTS\n */\n static String CREATE_RESOURCE = \"createResource\";\n ...
import com.sastix.cms.common.Constants; import com.sastix.cms.common.dataobjects.VersionDTO; import com.sastix.cms.common.services.api.ApiVersionService; import com.sastix.cms.common.services.api.ApiVersionServiceImpl; import com.sastix.cms.common.services.web.ApiVersionController; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import lombok.extern.slf4j.Slf4j; import com.sastix.cms.common.services.ApiVersionControllerTest.TestConfig; import static org.junit.Assert.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
/* * Copyright(c) 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sastix.cms.common.services; @Slf4j @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TestConfig.class}) public class ApiVersionControllerTest { static VersionDTO TEST_VERSION = new VersionDTO() .withMinVersion(1.0) .withMaxVersion(1.0) .withVersionContext(1.0,"/testapi/v1.0"); static String TEST_VERSION_JSON = "{\"minVersion\":1.0,\"maxVersion\":1.0,\"versionContexts\":{\"1.0\":\"/testapi/v1.0\"}}"; @Autowired
ApiVersionService service;
2
nodebox/nodebox
src/main/java/nodebox/client/Application.java
[ "public class Log {\n private static final Logger LOGGER = java.util.logging.Logger.getGlobal();\n\n static {\n try {\n // Initialize logging directory\n AppDirs.ensureUserLogDir();\n File logDir = AppDirs.getUserLogDir();\n\n // Initialize file logging\n ...
import nodebox.Log; import nodebox.node.NodeLibrary; import nodebox.node.NodeRepository; import nodebox.ui.ExceptionDialog; import nodebox.ui.LastResortHandler; import nodebox.ui.Platform; import nodebox.ui.ProgressDialog; import nodebox.versioncheck.Host; import nodebox.versioncheck.Updater; import nodebox.versioncheck.Version; import javax.swing.*; import java.awt.*; import java.awt.desktop.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import java.util.prefs.Preferences;
/* * This file is part of NodeBox. * * Copyright (C) 2008 Frederik De Bleser (frederik@pandora.be) * * NodeBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NodeBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NodeBox. If not, see <http://www.gnu.org/licenses/>. */ package nodebox.client; public class Application implements Host { public static final String PREFERENCE_ENABLE_DEVICE_SUPPORT = "NBEnableDeviceSupport"; public static boolean ENABLE_DEVICE_SUPPORT = false; private static Application instance; private JFrame hiddenFrame; private ExamplesBrowser examplesBrowser; public static Application getInstance() { return instance; } private AtomicBoolean startingUp = new AtomicBoolean(true); private SwingWorker<Throwable, String> startupWorker; private Updater updater; private List<NodeBoxDocument> documents = new ArrayList<NodeBoxDocument>(); private NodeBoxDocument currentDocument; private NodeRepository systemRepository; private ProgressDialog startupDialog; private Version version; private List<File> filesToLoad = Collections.synchronizedList(new ArrayList<File>()); private Console console = null; public static final String NAME = "NodeBox"; private Application() { instance = this; initLastResortHandler(); initLookAndFeel(); System.setProperty("line.separator", "\n"); } //// Application Load //// /** * Starts a SwingWorker that loads the application in the background. * <p> * Called in the event dispatch thread using invokeLater. */ private void run() { showProgressDialog(); startupWorker = new SwingWorker<Throwable, String>() { @Override protected Throwable doInBackground() throws Exception { try { publish("Starting NodeBox"); initApplication(); checkForUpdates(); } catch (RuntimeException ex) { return ex; } return null; } @Override protected void process(List<String> strings) { final String firstString = strings.get(0); startupDialog.setMessage(firstString); } @Override protected void done() { startingUp.set(false); startupDialog.setVisible(false); // See if application startup has generated an exception. Throwable t; try { t = get(); } catch (Exception e) { t = e; } if (t != null) { ExceptionDialog ed = new ExceptionDialog(null, t); ed.setVisible(true); System.exit(-1); } if (documents.isEmpty() && filesToLoad.isEmpty()) { instance.createNewDocument(); } else { for (File f : filesToLoad) { openDocument(f); } } } }; startupWorker.execute(); } private void initApplication() { installDefaultExceptionHandler(); setNodeBoxVersion(); createNodeBoxDataDirectories(); applyPreferences(); registerForMacOSXEvents(); initPython(); } private void installDefaultExceptionHandler() { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, final Throwable e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ExceptionDialog d = new ExceptionDialog(null, e); d.setVisible(true); } }); } }); } private void checkForUpdates() { updater = new Updater(Application.this); updater.checkForUpdatesInBackground(); } /** * Sets a handler for uncaught exceptions that pops up a message dialog with the exception. * <p> * Called from the constructor, in the main thread. */ private void initLastResortHandler() {
Thread.currentThread().setUncaughtExceptionHandler(new LastResortHandler());
1
holmes-org/holmes-validation
src/main/java/org/holmes/HolmesEngine.java
[ "public class BooleanEvaluator extends ObjectEvaluator<Boolean> {\n\n\tpublic BooleanEvaluator(Boolean target) {\n\n\t\tsuper(target);\n\t}\n\n\t/**\n\t * Ensures that the {@link Boolean} target is not null and it's logical value is TRUE.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Join...
import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import org.holmes.evaluator.BooleanEvaluator; import org.holmes.evaluator.CollectionEvaluator; import org.holmes.evaluator.DateEvaluator; import org.holmes.evaluator.NumberEvaluator; import org.holmes.evaluator.ObjectEvaluator; import org.holmes.evaluator.StringEvaluator; import org.holmes.exception.RuleViolationException; import org.holmes.exception.ValidationException; import org.holmes.resolver.SimpleMessageResolver;
package org.holmes; /** * The main class of the framework. * * @author diegossilveira */ public class HolmesEngine { private final List<Rule> rules; private final ResultCollector collector; private MessageResolver messageResolver; private String defaultViolationDescriptor; private HolmesEngine(ResultCollector collector) { rules = new ArrayList<Rule>(); this.messageResolver = new SimpleMessageResolver(); this.collector = collector; } /** * Initializes the engine with GREEDY {@link Op2erationMode}. * * @return initialized engine instance. */ public static HolmesEngine init() { return new HolmesEngine(OperationMode.GREEDY.getResultCollector()); } /** * Initializes the engine with the given {@link OperationMode}. * * @param mode * the {@link OperationMode} * @return initialized engine instance. */ public static HolmesEngine init(OperationMode mode) { return new HolmesEngine(mode.getResultCollector()); } /** * Initializes the engine with the given {@link ResultCollector}. * * @param collector * @return initialized engine instance. */ public static HolmesEngine init(ResultCollector collector) { return new HolmesEngine(collector); } /** * Creates a new {@link Rule} for a {@link Boolean} target type. * * @param bool * the target * @return an appropriated {@link Evaluator} for the given target type. */
public BooleanEvaluator ensureThat(final Boolean bool) {
0
alda-lang/alda-client-java
src/alda/repl/commands/ReplDownUp.java
[ "public class AldaScore {\n @SerializedName(\"chord-mode\")\n public Boolean chordMode;\n @SerializedName(\"current-instruments\")\n public Set<String> currentInstruments;\n\n public Map<String, Set<String>> nicknames;\n\n /**\n * Returns the current instruments if possible\n * @return null if not possibl...
import alda.AldaResponse.AldaScore; import alda.AldaServer; import alda.error.AlreadyUpException; import alda.error.InvalidOptionsException; import alda.error.NoResponseException; import alda.error.SystemException; import alda.repl.AldaRepl; import java.util.function.Consumer; import jline.console.ConsoleReader;
package alda.repl.commands; public class ReplDownUp implements ReplCommand { @Override
public void act(String args, StringBuffer history, AldaServer server,
1
vbauer/jconditions
src/test/java/com/github/vbauer/jconditions/annotation/AbstractAnnotationsTest.java
[ "public class IfJavaVersionChecker implements ConditionChecker<IfJavaVersion> {\n\n private static final String PROPERTY_JAVA_VERSION = \"java.version\";\n\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean isSatisfied(final CheckerContext<IfJavaVersion> context) {\n final IfJava...
import com.github.vbauer.jconditions.checker.IfJavaVersionChecker; import com.github.vbauer.jconditions.core.CheckerContext; import com.github.vbauer.jconditions.core.ConditionChecker; import com.github.vbauer.jconditions.misc.Always; import com.github.vbauer.jconditions.misc.AppleWorksFine; import com.github.vbauer.jconditions.misc.Never; import com.github.vbauer.jconditions.util.FSUtils; import com.github.vbauer.jconditions.util.PropUtils; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.net.URL; import java.net.URLConnection; import java.util.concurrent.Callable;
package com.github.vbauer.jconditions.annotation; /** * @author Vladislav Bauer */ @Ignore public abstract class AbstractAnnotationsTest implements InterfaceAnnotationsTest { @SuppressWarnings("all") private final boolean isSatisfiedInnerCheck = false; @Test @RunIf(ExceptionClass.class) public void testIgnoreIfException() { Assert.fail(); } @Test
@IgnoreIf(Always.class)
3
KeithYokoma/LGTMCamera
app/src/main/java/jp/yokomark/lgtm/app/compose/model/ComposeStateHolder.java
[ "public class ComposeData implements Parcelable {\n public static final Creator<ComposeData> CREATOR = new Creator<ComposeData>() {\n @Override\n @Nullable\n public ComposeData createFromParcel(Parcel source) {\n return new ComposeData(source);\n }\n\n @Override\n ...
import android.app.LoaderManager; import android.content.Context; import android.content.Loader; import android.graphics.Bitmap; import android.graphics.Point; import android.net.Uri; import android.os.Bundle; import com.amalgam.os.BundleUtils; import com.anprosit.android.dagger.annotation.ForActivity; import com.anprosit.android.dagger.utils.ObjectGraphUtils; import com.squareup.otto.Bus; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.inject.Inject; import jp.yokomark.lgtm.app.compose.entity.ComposeData; import jp.yokomark.lgtm.app.compose.event.SaveSuccessEvent; import jp.yokomark.lgtm.media.loader.SaveImageTask; import jp.yokomark.lgtm.media.utils.ImageUtils; import jp.yokomark.lgtm.misc.event.EventBusUtils; import jp.yokomark.lgtm.misc.model.AbstractModel;
package jp.yokomark.lgtm.app.compose.model; /** * @author yokomakukeishin * @version 1.0.0 * @since 1.0.0 */ public class ComposeStateHolder extends AbstractModel implements LoaderManager.LoaderCallbacks<Uri> { public static final String TAG = ComposeStateHolder.class.getSimpleName(); private static final int LOADER_ID = 1; private static final String ARGS_BITMAP = BundleUtils.buildKey(ComposeStateHolder.class, "ARGS_BITMAP"); private static final String STATE_DATA = BundleUtils.buildKey(ComposeStateHolder.class, "STATE_DATA"); private static final String STATE_VIEW_DIM = BundleUtils.buildKey(ComposeStateHolder.class, "STATE_VIEW_DIM"); private static final String STATE_X_SCALE = BundleUtils.buildKey(ComposeStateHolder.class, "STATE_X_SCALE"); private static final String STATE_Y_SCALE = BundleUtils.buildKey(ComposeStateHolder.class, "STATE_Y_SCALE"); private ComposeData mData; private Point mViewDimension; private float mXScaleFactor; private float mYScaleFactor; @Inject Bus mBus; @Inject public ComposeStateHolder(@ForActivity Context context) { super(context); ObjectGraphUtils.getObjectGraph(context).inject(this); } @Override public Loader<Uri> onCreateLoader(int id, Bundle args) { Bitmap bitmap = args.getParcelable(ARGS_BITMAP);
return new SaveImageTask(getContext(), bitmap);
2
PaulNoth/saral
src/main/java/com/pidanic/saral/domain/ArrayDeclaration.java
[ "public abstract class Expression {\n private Type type;\n\n public Expression(Type type) {\n this.type = type;\n }\n\n public Type type() {\n return type;\n }\n\n public abstract void accept(ExpressionGenerator generator);\n}", "public class CastExpression extends UnaryExpression ...
import com.pidanic.saral.domain.expression.Expression; import com.pidanic.saral.domain.expression.cast.CastExpression;; import com.pidanic.saral.generator.SimpleStatementGenerator; import com.pidanic.saral.generator.StatementGenerator; import com.pidanic.saral.util.BuiltInType; import com.pidanic.saral.util.Type;
package com.pidanic.saral.domain; public class ArrayDeclaration implements SimpleStatement { private Type type;
private Expression length;
0
VisualDataWeb/OWL2VOWL
src/main/java/de/uni_stuttgart/vis/vowl/owl2vowl/Owl2Vowl.java
[ "public interface Converter {\n\tString getLoadingInfoString();\n\tvoid setOntologyHasMissingImports(boolean val);\n\tboolean ontologyHasMissingImports();\n\tvoid addLoadingInfo(String msg);\n\tboolean getCurrentlyLoadingFlag();\n\tvoid setCurrentlyLoadingFlag(boolean val);\n\tvoid setCurrentlyLoadingFlag(String pa...
import de.uni_stuttgart.vis.vowl.owl2vowl.converter.Converter; import de.uni_stuttgart.vis.vowl.owl2vowl.converter.IRIConverter; import de.uni_stuttgart.vis.vowl.owl2vowl.converter.InputStreamConverter; import de.uni_stuttgart.vis.vowl.owl2vowl.converter.OntologyConverter; import de.uni_stuttgart.vis.vowl.owl2vowl.export.types.BackupExporter; import de.uni_stuttgart.vis.vowl.owl2vowl.export.types.FileExporter; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLOntology; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.util.Collection;
package de.uni_stuttgart.vis.vowl.owl2vowl; /** * Global class for easy to use of this library to include in other projects. */ public class Owl2Vowl { protected Converter converter; public Owl2Vowl(OWLOntology ontology) {
converter = new OntologyConverter(ontology);
3
wesabe/grendel
src/main/java/com/wesabe/grendel/resources/DocumentsResource.java
[ "public class Credentials {\n\t/**\n\t * An authentication challenge {@link Response}. Use this when a client's\n\t * provided credentials are invalid.\n\t */\n\tpublic static final Response CHALLENGE =\n\t\tResponse.status(Status.UNAUTHORIZED)\n\t\t\t.header(HttpHeaders.WWW_AUTHENTICATE, \"Basic realm=\\\"Grendel\...
import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import com.google.inject.Inject; import com.wesabe.grendel.auth.Credentials; import com.wesabe.grendel.auth.Session; import com.wesabe.grendel.entities.Document; import com.wesabe.grendel.entities.dao.UserDAO; import com.wesabe.grendel.representations.DocumentListRepresentation;
package com.wesabe.grendel.resources; /** * A class which exposes a list of {@link Document}s as a resource. * * @author coda */ @Path("/users/{id}/documents") @Produces(MediaType.APPLICATION_JSON) public class DocumentsResource { final UserDAO userDAO; @Inject public DocumentsResource(UserDAO userDAO) { this.userDAO = userDAO; } @GET public DocumentListRepresentation listDocuments(@Context UriInfo uriInfo,
@Context Credentials credentials, @PathParam("id") String id) {
0
aredee/accumulo-mesos
accumulo-mesos-executor/src/main/java/aredee/mesos/frameworks/accumulo/executor/AccumuloStartExecutor.java
[ "public class Environment {\n\n public static final String JAVA_HOME = \"JAVA_HOME\";\n\n public static final String CLASSPATH = \"CLASSPATH\";\n\n public static final String HADOOP_PREFIX = \"HADOOP_PREFIX\";\n public static final String HADOOP_CONF_DIR = \"HADOOP_CONF_DIR\";\n public static final S...
import aredee.mesos.frameworks.accumulo.configuration.Environment; import aredee.mesos.frameworks.accumulo.initialize.AccumuloInitializer; import aredee.mesos.frameworks.accumulo.initialize.AccumuloSiteXml; import aredee.mesos.frameworks.accumulo.model.ServerProfile; import aredee.mesos.frameworks.accumulo.process.AccumuloProcessFactory; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.mesos.Executor; import org.apache.mesos.ExecutorDriver; import org.apache.mesos.Protos; import org.apache.mesos.Protos.TaskID; import org.apache.mesos.Protos.TaskState; import org.apache.mesos.Protos.TaskStatus; import org.apache.mesos.SchedulerDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask;
package aredee.mesos.frameworks.accumulo.executor; public class AccumuloStartExecutor implements Executor { private static final Logger LOGGER = LoggerFactory.getLogger(AccumuloStartExecutor.class); private static final ObjectMapper mapper = new ObjectMapper(); private Process serverProcess = null; private Protos.ExecutorInfo executorInfo = null; private Protos.FrameworkInfo frameworkInfo = null; private Protos.SlaveInfo slaveInfo = null; private Protos.TaskInfo taskInfo = null; public AccumuloStartExecutor(){ } /** * Invoked once the executor driver has been able to successfully * connect with Mesos. In particular, a scheduler can pass some * data to it's executors through the {@link Protos.ExecutorInfo#getData()} * field. * * @param executorDriver * @param executorInfo Describes information about the executor that was * registered. * @param frameworkInfo Describes the framework that was registered. * @param slaveInfo Describes the slave that will be used to launch * the tasks for this executor. * @see org.apache.mesos.ExecutorDriver * @see org.apache.mesos.MesosSchedulerDriver */ @Override public void registered(ExecutorDriver executorDriver, Protos.ExecutorInfo executorInfo, Protos.FrameworkInfo frameworkInfo, Protos.SlaveInfo slaveInfo) { LOGGER.info("Executor Registered: " + executorInfo.getName()); this.executorInfo = executorInfo; this.frameworkInfo = frameworkInfo; this.slaveInfo = slaveInfo; } /** * Invoked when the executor re-registers with a restarted slave. * * @param executorDriver * @param slaveInfo Describes the slave that will be used to launch * the tasks for this executor. * @see org.apache.mesos.ExecutorDriver */ @Override public void reregistered(ExecutorDriver executorDriver, Protos.SlaveInfo slaveInfo) { LOGGER.info("Re-registered with mesos slave: " + slaveInfo.getHostname()); } /** * Invoked when the executor becomes "disconnected" from the slave * (e.g., the slave is being restarted due to an upgrade). * * @param executorDriver */ @Override public void disconnected(ExecutorDriver executorDriver) { // TODO set timer and destroy server if slave doesn't come back? LOGGER.info("Disconnected from Mesos slave"); } /** * Invoked when a task has been launched on this executor (initiated * via {@link SchedulerDriver#launchTasks}. Note that this task can be * realized with a thread, a process, or some simple computation, * however, no other callbacks will be invoked on this executor * until this callback has returned. * * @param executorDriver * @param taskInfo * @see org.apache.mesos.ExecutorDriver * @see org.apache.mesos.Protos.TaskInfo */ @Override public void launchTask(ExecutorDriver executorDriver, Protos.TaskInfo taskInfo) { LOGGER.info("Launch TaskInfo " + taskInfo); LOGGER.info("Launch Task Requested: " + taskInfo.getCommand()); this.taskInfo = taskInfo; // If there is another executor then exit?! checkForRunningExecutor(); // get server profile byte[] profileBytes = taskInfo.getData().toByteArray(); ServerProfile profile = null; try { profile = mapper.readValue(profileBytes, ServerProfile.class); } catch (IOException e) { LOGGER.error("Unable to deserialze ServerProfile"); // TODO what do? e.printStackTrace(); } //TODO get jvmArgs and args from protobuf? List<String> jvmArgs = new ArrayList<>(); String[] args = new String[0]; try { // accumulo-site.xml is sent in from scheduler // reify the xml and add in the tserver memory settings before writing
AccumuloSiteXml siteXml = new AccumuloSiteXml();
2
dnbn/smbtv
app/src/main/java/com/smbtv/ui/activity/fragment/MainFragmentUIBuilder.java
[ "public class SMBShareDelegate {\n\n private SMBShareDAO mDao;\n\n public SMBShareDelegate() {\n\n Context context = ApplicationDelegate.getContext();\n this.mDao = new SMBShareDAO(context);\n }\n\n public void delete(SMBShare share) {\n\n mDao.delete(share);\n }\n\n public vo...
import android.app.Activity; import android.support.v17.leanback.widget.ArrayObjectAdapter; import android.support.v17.leanback.widget.HeaderItem; import android.support.v17.leanback.widget.ListRow; import android.util.Log; import com.smbtv.R; import com.smbtv.delegate.SMBShareDelegate; import com.smbtv.model.SMBShare; import com.smbtv.delegate.SMBServerDelegate; import com.smbtv.ui.components.MenuAction; import com.smbtv.ui.components.MenuItem; import com.smbtv.ui.components.MenuItemPresenter; import java.util.List;
package com.smbtv.ui.activity.fragment; public class MainFragmentUIBuilder { private static final String TAG = MainFragmentUIBuilder.class.getSimpleName(); private Activity mParent; private int cpt; public MainFragmentUIBuilder(Activity parent) { this.mParent = parent; } public ListRow buildShares() { Log.d(TAG, "buildShares"); ArrayObjectAdapter rowAdapter = new ArrayObjectAdapter(new MenuItemPresenter());
rowAdapter.add(new MenuItem(MenuAction.AddShare, getLabel(R.string.add), R.drawable.ic_add));
3
EBIvariation/eva-ws
eva-release/src/main/java/uk/ac/ebi/eva/release/services/ReleaseStatsService.java
[ "public class ReleaseStatsPerSpeciesDto {\n\n @Id\n private int taxonomyId;\n\n @Id\n private int releaseVersion;\n\n private String scientificName;\n\n private String releaseFolder;\n\n private Long currentRs;\n\n private Long multiMappedRs;\n\n private Long mergedRs;\n\n private Long...
import org.springframework.stereotype.Service; import uk.ac.ebi.eva.release.dto.ReleaseStatsPerSpeciesDto; import uk.ac.ebi.eva.release.models.ReleaseInfo; import uk.ac.ebi.eva.release.models.ReleaseStatsPerSpecies; import uk.ac.ebi.eva.release.repositories.ReleaseInfoRepository; import uk.ac.ebi.eva.release.repositories.ReleaseStatsPerSpeciesRepository; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
/* * Copyright 2020 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.eva.release.services; @Service public class ReleaseStatsService { private static final String SPECIES_DIRECTORY = "by_species/"; private static final String TAXONOMY_URL = "https://www.ebi.ac.uk/ena/browser/view/Taxon:";
private final ReleaseStatsPerSpeciesRepository releaseStatsPerSpeciesRepository;
4
ypresto/miniguava
miniguava-collect-immutables/src/main/java/net/ypresto/miniguava/collect/immutables/InternalUtils.java
[ "public static <T> T checkNotNull(T reference) {\n if (reference == null) {\n throw new NullPointerException();\n }\n return reference;\n}", "public class Joiner {\n /**\n * Returns a joiner which automatically places {@code separator} between consecutive elements.\n */\n @CheckReturnValue\n public s...
import static net.ypresto.miniguava.base.Preconditions.checkNotNull; import net.ypresto.miniguava.annotations.MiniGuavaSpecific; import net.ypresto.miniguava.base.Joiner; import net.ypresto.miniguava.base.Joiner.MapJoiner; import net.ypresto.miniguava.collect.UnmodifiableIterator; import net.ypresto.miniguava.collect.internal.AbstractMapEntry; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable;
/* * Copyright (C) 2016 The Guava 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 net.ypresto.miniguava.collect.immutables; // miniguava: A collection of helper methods used in this module. @MiniGuavaSpecific class InternalUtils { private InternalUtils() {} /** * The largest power of two that can be represented as an {@code int}. * * @since 10.0 */ @MiniGuavaSpecific(value = MiniGuavaSpecific.Reason.COPIED, from = "primitives.Ints") public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); // miniguava: From Sets.java, original method name: hashCodeImpl /** * An implementation for {@link Set#hashCode()}. */ static int setsHashCodeImpl(Set<?> s) { int hashCode = 0; for (Object o : s) { hashCode += o != null ? o.hashCode() : 0; hashCode = ~~hashCode; // Needed to deal with unusual integer overflow in GWT. } return hashCode; } /** * An implementation for {@link Set#equals(Object)}. */ @MiniGuavaSpecific(value = MiniGuavaSpecific.Reason.COPIED, from = "collect.Sets#equalsImpl") static boolean setsEqualsImpl(Set<?> s, @Nullable Object object) { if (s == object) { return true; } if (object instanceof Set) { Set<?> o = (Set<?>) object; try { return s.size() == o.size() && s.containsAll(o); } catch (NullPointerException ignored) { return false; } catch (ClassCastException ignored) { return false; } } return false; } /** * An implementation of {@link Map#equals}. */ @MiniGuavaSpecific(value = MiniGuavaSpecific.Reason.COPIED, from = "collect.Maps#equalsImpl") static boolean mapsEqualsImpl(Map<?, ?> map, Object object) { if (map == object) { return true; } else if (object instanceof Map) { Map<?, ?> o = (Map<?, ?>) object; return map.entrySet().equals(o.entrySet()); } return false; } /** * Returns best-effort-sized StringBuilder based on the given collection size. */ @MiniGuavaSpecific(value = MiniGuavaSpecific.Reason.COPIED, from = "collect.Collections2") static StringBuilder newStringBuilderForCollection(int size) { checkNonnegative(size, "size"); return new StringBuilder((int) Math.min(size * 8L, MAX_POWER_OF_TWO)); } @MiniGuavaSpecific(value = MiniGuavaSpecific.Reason.COPIED, from = "collect.Collections2")
static final Joiner STANDARD_JOINER = Joiner.on(", ").useForNull("null");
1
iChun/Sync
src/main/java/me/ichun/mods/sync/common/tileentity/TileEntityDualVertical.java
[ "@SideOnly(Side.CLIENT)\npublic class SyncSkinManager {\n //Cache skins throughout TEs to avoid hitting the rate limit for skin session servers\n //Hold values for a longer time, so they are loaded fast if many TEs with the same player are loaded, or when loading other chunks with the same player\n //Skin ...
import io.netty.buffer.ByteBuf; import me.ichun.mods.ichunutil.common.core.util.EntityHelper; import me.ichun.mods.sync.client.core.SyncSkinManager; import me.ichun.mods.sync.common.Sync; import me.ichun.mods.sync.common.block.BlockDualVertical; import me.ichun.mods.sync.common.packet.PacketNBT; import me.ichun.mods.sync.common.packet.PacketZoomCamera; import me.ichun.mods.sync.common.shell.ShellHandler; import me.ichun.mods.sync.common.shell.TeleporterShell; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.server.management.PlayerInteractionManager; import net.minecraft.server.management.PlayerList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.*; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.GameType; import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.Constants; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.network.ByteBufUtils; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import java.util.List; import java.util.Set; import java.util.UUID;
} //Beginning of kicking the player out if (this.resyncPlayer == 40) { this.vacating = true; if (this.getClass() == TileEntityShellStorage.class) { TileEntityShellStorage shellStorage = (TileEntityShellStorage) this; shellStorage.occupied = true; shellStorage.occupationTime = animationTime; } else if (this.getClass() == TileEntityShellConstructor.class) { TileEntityShellConstructor shellConstructor = (TileEntityShellConstructor) this; shellConstructor.doorOpen = true; } IBlockState state = world.getBlockState(getPos()); IBlockState state1 = world.getBlockState(getPos().add(0, 1, 0)); world.notifyBlockUpdate(getPos(), state, state, 3); world.notifyBlockUpdate(getPos().add(0, 1, 0), state1, state1, 3); } //This is where we begin to sync the data aka point of no return if (this.resyncPlayer == 30) { EntityPlayerMP player = getPlayerIfAvailable(); if (player != null && player.isEntityAlive()) { //Clear active potion effects before syncing player.clearActivePotions(); if (Sync.config.transferPersistentItems == 1) { if (wasDead) { //copy new items that are given on death, like the key to a tombstone EntityPlayerMP deadDummy = setupDummy(player); mergeStoredInv(deadDummy.inventory); } //Copy data needed from player NBTTagCompound tag = new NBTTagCompound(); EntityPlayerMP dummy = setupDummy(player); //Set data dummy.writeToNBT(tag); if (resyncOrigin != null) //deduplicate items { //Strip items from the old inv that have been transferred to the new inventory deleteItemsFrom(player.inventory.mainInventory, dummy.inventory.mainInventory); deleteItemsFrom(player.inventory.armorInventory, dummy.inventory.armorInventory); deleteItemsFrom(player.inventory.offHandInventory, dummy.inventory.offHandInventory); //Write the changes to the old inventory resyncOrigin.getPlayerNBT().setTag("Inventory", player.inventory.writeToNBT(new NBTTagList())); resyncOrigin.markDirty(); if (getPlayerNBT().hasKey("Inventory")) //try inserting persistent items by merging { mergeStoredInv(dummy.inventory); } } else { dummy.inventory.clear(); } if (!getPlayerNBT().hasKey("Inventory")) { tag.setInteger("sync_playerGameMode", player.interactionManager.getGameType().getID()); this.setPlayerNBT(tag); //Write the new data } } else if (!getPlayerNBT().hasKey("Inventory")) //just go this way if configured { //Copy data needed from player NBTTagCompound tag = new NBTTagCompound(); //Setup location for dummy EntityPlayerMP dummy = setupDummy(player); dummy.inventory.clear(); //Set data dummy.writeToNBT(tag); tag.setInteger("sync_playerGameMode", player.interactionManager.getGameType().getID()); this.setPlayerNBT(tag); } wasDead = false; //Sync Forge persistent data as it's supposed to carry over on death NBTTagCompound persistentData = player.getEntityData(); if (persistentData != null) { NBTTagCompound forgeData = playerNBT.getCompoundTag("ForgeData"); forgeData.setTag(EntityPlayer.PERSISTED_NBT_TAG, player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG)); persistentData.setBoolean("isDeathSyncing", false); forgeData.setBoolean("isDeathSyncing", false); playerNBT.setTag("ForgeData", forgeData); } NBTTagCompound persistent = player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG); int healthReduction = persistent.getInteger("Sync_HealthReduction"); //Also sync ender chest. playerNBT.setTag("EnderItems", player.getInventoryEnderChest().saveInventoryToNBT()); //Update the players NBT stuff player.readFromNBT(this.getPlayerNBT()); if(healthReduction > 0) { double curMaxHealth = player.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).getBaseValue(); double morphMaxHealth = curMaxHealth - healthReduction; if(morphMaxHealth < 1D) { morphMaxHealth = 1D; } if(morphMaxHealth != curMaxHealth) { player.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(morphMaxHealth); } } player.interactionManager.initializeGameType(GameType.getByID(this.getPlayerNBT().getInteger("sync_playerGameMode")));
Sync.channel.sendTo(new PacketNBT(this.getPlayerNBT()), player);
3
docbleach/DocBleach
module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PdfBleachSession.java
[ "public class BleachSession implements Serializable {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);\n private static final int MAX_ONGOING_TASKS = 10;\n private final transient Bleach bleach;\n private final Collection<Threat> threats = new ArrayList<>();\n /**\n * Co...
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.io.OutputStream; import org.apache.pdfbox.io.MemoryUsageSetting; import org.apache.pdfbox.io.RandomAccessRead; import org.apache.pdfbox.io.ScratchFile; import org.apache.pdfbox.pdfparser.PDFParser; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentCatalog; import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary; import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import xyz.docbleach.api.BleachSession; import xyz.docbleach.api.exception.BleachException; import xyz.docbleach.api.threat.Threat; import xyz.docbleach.api.threat.ThreatAction; import xyz.docbleach.api.threat.ThreatSeverity; import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.pdf; class PdfBleachSession { private static final Logger LOGGER = LoggerFactory.getLogger(PdfBleachSession.class); private static final String[] COMMON_PASSWORDS = new String[]{null, "", "test", "example", "sample", "malware", "infected", "password"}; private static final MemoryUsageSetting MEMORY_USAGE_SETTING = MemoryUsageSetting.setupMixed(1024 * 100); private final BleachSession session; private final COSObjectBleach cosObjectBleach; PdfBleachSession(BleachSession session) { this.session = session; cosObjectBleach = new COSObjectBleach(this); } void sanitize(RandomAccessRead source, OutputStream outputStream) throws IOException, BleachException { final PDDocument doc = getDocument(source); final PDDocumentCatalog docCatalog = doc.getDocumentCatalog(); sanitizeNamed(doc, docCatalog.getNames()); PDDocumentCatalogBleach catalogBleach = new PDDocumentCatalogBleach(this); catalogBleach.sanitize(docCatalog); sanitizeDocumentOutline(doc.getDocumentCatalog().getDocumentOutline()); cosObjectBleach.sanitizeObjects(doc.getDocument().getObjects()); doc.save(outputStream); doc.close(); } private void sanitizeDocumentOutline(PDDocumentOutline documentOutline) { if (documentOutline == null) { return; } documentOutline.children().forEach(this::sanitizeDocumentOutlineItem); } private void sanitizeDocumentOutlineItem(PDOutlineItem item) { if (item.getAction() == null) { return; } LOGGER.debug("Found&removed action on outline item (was {})", item.getAction()); item.setAction(null); recordJavascriptThreat("DocumentOutline Item Action", "Action"); } private void sanitizeNamed(PDDocument doc, PDDocumentNameDictionary names) { if (names == null) { return; } new PDEmbeddedFileBleach(this, doc).sanitize(names.getEmbeddedFiles()); if (names.getJavaScript() != null) { recordJavascriptThreat("Named JavaScriptAction", "Action"); names.setJavascript(null); } } private PDDocument getDocument(RandomAccessRead source) throws IOException, BleachException { PDDocument doc; for (String pwd : COMMON_PASSWORDS) { ScratchFile scratchFile = new ScratchFile(MEMORY_USAGE_SETTING); doc = testPassword(scratchFile, source, pwd); if (doc != null) { LOGGER.debug("Password was guessed: '{}'", pwd); doc.protect(new StandardProtectionPolicy(pwd, pwd, doc.getCurrentAccessPermission())); return doc; } scratchFile.close(); } // @TODO: fetch password from config? throw new BleachException("PDF is protected with an unknown password"); } @SuppressFBWarnings( value = "EXS_EXCEPTION_SOFTENING_RETURN_FALSE", justification = "This method is an helper to check the password") private PDDocument testPassword(ScratchFile inFile, RandomAccessRead source, String password) throws IOException { PDFParser parser = new PDFParser(source, password, inFile); try { parser.parse(); return parser.getPDDocument(); } catch (InvalidPasswordException e) { LOGGER.error("The tested password is invalid"); return null; } finally { source.rewind((int) source.getPosition()); } } void recordJavascriptThreat(String location, String details) { Threat threat = Threat.builder() .type(ThreatType.ACTIVE_CONTENT) .severity(ThreatSeverity.HIGH) .details(details) .location(location)
.action(ThreatAction.REMOVE)
3
misberner/duzzt
processor/src/main/java/com/github/misberner/duzzt/processor/Duzzt.java
[ "public interface DuzztDiagnosticListener {\n\t\n\t/**\n\t * Called if an expression could not be parsed.\n\t * <p>\n\t * If the parse error occurred while parsing a named subexpression, the name\n\t * of the subexpression will also be passed as the <tt>exprName</tt> parameter.\n\t * Otherwise (that is, if the main...
import java.io.BufferedWriter; import java.io.IOException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.annotation.processing.Filer; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.JavaFileObject; import org.stringtemplate.v4.AutoIndentWriter; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; import org.stringtemplate.v4.STGroupFile; import org.stringtemplate.v4.STWriter; import com.github.misberner.apcommons.reporting.Reporter; import com.github.misberner.apcommons.util.APUtils; import com.github.misberner.apcommons.util.ElementUtils; import com.github.misberner.duzzt.DuzztDiagnosticListener; import com.github.misberner.duzzt.annotations.GenerateEmbeddedDSL; import com.github.misberner.duzzt.automaton.DuzztAutomaton; import com.github.misberner.duzzt.bricscompiler.BricsCompiler; import com.github.misberner.duzzt.exceptions.DuzztInitializationException; import com.github.misberner.duzzt.model.DSLSettings; import com.github.misberner.duzzt.model.DSLSpecification; import com.github.misberner.duzzt.model.ImplementationModel; import com.github.misberner.duzzt.re.DuzztREUtil; import com.github.misberner.duzzt.re.DuzztRegExp;
/* * * Copyright (c) 2014 by Malte Isberner (https://github.com/misberner). * * 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.github.misberner.duzzt.processor; public class Duzzt { public static boolean checkExpressions(DuzztDiagnosticListener el, ImplementationModel im, DuzztRegExp re, Map<String,DuzztRegExp> subExpressions) { return doCheck(el, im, re, null, subExpressions, new HashMap<String,Integer>()); } private static boolean doCheck(DuzztDiagnosticListener el, ImplementationModel im, DuzztRegExp re, String reName, Map<String,DuzztRegExp> subExpressions, Map<String,Integer> visited) { visited.put(reName, 1); boolean error = false; Set<String> identifiers = DuzztREUtil.findIdentifiers(re); for(String id : identifiers) { if(!im.hasActionName(id)) { el.undefinedIdentifier(id, reName); error = true; } } Set<String> subExprs = DuzztREUtil.findReferencedSubexprs(re); for(String se : subExprs) { DuzztRegExp seRe = subExpressions.get(se); if(seRe == null) { el.undefinedSubExpression(se, reName); error = true; } else { Integer state = visited.get(se); if(state == null) { error |= doCheck(el, im, seRe, se, subExpressions, visited); } else if(state == 1) { el.recursiveSubExpression(se); error = true; } } } visited.put(reName, 2); return error; } private static final String ST_ENCODING = "UTF-8"; private static final char ST_DELIM_START_CHAR = '<'; private static final char ST_DELIM_STOP_CHAR = '>'; private static final String ST_RESOURCE_NAME = "/stringtemplates/edsl-source.stg"; private static final String ST_MAIN_TEMPLATE_NAME = "edsl_source"; private STGroup sourceGenGroup; private boolean isJava9OrNewer; /** * Default constructor. */ public Duzzt() { } public boolean isInitialized() { return (sourceGenGroup != null); } /** * Initialize the Duzzt embedded DSL generator. * * @param utils the APUtils instance wrapping the {@link javax.annotation.processing.ProcessingEnvironment} * @throws DuzztInitializationException if a fatal error occurs during initialization */
public void init(APUtils utils) throws DuzztInitializationException {
3
kakao/hbase-tools
hbase0.98/hbase-manager-0.98/src/main/java/com/kakao/hbase/manager/Manager.java
[ "public class ManagerArgs extends Args {\n public ManagerArgs(String[] args) throws IOException {\n super(args);\n }\n\n @Override\n protected OptionParser createOptionParser() {\n OptionParser optionParser = createCommonOptionParser();\n optionParser.accepts(OPTION_OPTIMIZE).withRe...
import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import com.google.common.annotations.VisibleForTesting; import com.kakao.hbase.ManagerArgs; import com.kakao.hbase.common.Args; import com.kakao.hbase.common.HBaseClient; import com.kakao.hbase.common.InvalidTableException; import com.kakao.hbase.common.util.Util; import com.kakao.hbase.manager.command.Command; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.scanners.SubTypesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder;
/* * Copyright 2015 Kakao Corporation * * 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.kakao.hbase.manager; public class Manager { public static final String INVALID_COMMAND = "Invalid command"; public static final String INVALID_ZOOKEEPER = "Invalid zookeeper quorum"; private static final Set<Class<? extends Command>> commandSet; static { Util.setLoggingThreshold("ERROR"); Reflections reflections = createReflections(); commandSet = reflections.getSubTypesOf(Command.class); } private final Args args; private final String commandName; public Manager(Args args, String commandName) throws Exception { this.args = args; this.commandName = commandName; } public static void main(String[] args) throws Exception { String commandName = ""; Args argsObject; try { if (args.length > 0) commandName = args[0]; argsObject = parseArgs(args); } catch (IllegalArgumentException e) { if (commandExists(commandName)) { printError(INVALID_ZOOKEEPER); printUsage(commandName); System.exit(1); } else { printError(INVALID_COMMAND); printUsage(); System.exit(1); } throw e; } try { new Manager(argsObject, commandName).run(); } catch (InvocationTargetException e) { printError(e.getCause().getMessage() + "\n"); printUsage(commandName); System.exit(1); } catch (InvalidTableException e) { printError(e.getMessage()); System.exit(1); } } private static void printError(String message) { System.out.println("ERROR - " + message + "\n"); } private static Reflections createReflections() { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); return new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader( classLoadersList.toArray(new ClassLoader[classLoadersList.size()])))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command")))); } @VisibleForTesting static Set<Class<? extends Command>> getCommandSet() { return commandSet; } @VisibleForTesting static String getCommandUsage(String commandName) throws Exception { for (Class<? extends Command> c : commandSet) { if (c.getSimpleName().toLowerCase().equals(commandName.toLowerCase())) { Method usage = c.getDeclaredMethod("usage"); return (String) usage.invoke(null); } } throw new IllegalArgumentException(INVALID_COMMAND); } private static boolean commandExists(String commandName) { for (Class<? extends Command> c : commandSet) { if (c.getSimpleName().toLowerCase().equals(commandName.toLowerCase())) { return true; } } return false; } private static List<String> getCommandNames() { List<String> commandNames = new ArrayList<>(); for (Class<? extends Command> c : commandSet) { commandNames.add(c.getSimpleName().toLowerCase()); } Collections.sort(commandNames); return commandNames; } private static void printUsage() { System.out.println("Usage: " + Manager.class.getSimpleName() + " <command> (<zookeeper quorum>|<args file>) [args...]"); System.out.println(" commands:"); for (String c : getCommandNames()) System.out.println(" " + c); System.out.println(Args.commonUsage()); } @VisibleForTesting static Args parseArgs(String[] argsParam) throws Exception { if (argsParam.length == 0) throw new IllegalArgumentException(Args.INVALID_ARGUMENTS); if (!commandExists(argsParam[0])) throw new IllegalArgumentException(INVALID_COMMAND); return new ManagerArgs(Arrays.copyOfRange(argsParam, 1, argsParam.length)); } private static void printUsage(String commandName) throws Exception { String usage = getCommandUsage(commandName); if (usage == null) { System.out.println("Usage is not implemented"); } else { System.out.println(usage); } } public void run() throws Exception {
try (HBaseAdmin admin = HBaseClient.getAdmin(args)) {
2
didi/VirtualAPK
CoreLibrary/src/main/java/com/didi/virtualapk/internal/VAInstrumentation.java
[ "public class Instrumentation {\n \n public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {\n throw new RuntimeException(\"Stub!\");\n }\n \n public void callApplicationOnCreate(Applic...
import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.app.Fragment; import android.app.Instrumentation; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PersistableBundle; import android.util.Log; import com.didi.virtualapk.PluginManager; import com.didi.virtualapk.delegate.StubActivity; import com.didi.virtualapk.internal.utils.PluginUtil; import com.didi.virtualapk.utils.Reflector; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List;
/* * Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. 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 com.didi.virtualapk.internal; /** * Created by renyugang on 16/8/10. */ public class VAInstrumentation extends Instrumentation implements Handler.Callback { public static final String TAG = Constants.TAG_PREFIX + "VAInstrumentation"; public static final int LAUNCH_ACTIVITY = 100; protected Instrumentation mBase; protected final ArrayList<WeakReference<Activity>> mActivities = new ArrayList<>();
protected PluginManager mPluginManager;
1
KostyaSha/github-integration-plugin
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRLabelAddPublisher.java
[ "public class GitHubPRLabel implements Describable<GitHubPRLabel> {\n private Set<String> labels;\n\n @DataBoundConstructor\n public GitHubPRLabel(String labels) {\n this(new HashSet<>(Arrays.asList(labels.split(\"\\n\"))));\n }\n\n public GitHubPRLabel(Set<String> labels) {\n this.labe...
import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import jenkins.model.Jenkins; import org.jenkinsci.Symbol; import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel; import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher; import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler; import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier; import org.kohsuke.github.GHIssue; import org.kohsuke.github.GHLabel; import org.kohsuke.stapler.DataBoundConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.umd.cs.findbugs.annotations.NonNull; import java.io.IOException; import java.util.HashSet; import java.util.stream.Collectors; import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue; import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
package org.jenkinsci.plugins.github.pullrequest.publishers.impl; /** * Implements addition of labels (one or many) to GitHub. * * @author Alina Karpovich * @author Kanstantsin Shautsou */ public class GitHubPRLabelAddPublisher extends GitHubPRAbstractPublisher { private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRLabelAddPublisher.class);
private GitHubPRLabel labelProperty;
0
micdoodle8/Crossbow_Mod_2
src/main/java/micdoodle8/mods/crossbowmod/CrossbowEvents.java
[ "public class EntityDiamondBolt extends EntityBolt\n{\n public EntityDiamondBolt(World world)\n {\n super(world);\n }\n\n public EntityDiamondBolt(World world, double d, double d1, double d2)\n {\n super(world, d, d1, d2);\n }\n\n public EntityDiamondBolt(World world, EntityLiving...
import cpw.mods.fml.common.eventhandler.SubscribeEvent; import micdoodle8.mods.crossbowmod.entity.EntityDiamondBolt; import micdoodle8.mods.crossbowmod.entity.EntityGoldBolt; import micdoodle8.mods.crossbowmod.entity.EntityIronBolt; import micdoodle8.mods.crossbowmod.entity.EntityStoneBolt; import micdoodle8.mods.crossbowmod.entity.EntityWoodBolt; import micdoodle8.mods.crossbowmod.util.Util; import net.minecraft.entity.passive.EntityChicken; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.event.entity.living.LivingDeathEvent;
package micdoodle8.mods.crossbowmod; public class CrossbowEvents { @SubscribeEvent public void deathEvent(LivingDeathEvent event) {
if (event.entity instanceof EntityChicken && (event.source.getSourceOfDamage() instanceof EntityWoodBolt || event.source.getSourceOfDamage() instanceof EntityStoneBolt || event.source.getSourceOfDamage() instanceof EntityIronBolt || event.source.getSourceOfDamage() instanceof EntityGoldBolt || event.source.getSourceOfDamage() instanceof EntityDiamondBolt) && event.source.getEntity() instanceof EntityPlayer)
3
szmg/grafana-dashboard-generator-java
grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/complex/MultiEnvExampleDashboards.java
[ "public interface DashboardFactory {\n\n /**\n * Creates dashboards.\n * @return a list of dashboards created, should not be {@code null}\n */\n List<Dashboard> create();\n\n}", "public class ColorTheme {\n\n /**\n * A simple, red-yellow-green and white theme.\n */\n public static ...
import static uk.co.szmg.grafana.dashboard.StaticFactories.placeholder; import static uk.co.szmg.grafana.dashboard.StaticFactories.thinRow; import static uk.co.szmg.grafana.dashboard.StaticFactories.title; import static uk.co.szmg.grafana.domain.DomainFactories.newDashboard; import static uk.co.szmg.grafana.domain.DomainFactories.newRow; import uk.co.szmg.grafana.DashboardFactory; import uk.co.szmg.grafana.dashboard.ColorTheme; import uk.co.szmg.grafana.domain.Dashboard; import uk.co.szmg.grafana.domain.Row; import uk.co.szmg.grafana.domain.SingleStat; import javax.inject.Named; import java.util.ArrayList; import java.util.List;
package uk.co.szmg.grafana.example.dashboards.complex; /*- * #%L * grafana-dashboard-generator-example * %% * Copyright (C) 2017 Mate Gabor Szvoboda * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ @Named public class MultiEnvExampleDashboards implements DashboardFactory { private SampleAppEnvironment environments[] = new SampleAppEnvironment[]{ new SampleAppEnvironment("Staging", "graphite", "MYAPP.stage", 2), new SampleAppEnvironment("Production", "aws.graphite", "MYAPP.prod", 10) };
private ColorTheme colorTheme = ColorTheme.RED_YELLOW_GREEN;
1
ming-soft/MCMS
src/main/java/net/mingsoft/cms/action/ContentAction.java
[ "public class ContentBean extends ContentEntity {\n\n// /**\n// * 静态化地址\n// */\n// private String staticUrl;\n\n /**\n * 开始时间\n */\n private String beginTime;\n\n /**\n * 结束时间\n */\n private String endTime;\n\n /**\n * 属性标记\n */\n private String flag;\n\n /...
import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import net.mingsoft.base.entity.ResultData; import net.mingsoft.basic.annotation.LogAnn; import net.mingsoft.basic.bean.EUListBean; import net.mingsoft.basic.constant.e.BusinessTypeEnum; import net.mingsoft.basic.util.BasicUtil; import net.mingsoft.basic.util.StringUtil; import net.mingsoft.cms.bean.ContentBean; import net.mingsoft.cms.biz.ICategoryBiz; import net.mingsoft.cms.biz.IContentBiz; import net.mingsoft.cms.entity.CategoryEntity; import net.mingsoft.cms.entity.ContentEntity; import net.mingsoft.mdiy.biz.IModelBiz; import net.mingsoft.mdiy.entity.ModelEntity; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
/** * The MIT License (MIT) * Copyright (c) 2012-2022 铭软科技(mingsoft.net) * 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 net.mingsoft.cms.action; /** * 文章管理控制层 * @author 铭飞开发团队 * 创建日期:2019-11-28 15:12:32<br/> * 历史修订:<br/> */ @Api(tags={"后端-内容模块接口"}) @Controller("cmsContentAction") @RequestMapping("/${ms.manager.path}/cms/content") public class ContentAction extends BaseAction { /** * 注入文章业务层 */ @Autowired private IContentBiz contentBiz; @Autowired
private ICategoryBiz categoryBiz;
1
pfstrack/eldamo
src/test/java/xdb/dom/XQueryEngineTest.java
[ "public class ModelConfigManagerTest extends TestCase {\n\n public ModelConfigManagerTest(String testName) {\n super(testName);\n }\n\n public static ModelConfigManager getTestModelConfigManager() {\n init();\n return ModelConfigManager.instance();\n }\n\n public static void init...
import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import junit.framework.TestCase; import net.sf.saxon.dom.NodeOverNodeInfo; import net.sf.saxon.om.NodeInfo; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import xdb.config.ModelConfigManagerTest; import xdb.dom.XQueryEngine; import xdb.dom.XmlParser; import xdb.dom.impl.DocumentImpl; import xdb.util.XmlUtil;
package xdb.dom; public class XQueryEngineTest extends TestCase { public XQueryEngineTest(String testName) { super(testName); } public void testQuery() throws Exception { String xml = "<x><a id='1'>x</a><a id='2'>y</a><a id='3'>z</a></x>"; Document doc = parse(xml); Map<String, String> params = Collections.singletonMap("id", "2"); TestWriter writer = new TestWriter(); XQueryEngine.query(doc, "declare variable $id external; /x/a[@id=$id]", params, writer, "xml"); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<a id=\"2\">y</a>", writer.toString()); } public void testStaticFunctions() throws Exception { String declaration = "declare namespace test=\"java:" + getClass().getName() + "\";"; String xml = "<x><a id='1'>x</a><a id='2'>y</a><a id='3'>z</a></x>"; Document doc = parse(xml); Map<String, String> params = Collections.singletonMap("id", "2"); TestWriter writer = new TestWriter(); XQueryEngine.query(doc, declaration + " test:functionTest('X')", params, writer, "text"); assertEquals("x", writer.toString()); } public static String functionTest(String value) { return value.toLowerCase(); } public void testStaticElementFunctions() throws Exception { String declaration = "declare namespace test=\"java:" + getClass().getName() + "\";"; String xml = "<x test='The Test' />"; Document doc = parse(xml); Map<String, String> params = Collections.singletonMap("id", "2"); TestWriter writer = new TestWriter(); XQueryEngine.query(doc, declaration + " test:elementFunctionTest(/x)", params, writer, "text"); assertEquals("The Test", writer.toString()); } public static String elementFunctionTest(Element element) { if (element instanceof NodeOverNodeInfo) { NodeOverNodeInfo wrapper = (NodeOverNodeInfo) element; element = (Element) wrapper.getUnderlyingNodeInfo(); } return element.getAttribute("test"); } public void testStaticNodeReturnTest() throws Exception { String declaration = "declare namespace test=\"java:" + getClass().getName() + "\";"; String xml = "<x><a/><a/><a/></x>"; Document doc = parse(xml); Map<String, String> params = Collections.singletonMap("id", "2"); TestWriter writer = new TestWriter(); XQueryEngine.query(doc, declaration + " count(test:nodeReturnTest(/x))", params, writer, "text"); assertEquals("3", writer.toString()); } public static List<NodeInfo> nodeReturnTest(Element element) { if (element instanceof NodeOverNodeInfo) { NodeOverNodeInfo wrapper = (NodeOverNodeInfo) element; element = (Element) wrapper.getUnderlyingNodeInfo(); } List<Element> children = XmlUtil.getChildElements(element, "a"); List<NodeInfo> result = new ArrayList<NodeInfo>(children.size()); for (Element child : children) { result.add((NodeInfo) child); } return result; } public void testExternalNamespaceResolver() throws Exception { Document doc = parseFromFile("sample-data.xml"); if (!(doc instanceof DocumentImpl)) { return; } DocumentImpl docImpl = (DocumentImpl) doc;
ModelConfigManagerTest.init();
0
Putnami/putnami-gradle-plugin
src/main/java/fr/putnami/gwt/gradle/task/GwtDevTask.java
[ "public class JavaAction implements Action<Task> {\n\n\tpublic static class ProcessLogger extends Thread {\n\t\tprivate InputStream stream;\n\t\tprivate LogLevel level;\n\t\tprivate boolean quit = false;\n\n\t\tpublic void setStream(InputStream stream) {\n\t\t\tthis.stream = stream;\n\t\t}\n\n\t\tpublic void setLev...
import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.gradle.api.Project; import org.gradle.api.internal.ConventionMapping; import org.gradle.api.internal.IConventionAware; import org.gradle.api.plugins.JavaPlugin; import org.gradle.api.plugins.JavaPluginConvention; import org.gradle.api.plugins.WarPluginConvention; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.TaskAction; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.Semaphore; import fr.putnami.gwt.gradle.action.JavaAction; import fr.putnami.gwt.gradle.action.JavaAction.ProcessLogger; import fr.putnami.gwt.gradle.extension.DevOption; import fr.putnami.gwt.gradle.extension.PutnamiExtension; import fr.putnami.gwt.gradle.helper.CodeServerBuilder; import fr.putnami.gwt.gradle.helper.JettyServerBuilder; import fr.putnami.gwt.gradle.util.ResourceUtils;
/** * This file is part of pwt. * * pwt is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * pwt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with pwt. If not, * see <http://www.gnu.org/licenses/>. */ package fr.putnami.gwt.gradle.task; public class GwtDevTask extends AbstractTask { public static final String NAME = "gwtDev"; private final List<String> modules = Lists.newArrayList(); private File jettyConf; public GwtDevTask() { setDescription("Run DevMode"); dependsOn(JavaPlugin.COMPILE_JAVA_TASK_NAME, JavaPlugin.PROCESS_RESOURCES_TASK_NAME); } @TaskAction public void exec() throws Exception { PutnamiExtension putnami = getProject().getExtensions().getByType(PutnamiExtension.class); DevOption sdmOption = putnami.getDev(); createWarExploded(sdmOption); ResourceUtils.ensureDir(sdmOption.getWar()); ResourceUtils.ensureDir(sdmOption.getWorkDir()); jettyConf = new File(getProject().getBuildDir(), "putnami/conf/jetty-run-conf.xml"); Map<String, String> model = new ImmutableMap.Builder<String, String>() .put("__WAR_FILE__", sdmOption.getWar().getAbsolutePath()) .build(); ResourceUtils.copy("/stub.jetty-conf.xml", jettyConf, model); JavaAction sdm = execSdm(); if (sdm.isAlive()) { JavaAction jetty = execJetty(); jetty.join(); } } private void createWarExploded(DevOption sdmOption) throws IOException { WarPluginConvention warConvention = getProject().getConvention().getPlugin(WarPluginConvention.class); JavaPluginConvention javaConvention = getProject().getConvention().getPlugin(JavaPluginConvention.class); File warDir = sdmOption.getWar(); ResourceUtils.copyDirectory(warConvention.getWebAppDir(), warDir); if (Boolean.TRUE.equals(sdmOption.getNoServer())) { File webInfDir = ResourceUtils.ensureDir(new File(warDir, "WEB-INF")); ResourceUtils.deleteDirectory(webInfDir); } else { SourceSet mainSourceSet = javaConvention.getSourceSets().getByName("main"); File classesDir = ResourceUtils.ensureDir(new File(warDir, "WEB-INF/classes")); for (File file : mainSourceSet.getResources().getSrcDirs()) { ResourceUtils.copyDirectory(file, classesDir); } for (File f: mainSourceSet.getOutput().getClassesDirs()) { ResourceUtils.copyDirectory(f, classesDir); } for (File file : mainSourceSet.getOutput().getFiles()) { if (file.exists() && file.isFile()) { ResourceUtils.copy(file, new File(classesDir, file.getName())); } } File libDir = ResourceUtils.ensureDir(new File(warDir, "WEB-INF/lib")); for (File file : mainSourceSet.getRuntimeClasspath()) { if (file.exists() && file.isFile()) { ResourceUtils.copy(file, new File(libDir, file.getName())); } } } } private JavaAction execJetty() { PutnamiExtension putnami = getProject().getExtensions().getByType(PutnamiExtension.class); JettyServerBuilder jettyBuilder = new JettyServerBuilder(); jettyBuilder.configure(getProject(), putnami.getJetty(), jettyConf); JavaAction jetty = jettyBuilder.buildJavaAction(); jetty.execute(this); return jetty; } private JavaAction execSdm() { PutnamiExtension putnami = getProject().getExtensions().getByType(PutnamiExtension.class); DevOption devOption = putnami.getDev(); if (!Strings.isNullOrEmpty(putnami.getSourceLevel()) && Strings.isNullOrEmpty(devOption.getSourceLevel())) { devOption.setSourceLevel(putnami.getSourceLevel()); } CodeServerBuilder sdmBuilder = new CodeServerBuilder(); if (!putnami.getGwtVersion().startsWith("2.6")) { sdmBuilder.addArg("-launcherDir", devOption.getWar()); } sdmBuilder.configure(getProject(), putnami.getDev(), getModules()); final JavaAction sdmAction = sdmBuilder.buildJavaAction(); final Semaphore lock = new Semaphore(1);
sdmAction.setInfoLogger(new ProcessLogger() {
1
binkley/binkley
yaml-compile/src/main/java/hm/binkley/annotation/processing/y/YModel.java
[ "public final class LoadedTemplate\n extends Loaded<Template> {\n LoadedTemplate(final String path, final Resource whence,\n final Template template) {\n super(path, whence, template);\n }\n\n @Override\n public String where() {\n return where;\n }\n}", "public final...
import hm.binkley.annotation.processing.LoadedTemplate; import hm.binkley.annotation.processing.LoadedYaml; import hm.binkley.annotation.processing.YamlGenerateMesseger; import hm.binkley.util.Listable; import hm.binkley.util.YamlHelper; import org.yaml.snakeyaml.Yaml; import javax.annotation.Nonnull; import javax.lang.model.element.Element; import javax.lang.model.element.Name; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.function.Consumer; import java.util.function.Function; import static java.util.Collections.emptyMap; import static java.util.Collections.unmodifiableList; import static java.util.stream.Collectors.toList; import static org.yaml.snakeyaml.DumperOptions.FlowStyle.FLOW; import static org.yaml.snakeyaml.DumperOptions.ScalarStyle.PLAIN;
package hm.binkley.annotation.processing.y; /** * Represents YAML class/enum definitions immutably and accessible from * FreeMarker. Typical: <pre> * Foo: * .meta: * doc: I am the one and only Foo! * bar: * doc: I am bar * value: 0</pre> * * @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley (binkley)</a> * @todo Documentation */ public final class YModel implements Listable<YType> { // TODO: Some less gross place for this global public static final Map<ZisZuper, List<YMethod>> methods = new LinkedHashMap<>(); private final String generator; @Nonnull
private final Yaml yaml = YamlHelper.builder().build(dumper -> {
4
xpush/lib-xpush-android
sample/src/main/java/io/xpush/sampleChat/fragments/ProfileFragment.java
[ "public class Constants {\n public static final int REQUEST_SIGNUP = 100;\n\n public static final int REQUEST_EDIT_IMAGE = 111;\n public static final int REQUEST_EDIT_NICKNAME = 112;\n public static final int REQUEST_EDIT_STATUS_MESSAGE = 113;\n\n public static final int REQUEST_INVITE_USER = 201;\n\...
import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import org.json.JSONException; import org.json.JSONObject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import io.xpush.chat.common.Constants; import io.xpush.chat.core.CallbackEvent; import io.xpush.chat.core.XPushCore; import io.xpush.chat.models.XPushSession; import io.xpush.sampleChat.R; import io.xpush.sampleChat.activities.EditNickNameActivity; import io.xpush.sampleChat.activities.EditStatusMessageActivity;
package io.xpush.sampleChat.fragments; public class ProfileFragment extends Fragment { private String TAG = ProfileFragment.class.getSimpleName(); private Context mActivity;
private XPushSession mSession;
3
bonigarcia/dualsub
src/test/java/io/github/bonigarcia/dualsub/test/TestSynchronization.java
[ "public class DualSrt {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(DualSrt.class);\n\n\tprivate TreeMap<String, Entry[]> subtitles;\n\n\tprivate int signatureGap;\n\tprivate int signatureTime;\n\tprivate int gap;\n\tprivate int desync;\n\tprivate int extension;\n\tprivate boolean extend;\n\tpriv...
import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.github.bonigarcia.dualsub.srt.DualSrt; import io.github.bonigarcia.dualsub.srt.Merger; import io.github.bonigarcia.dualsub.srt.Srt; import io.github.bonigarcia.dualsub.srt.SrtUtils; import io.github.bonigarcia.dualsub.util.Charset; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.Properties; import org.junit.Assert; import org.junit.Before;
/* * (C) Copyright 2014 Boni Garcia (http://bonigarcia.github.io/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.github.bonigarcia.dualsub.test; /** * TestSynchronization. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.0.0 */ public class TestSynchronization { private static final Logger log = LoggerFactory .getLogger(TestSynchronization.class); private Properties properties; @Before public void setup() throws IOException { properties = new Properties(); InputStream inputStream = Thread.currentThread() .getContextClassLoader() .getResourceAsStream("dualsub.properties"); properties.load(inputStream); } @Test public void testDesynchronization() throws ParseException, IOException { // Initial configuration
SrtUtils.init("624", "Tahoma", 17, true, true, ".", 50, false, null,
3
roscrazy/Android-RealtimeUpdate-CleanArchitecture
mvvm/src/main/java/com/mike/feed/mapper/FeedModelMapper.java
[ "public class Deleted {\n}", "public class Feed {\n private String title;\n private String body;\n private String image;\n private String key;\n private int index;\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title...
import com.mike.feed.domain.Deleted; import com.mike.feed.domain.Feed; import com.mike.feed.domain.FeedChangedInfo; import com.mike.feed.domain.Written; import com.mike.feed.model.DeletedModel; import com.mike.feed.model.FeedChangedInfoModel; import com.mike.feed.model.FeedModel; import com.mike.feed.model.WrittenModel; import javax.inject.Inject; import javax.inject.Singleton;
package com.mike.feed.mapper; /** * Created by MinhNguyen on 8/24/16. */ @Singleton public class FeedModelMapper { @Inject public FeedModelMapper(){ }
public Feed transform(FeedModel entity){
6
shagwood/micro-genie
micro-genie-dw-service/src/main/java/io/microgenie/service/AppConfiguration.java
[ "public abstract class ApplicationFactory implements Closeable{\n\n\tpublic ApplicationFactory(){}\n\n\tpublic abstract EventFactory events();\n\tpublic abstract QueueFactory queues();\n\tpublic abstract FileStoreFactory blobs();\n\tpublic abstract <T extends DatabaseFactory> T database();\n}", "public class ...
import io.dropwizard.Configuration; import io.microgenie.application.ApplicationFactory; import io.microgenie.application.StateChangeConfiguration; import io.microgenie.aws.AwsApplicationFactory; import io.microgenie.aws.config.AwsConfig; import io.microgenie.service.commands.CommandConfiguration; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper;
package io.microgenie.service; /*** * Application Configuration Factory * <p> * This class contains common configuration elements to configure micro-genie service * functionality * @author shawn */ public class AppConfiguration extends Configuration { private static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; private String dateFormat = ISO_8601_DATE_FORMAT; /** default to ISO 8601 UTC date format **/ private ApiConfiguration api; private StateChangeConfiguration stateChanges; private CommandConfiguration commands;
private AwsConfig aws;
3
jrimum/domkee
src/main/java/org/jrimum/domkee/financeiro/banco/febraban/Banco.java
[ "public class NumeroDeTelefone{\r\n\r\n\tprivate int ddi;\r\n\r\n\tprivate int ddd;\r\n\r\n\tprivate int prefixo;\r\n\r\n\tprivate int sufixo;\r\n\t\r\n\tprivate String telefone;\r\n\r\n\tpublic NumeroDeTelefone() {}\r\n\t\r\n\tpublic int getDDI() {\r\n\t\treturn ddi;\r\n\t}\r\n\r\n\tpublic void setDDI(int ddi) {\r...
import java.awt.Image; import java.util.Collection; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.log4j.Logger; import org.jrimum.domkee.comum.pessoa.contato.NumeroDeTelefone; import org.jrimum.domkee.comum.pessoa.endereco.Endereco; import org.jrimum.domkee.comum.pessoa.id.cprf.CNPJ; import org.jrimum.domkee.comum.pessoa.id.cprf.CPRF; import org.jrimum.domkee.financeiro.banco.Pessoa; import org.jrimum.domkee.financeiro.banco.PessoaJuridica; import static org.jrimum.utilix.Objects.isNotNull;
/* * Copyright 2008 JRimum 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. * * Created at: 30/03/2008 - 18:57:43 * * ================================================================================ * * Direitos autorais 2008 JRimum Project * * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que * haja exigência legal ou acordo por escrito, a distribuição de software sob * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a * reger permissões e limitações sob esta LICENÇA. * * Criado em: 30/03/2008 - 18:57:43 * */ package org.jrimum.domkee.financeiro.banco.febraban; /** * * <p> * Um Banco (instituição financeira) supervisionada pelo <a href="http://www.bcb.gov.br/">BACEN</a>. * </p> * * @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a> * * @since 0.2 * * @version 0.2 */ public class Banco implements org.jrimum.domkee.financeiro.banco.Banco { private static Logger log = Logger.getLogger(Banco.class); private CodigoDeCompensacaoBACEN codigoDeCompensacaoBACEN; private String segmento; private Image imgLogo;
private PessoaJuridica pessoaJuridica;
5
1gravity/Android-ContactPicker
library/src/main/java/com/onegravity/contactpicker/core/PagerAdapter.java
[ "public enum ContactDescription {\n PHONE,\n EMAIL,\n ADDRESS;\n\n public static ContactDescription lookup(String name) {\n try {\n return ContactDescription.valueOf(name);\n }\n catch (IllegalArgumentException ignore) {\n Log.e(ContactDescription.class.getSimp...
import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import com.onegravity.contactpicker.contact.ContactDescription; import com.onegravity.contactpicker.contact.ContactFragment; import com.onegravity.contactpicker.contact.ContactSortOrder; import com.onegravity.contactpicker.group.GroupFragment; import com.onegravity.contactpicker.picture.ContactPictureType;
/* * Copyright (C) 2015-2017 Emanuel Moecklin * * 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.onegravity.contactpicker.core; public class PagerAdapter extends FragmentStatePagerAdapter { final private int mNumOfTabs; final private ContactSortOrder mSortOrder; final private ContactPictureType mBadgeType; final private ContactDescription mDescription; final private int mDescriptionType; public PagerAdapter(FragmentManager fm, int numOfTabs, ContactSortOrder sortOrder, ContactPictureType badgeType, ContactDescription description, int descriptionType) { super(fm); mNumOfTabs = numOfTabs; mSortOrder = sortOrder; mBadgeType = badgeType; mDescription = description; mDescriptionType = descriptionType; } @Override public Fragment getItem(int position) { switch (position) { case 0:
return ContactFragment.newInstance(mSortOrder, mBadgeType, mDescription, mDescriptionType);
1
hlavki/g-suite-identity-sync
services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/impl/AccountSyncServiceImpl.java
[ "public interface AppConfiguration {\n\n Optional<String> getExternalAccountsGroup();\n\n\n void setExternalAccountsGroup(String groupName);\n}", "public interface GSuiteDirectoryService {\n\n /**\n * Retrieve all groups for a member.\n *\n * @param userKey The userKey can be the user's prima...
import eu.hlavki.identity.services.config.AppConfiguration; import eu.hlavki.identity.services.google.GSuiteDirectoryService; import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.google.model.*; import eu.hlavki.identity.services.ldap.LdapAccountService; import eu.hlavki.identity.services.ldap.model.LdapAccount; import eu.hlavki.identity.services.ldap.model.LdapGroup; import eu.hlavki.identity.services.sync.AccountSyncService; import static eu.hlavki.identity.services.sync.impl.AccountUtil.isInternalAccount; import java.util.*; import static java.util.Collections.emptySet; import java.util.stream.Collectors; import static java.util.stream.Collectors.toSet; import org.apache.cxf.rs.security.oidc.common.UserInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.sync.impl; public class AccountSyncServiceImpl implements AccountSyncService { private static final Logger LOG = LoggerFactory.getLogger(AccountSyncServiceImpl.class); private final LdapAccountService ldapService; private final GSuiteDirectoryService gsuiteDirService; private final AppConfiguration appConfig; public AccountSyncServiceImpl(LdapAccountService ldapService, GSuiteDirectoryService gsuiteDirService, AppConfiguration appConfig) { this.ldapService = ldapService; this.gsuiteDirService = gsuiteDirService; this.appConfig = appConfig; } @Override public void synchronizeUserGroups(UserInfo userInfo) { String accountDN = ldapService.getAccountDN(userInfo.getSubject()); GroupList gsuiteGroups = gsuiteDirService.getUserGroups(userInfo.getSubject()); List<LdapGroup> ldapGroups = ldapService.getAccountGroups(accountDN); Set<String> asIs = ldapGroups.stream() .filter(g -> g.getMembersDn().contains(accountDN)) .map(g -> g.getDn()) .collect(Collectors.toSet()); List<GSuiteGroup> gg = gsuiteGroups.getGroups() != null ? gsuiteGroups.getGroups() : Collections.emptyList(); Set<String> toBe = gg.stream() .map(group -> AccountUtil.getLdapGroupName(group)) .collect(Collectors.toSet()); // Workaround for implicit group mapping boolean implicitGroup = gsuiteDirService.getImplicitGroup() != null; if (isInternalAccount(userInfo, gsuiteDirService.getDomainName()) && implicitGroup) { toBe.add(AccountUtil.getLdapGroupName(gsuiteDirService.getImplicitGroup())); } Set<String> toRemove = new HashSet<>(asIs); toRemove.removeAll(toBe); Set<String> toAdd = new HashSet<>(toBe); toAdd.removeAll(asIs); LOG.info("Remove membership for user {} from groups {}", userInfo.getEmail(), toRemove); LOG.info("Add membership for user {} to groups {}", userInfo.getEmail(), toAdd); for (String group : toRemove) { ldapService.deleteGroupMember(accountDN, group); } for (String group : toAdd) { ldapService.addGroupMember(accountDN, group); } } @Override public void synchronizeAllGroups() { Map<GSuiteGroup, GroupMembership> gsuiteGroups = gsuiteDirService.getAllGroupMembership(); Set<String> ldapGroups = ldapService.getAllGroupNames(); GSuiteUsers allGsuiteUsers = gsuiteDirService.getAllUsers();
Map<String, LdapAccount> emailAccountMap = new HashMap<>();
4
CraftedCart/SMBLevelWorkshop
src/main/java/craftedcart/smblevelworkshop/ui/component/transform/PlaceableScaleTextFields.java
[ "public class Placeable implements Cloneable, ITransformable {\n\n @NotNull private IAsset asset;\n\n @NotNull private PosXYZ position = new PosXYZ();\n @NotNull private PosXYZ rotation = new PosXYZ();\n @NotNull private PosXYZ scale = new PosXYZ(1, 1, 1);\n\n public Placeable(@NotNull IAsset asset) ...
import craftedcart.smblevelworkshop.asset.Placeable; import craftedcart.smblevelworkshop.project.ProjectManager; import craftedcart.smblevelworkshop.resource.LangManager; import craftedcart.smblevelworkshop.ui.MainScreen; import craftedcart.smblevelworkshop.undo.UndoAssetTransform; import craftedcart.smblevelworkshop.util.ITransformable; import io.github.craftedcart.fluidui.component.TextField; import io.github.craftedcart.fluidui.util.UIColor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List;
package craftedcart.smblevelworkshop.ui.component.transform; /** * @author CraftedCart * Created on 30/10/2016 (DD/MM/YYYY) */ public class PlaceableScaleTextFields extends ScaleTextFields { public PlaceableScaleTextFields(@NotNull MainScreen mainScreen, @Nullable TextField nextTextField) { super(mainScreen, nextTextField); } @Nullable @Override protected Double valueConfirmedParseNumber(String value, List<ITransformable> transformablesToPopulate) { double newValue; try { newValue = Double.parseDouble(value); assert ProjectManager.getCurrentClientLevelData() != null; mainScreen.addUndoCommand(new UndoAssetTransform(ProjectManager.getCurrentClientLevelData(), ProjectManager.getCurrentClientLevelData().getSelectedPlaceables())); for (String name : ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()) {
Placeable placeable = ProjectManager.getCurrentLevelData().getPlaceable(name);
0
wxiaoqi/ace-cache
src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
[ "public class RedisConfig {\n private RedisPoolConfig pool = new RedisPoolConfig();\n private String host;\n private String password;\n private String timeout;\n private String database;\n private String port;\n private String enable;\n private String sysName;\n private String userKey;\n ...
import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.ace.cache.config.RedisConfig; import com.ace.cache.parser.IUserKeyGenerator; import com.ace.cache.utils.ReflectionUtils; import com.ace.cache.constants.CacheScope; import com.ace.cache.utils.WebUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ace.cache.parser.IKeyGenerator; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest;
package com.ace.cache.parser.impl; @Service public class DefaultKeyGenerator extends IKeyGenerator { @Autowired RedisConfig redisConfig; @Autowired(required = false)
private IUserKeyGenerator userKeyGenerator;
1
openintents/filemanager
FileManager/src/main/java/org/openintents/filemanager/FileManagerActivity.java
[ "public class BookmarkListActivity extends FragmentActivity {\n public static final String KEY_RESULT_PATH = \"path\";\n private static final String FRAGMENT_TAG = \"Fragment\";\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n UIUtils.setThemeFor(this);\n super.onCrea...
import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; import androidx.annotation.VisibleForTesting; import androidx.appcompat.widget.Toolbar; import org.openintents.distribution.DistributionLibrary; import org.openintents.distribution.DistributionLibraryActivity; import org.openintents.filemanager.bookmarks.BookmarkListActivity; import org.openintents.filemanager.files.FileHolder; import org.openintents.filemanager.lists.SimpleFileListFragment; import org.openintents.filemanager.util.FileUtils; import org.openintents.intents.FileManagerIntents; import org.openintents.util.MenuIntentOptionsWithIcons; import java.io.File;
/* * Copyright (C) 2008 OpenIntents.org * * 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.openintents.filemanager; public class FileManagerActivity extends DistributionLibraryActivity { @VisibleForTesting public static final String FRAGMENT_TAG = "ListFragment"; protected static final int REQUEST_CODE_BOOKMARKS = 1; private SimpleFileListFragment mFragment; @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (intent.getData() != null)
mFragment.openInformingPathBar(new FileHolder(FileUtils.getFile(intent.getData())));
1
thomasjungblut/tjungblut-graph
test/de/jungblut/graph/bsp/SSSPTest.java
[ "public interface Graph<VERTEX_ID, VERTEX_VALUE, EDGE_VALUE> {\n\n /**\n * Adds a vertex with a single adjacent to it.\n */\n void addVertex(Vertex<VERTEX_ID, VERTEX_VALUE> vertex,\n Edge<VERTEX_ID, EDGE_VALUE> adjacent);\n\n /**\n * Adds a vertex with a no adjacents to it.\n ...
import de.jungblut.graph.Graph; import de.jungblut.graph.TestGraphProvider; import de.jungblut.graph.bsp.SSSP.IntIntPairWritable; import de.jungblut.graph.bsp.SSSP.SSSPTextReader; import de.jungblut.graph.bsp.SSSP.ShortestPathVertex; import de.jungblut.graph.model.Edge; import de.jungblut.graph.model.Vertex; import org.apache.hadoop.fs.*; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hama.HamaConfiguration; import org.apache.hama.bsp.HashPartitioner; import org.apache.hama.bsp.TextInputFormat; import org.apache.hama.bsp.TextOutputFormat; import org.apache.hama.graph.GraphJob; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.io.*; import java.util.EnumSet; import java.util.Set;
package de.jungblut.graph.bsp; public final class SSSPTest { @Test @Ignore("BSP partitioning job fails without proper reason") public void testSSSP() throws Exception { // Graph job configuration HamaConfiguration conf = new HamaConfiguration(); conf.set("bsp.local.tasks.maximum", "2"); GraphJob ssspJob = new GraphJob(conf, SSSP.class); // Set the job name ssspJob.setJobName("Single Source Shortest Path"); FileContext fs = FileContext.getFileContext(conf); Path in = new Path(TestHelpers.getTempDir() + "/sssp/input.txt"); createInput(fs, in); Path out = new Path(TestHelpers.getTempDir() + "/sssp/out/"); if (fs.util().exists(out)) { fs.delete(out, true); } conf.set(SSSP.START_VERTEX, "0"); ssspJob.setNumBspTask(2); ssspJob.setInputPath(in); ssspJob.setOutputPath(out); ssspJob.setVertexClass(ShortestPathVertex.class); ssspJob.setInputFormat(TextInputFormat.class); ssspJob.setInputKeyClass(LongWritable.class); ssspJob.setInputValueClass(Text.class); ssspJob.setPartitioner(HashPartitioner.class); ssspJob.setOutputFormat(TextOutputFormat.class); ssspJob.setVertexInputReaderClass(SSSPTextReader.class); ssspJob.setOutputKeyClass(IntWritable.class); ssspJob.setOutputValueClass(IntIntPairWritable.class); // Iterate until all the nodes have been reached. ssspJob.setMaxIteration(Integer.MAX_VALUE); ssspJob.setVertexIDClass(IntWritable.class); ssspJob.setVertexValueClass(IntIntPairWritable.class); ssspJob.setEdgeValueClass(IntWritable.class); long startTime = System.currentTimeMillis(); if (ssspJob.waitForCompletion(true)) { System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); verifyOutput(fs, out); } } private void createInput(FileContext fs, Path in) throws IOException { if (fs.util().exists(in)) { fs.delete(in, true); } else { fs.mkdir(in.getParent(), FsPermission.getDefault(), true); } try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( fs.create(in, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE))))) { Graph<Integer, String, Integer> wikipediaExampleGraph = TestGraphProvider .getWikipediaExampleGraph(); for (Vertex<Integer, String> v : wikipediaExampleGraph.getVertexSet()) {
Set<Edge<Integer, Integer>> adjacentVertices = wikipediaExampleGraph
5
hnakagawa/proton
Proton/src/instrumentTest/java/proton/inject/state/StateRecoveryTest.java
[ "public class DefaultModule extends AbstractModule {\n @SuppressWarnings(\"rawtypes\")\n private static final Class mAccountManagerClass = loadClass(\"android.accounts.AccountManager\");\n\n private static Class<?> loadClass(String className) {\n try {\n return Class.forName(className);\n...
import java.util.ArrayList; import proton.inject.DefaultModule; import proton.inject.Injector; import proton.inject.MockContext; import proton.inject.Proton; import proton.inject.observer.ObserverManager; import proton.inject.observer.event.OnCreateEvent; import proton.inject.observer.event.OnDestroyEvent; import proton.inject.observer.event.OnSaveInstanceStateEvent; import android.app.Application; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.test.AndroidTestCase; import android.test.mock.MockApplication;
package proton.inject.state; public class StateRecoveryTest extends AndroidTestCase { private Application mMockApplication; private Injector mInjector; private ObserverManager mObserverManager; @SuppressWarnings("unused") private StateEventObserver mStateEventObserver; @Override protected void setUp() throws Exception { super.setUp(); mMockApplication = new MockApplication(); Proton.initialize(mMockApplication, new DefaultModule() { @Override protected void configure() { super.configure(); bind(Aaa.class); } }); mInjector = Proton.getInjector(new MockContext(mMockApplication)); mObserverManager = mInjector.getInstance(ObserverManager.class); mStateEventObserver = mInjector.getInstance(StateEventObserver.class); } @Override protected void tearDown() throws Exception { Proton.destroy(); super.tearDown(); } public void testRecovery() {
mObserverManager.fire(new OnCreateEvent(null));
4
Kestutis-Z/World-Weather
WorldWeather/app/src/main/java/com/haringeymobile/ukweather/database/GeneralDatabaseService.java
[ "public class CityManagementActivity extends ThemedActivity implements\n CityListFragmentWithUtilityButtons.OnUtilityButtonClickedListener,\n CityUtilitiesCursorAdapter.Listener,\n DeleteCityDialog.OnDialogButtonClickedListener {\n\n public static final String CITY_ID = \"city id\";\n pub...
import android.app.IntentService; import android.content.Intent; import com.haringeymobile.ukweather.CityManagementActivity; import com.haringeymobile.ukweather.MainActivity; import com.haringeymobile.ukweather.RefreshingActivity; import com.haringeymobile.ukweather.utils.SharedPrefsHelper; import com.haringeymobile.ukweather.weather.WeatherInfoType;
package com.haringeymobile.ukweather.database; public class GeneralDatabaseService extends IntentService { private static final String APP_PACKAGE = "com.haringeymobile.ukweather"; public static final String ACTION_INSERT_OR_UPDATE_CITY_RECORD = APP_PACKAGE + ".insert_or_update_city_records"; public static final String ACTION_UPDATE_WEATHER_INFO = APP_PACKAGE + ".update_weather_info_records"; public static final String ACTION_RENAME_CITY = APP_PACKAGE + ".rename_city"; public static final String ACTION_DELETE_CITY_RECORDS = APP_PACKAGE + ".delete_city_records"; public static final String ACTION_DRAG_CITY = APP_PACKAGE + ".drag_city"; private static final String WORKER_THREAD_NAME = "General database service thread"; public GeneralDatabaseService() { super(WORKER_THREAD_NAME); } @Override protected void onHandleIntent(Intent intent) { String action = intent.getAction(); switch (action) { case ACTION_INSERT_OR_UPDATE_CITY_RECORD: { int cityId = intent.getIntExtra(MainActivity.CITY_ID, CityTable. CITY_ID_DOES_NOT_EXIST); String cityName = intent.getStringExtra(MainActivity.CITY_NAME); String currentWeatherJsonString = intent.getStringExtra(RefreshingActivity. WEATHER_INFO_JSON_STRING); new SqlOperation(this, WeatherInfoType.CURRENT_WEATHER). updateOrInsertCityWithCurrentWeather(cityId, cityName, currentWeatherJsonString); break; } case ACTION_UPDATE_WEATHER_INFO: {
int cityId = SharedPrefsHelper.getCityIdFromSharedPrefs(this);
3
quaap/LaunchTime
app/src/main/java/com/quaap/launchtime/db/DB.java
[ "public class AppLauncher implements Comparable<AppLauncher> {\n\n\n private static final Map<ComponentName,AppLauncher> mAppLaunchers = Collections.synchronizedMap(new HashMap<ComponentName,AppLauncher>());\n private static final String LINK_SEP = \":IS_APP_LINK:\";\n public static final String ACTION_PAC...
import android.annotation.SuppressLint; import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import android.preference.PreferenceManager; import android.util.Log; import android.view.ViewGroup; import com.quaap.launchtime.R; import com.quaap.launchtime.apps.AppLauncher; import com.quaap.launchtime.components.Categories; import com.quaap.launchtime.components.FsTools; import com.quaap.launchtime.components.SpecialIconStore; import com.quaap.launchtime.components.Theme; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern;
} private static String buildIndexStmt(String tablename, String col) { return "CREATE INDEX " + ((col + tablename).replaceAll("\\W+", "_")) + " on " + tablename + "(" + col + ");"; } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { firstRun = true; Log.i("db", "create database"); sqLiteDatabase.execSQL(APP_TABLE_CREATE); for (String createind : appcolumnsindex) { sqLiteDatabase.execSQL(buildIndexStmt(APP_TABLE, createind)); } sqLiteDatabase.execSQL(APP_ORDER_TABLE_CREATE); for (String createind : appordercolumnsindex) { sqLiteDatabase.execSQL(buildIndexStmt(APP_ORDER_TABLE, createind)); } sqLiteDatabase.execSQL(CATEGORIES_TABLE_CREATE); for (String createind : categoriescolumnsindex) { sqLiteDatabase.execSQL(buildIndexStmt(CATEGORIES_TABLE, createind)); } sqLiteDatabase.execSQL(APP_HISTORY_TABLE_CREATE); for (String createind : apphistorycolumnsindex) { sqLiteDatabase.execSQL(buildIndexStmt(APP_HISTORY_TABLE, createind)); } buildCatTable(sqLiteDatabase); } private void buildCatTable(SQLiteDatabase sqLiteDatabase) { Log.i("db", "creating category table"); sqLiteDatabase.execSQL("drop table if exists " + APP_CAT_MAP_TABLE); sqLiteDatabase.execSQL(APP_CAT_MAP_TABLE_CREATE); for (String createind : appcatmapcolumnsindex) { sqLiteDatabase.execSQL(buildIndexStmt(APP_CAT_MAP_TABLE, createind)); } loadCategories(sqLiteDatabase, true, R.raw.submitted_activities,1); loadCategories(sqLiteDatabase, false, R.raw.submitted_packages, 2); loadCategories(sqLiteDatabase, false, R.raw.packages1,3); loadCategories(sqLiteDatabase, false, R.raw.packages2,4); } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { Log.i("db", "upgrade database"); if (oldVersion==1) { sqLiteDatabase.execSQL("alter table " + APP_TABLE_OLD + " add column " + ISUNINSTALLED + " SHORT"); //sqLiteDatabase.execSQL(buildIndexStmt(APP_TABLE_OLD, ISUNINSTALLED)); ContentValues values = new ContentValues(); values.put(ISUNINSTALLED, 0); sqLiteDatabase.update(APP_TABLE_OLD, values, null, null); } if (oldVersion<=2) { upgradeTo2(sqLiteDatabase); } if (oldVersion<6) { sqLiteDatabase.execSQL("alter table " + APP_TABLE + " add column " + CUSTOMLABEL + " TEXT"); } if (oldVersion<10) { ContentValues values = new ContentValues(); values.put(INDEX, 101); sqLiteDatabase.update(CATEGORIES_TABLE, values, CATID + "=?", new String[]{Categories.CAT_SEARCH}); } if (oldVersion<11) { buildCatTable(sqLiteDatabase); } sqLiteDatabase.delete(APP_ORDER_TABLE, PKGNAME + " is null", null); } public boolean isFirstRun() { return firstRun; } public List<ComponentName> getAppNames() { List<ComponentName> actvnames = new ArrayList<>(); SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(APP_TABLE, new String[]{ACTVNAME, PKGNAME}, ISUNINSTALLED+"=0", null, null, null, LABEL); try { while (cursor.moveToNext()) { String actv = cursor.getString(cursor.getColumnIndex(ACTVNAME)); String pkg = cursor.getString(cursor.getColumnIndex(PKGNAME)); try { ComponentName cn = new ComponentName(pkg, actv); actvnames.add(cn); } catch (Exception e) { Log.e("LaunchDB", e.getMessage(), e); } } } finally { cursor.close(); } return actvnames; }
public AppLauncher getApp(ComponentName appname) {
0
CreativeMD/EnhancedVisuals
src/main/java/team/creative/enhancedvisuals/common/event/EVEvents.java
[ "@Mod(modid = EnhancedVisuals.MODID, name = EnhancedVisuals.NAME, version = EnhancedVisuals.VERSION, acceptedMinecraftVersions = \"\", dependencies = \"required-after:creativecore\", guiFactory = \"team.creative.enhancedvisuals.client.EVSettings\")\npublic class EnhancedVisuals {\n\t\n\tpublic static final String M...
import java.lang.reflect.Field; import java.util.List; import com.creativemd.creativecore.common.packet.PacketHandler; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.projectile.EntityPotion; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.Explosion; import net.minecraftforge.event.entity.ProjectileImpactEvent; import net.minecraftforge.event.entity.living.LivingDamageEvent; import net.minecraftforge.event.world.ExplosionEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; import net.minecraftforge.fml.relauncher.ReflectionHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import team.creative.enhancedvisuals.EnhancedVisuals; import team.creative.enhancedvisuals.client.EVClient; import team.creative.enhancedvisuals.client.VisualManager; import team.creative.enhancedvisuals.client.sound.SoundMuteHandler; import team.creative.enhancedvisuals.common.packet.DamagePacket; import team.creative.enhancedvisuals.common.packet.ExplosionPacket; import team.creative.enhancedvisuals.common.packet.PotionPacket;
package team.creative.enhancedvisuals.common.event; public class EVEvents { private Field size = ReflectionHelper.findField(Explosion.class, new String[] { "field_77280_f", "size" }); private Field exploder = ReflectionHelper.findField(Explosion.class, new String[] { "field_77283_e", "exploder" }); @SubscribeEvent public void explosion(ExplosionEvent.Detonate event) { if (event.getWorld() != null && !event.getWorld().isRemote) { try { int sourceEntity = -1; Entity source = ((Entity) exploder.get(event.getExplosion())); if (source != null) sourceEntity = source.getEntityId();
ExplosionPacket packet = new ExplosionPacket(event.getExplosion().getPosition(), size.getFloat(event.getExplosion()), sourceEntity);
5
krazykira/VidEffects
videffects/src/main/java/com/sherazkhilji/videffects/view/VideoSurfaceView.java
[ "public class NoEffect implements ShaderInterface {\r\n\r\n @Override\r\n public String getShader(GLSurfaceView mGlSurfaceView) {\r\n return \"#extension GL_OES_EGL_image_external : require\\n\"\r\n + \"precision mediump float;\\n\"\r\n + \"varying vec2 vTextureCoord;\\n\"...
import android.annotation.SuppressLint; import android.content.Context; import android.graphics.SurfaceTexture; import android.media.MediaPlayer; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.Matrix; import android.util.AttributeSet; import android.util.Log; import android.view.Surface; import com.sherazkhilji.videffects.NoEffect; import com.sherazkhilji.videffects.filter.NoEffectFilter; import com.sherazkhilji.videffects.interfaces.Filter; import com.sherazkhilji.videffects.interfaces.ShaderInterface; import com.sherazkhilji.videffects.model.BaseRenderer; import com.sherazkhilji.videffects.model.Utils; import java.io.IOException; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import static com.sherazkhilji.videffects.Constants.DEFAULT_VERTEX_SHADER;
* @param shaderEffect any effect that implements {@link ShaderInterface} */ @Deprecated public void setShader(ShaderInterface shaderEffect) { this.filter = null; effect = shaderEffect != null ? shaderEffect : new NoEffect(); } public void setFilter(Filter filter) { this.effect = null; this.filter = filter != null ? filter : new NoEffectFilter(); } public ShaderInterface getShader() { return effect; } public Filter getFilter() { return filter; } @Override public void onResume() { if (mMediaPlayer == null) { Log.e(TAG, "Call init() before Continuing"); return; } super.onResume(); } @Override public void onPause() { super.onPause(); mMediaPlayer.pause(); } private class VideoRender extends BaseRenderer implements Renderer, SurfaceTexture.OnFrameAvailableListener { private SurfaceTexture mSurface; private boolean updateSurface = false; private boolean isMediaPlayerPrepared = false; VideoRender() { Matrix.setIdentityM(getTransformMatrix(), 0); } @Override public void onSurfaceCreated(GL10 glUnused, EGLConfig config) { super.init(); /* * Create the SurfaceTexture that will feed this textureID, and pass * it to the MediaPlayer */ mSurface = new SurfaceTexture(getTexture()); mSurface.setOnFrameAvailableListener(this); Surface surface = new Surface(mSurface); mMediaPlayer.setSurface(surface); mMediaPlayer.setScreenOnWhilePlaying(true); surface.release(); if (!isMediaPlayerPrepared) { try { mMediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); } isMediaPlayerPrepared = true; } synchronized (this) { updateSurface = false; } mMediaPlayer.start(); } @Override public void onSurfaceChanged(GL10 glUnused, int width, int height) { } @Override synchronized public void onFrameAvailable(SurfaceTexture surface) { updateSurface = true; } @Override public void onDrawFrame(GL10 glUnused) { synchronized (this) { if (updateSurface) { mSurface.updateTexImage(); mSurface.getTransformMatrix(getTransformMatrix()); updateSurface = false; } } GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f); GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT); draw(); } @Override protected void draw() { super.draw(); GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_INT, 0); GLES20.glFinish(); } @Override protected int getVertexShader() { String vertexShaderString; if (effect != null) { vertexShaderString = DEFAULT_VERTEX_SHADER; } else if (filter != null) { vertexShaderString = filter.getVertexShader(); } else { throw new IllegalStateException("Effect is not applied"); }
return Utils.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderString);
5
spinnaker/fiat
fiat-web/src/main/java/com/netflix/spinnaker/fiat/controllers/RolesController.java
[ "@Data\npublic class UserPermission {\n private String id;\n\n private Set<Account> accounts = new LinkedHashSet<>();\n private Set<Application> applications = new LinkedHashSet<>();\n private Set<ServiceAccount> serviceAccounts = new LinkedHashSet<>();\n private Set<Role> roles = new LinkedHashSet<>();\n pri...
import com.netflix.spinnaker.fiat.model.UserPermission; import com.netflix.spinnaker.fiat.model.resources.Role; import com.netflix.spinnaker.fiat.permissions.ExternalUser; import com.netflix.spinnaker.fiat.permissions.PermissionResolutionException; import com.netflix.spinnaker.fiat.permissions.PermissionsRepository; import com.netflix.spinnaker.fiat.permissions.PermissionsResolver; import com.netflix.spinnaker.fiat.roles.UserRolesSyncer; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;
/* * Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.controllers; @Slf4j @RestController @RequestMapping("/roles") @ConditionalOnExpression("${fiat.write-mode.enabled:true}") public class RolesController { @Autowired @Setter PermissionsResolver permissionsResolver; @Autowired @Setter PermissionsRepository permissionsRepository; @Autowired @Setter UserRolesSyncer syncer; @RequestMapping(value = "/{userId:.+}", method = RequestMethod.POST) public void putUserPermission(@PathVariable String userId) { try { UserPermission userPermission = permissionsResolver.resolve(ControllerSupport.convert(userId)); log.debug( "Updated user permissions (userId: {}, roles: {})", userId, userPermission.getRoles().stream().map(Role::getName).collect(Collectors.toList())); permissionsRepository.put(userPermission); } catch (PermissionResolutionException pre) { throw new UserPermissionModificationException(pre); } } @RequestMapping(value = "/{userId:.+}", method = RequestMethod.PUT) public void putUserPermission( @PathVariable String userId, @RequestBody @NonNull List<String> externalRoles) { List<Role> convertedRoles = externalRoles.stream() .map(extRole -> new Role().setSource(Role.Source.EXTERNAL).setName(extRole)) .collect(Collectors.toList());
ExternalUser extUser =
2
374901588/PaperPlane
app/src/main/java/com/hut/zero/homepage/DoubanMomentPresenter.java
[ "public enum BeanType {\n\n TYPE_ZHIHU, TYPE_GUOKE,TYPE_DOUBAN;\n\n}", "public class DoubanCache extends DataSupport {\n private int douban_id;\n private String douban_news;\n private float douban_time;\n private String douban_content;\n private boolean bookmark=false;\n\n public int getDouba...
import android.content.Context; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.hut.zero.bean.BeanType; import com.hut.zero.bean.DoubanCache; import com.hut.zero.bean.DoubanMomentNews; import com.hut.zero.detail.DetailActivity; import com.hut.zero.model.DoubanModelImpl; import com.hut.zero.service.CacheService; import com.hut.zero.util.DateFormatter; import com.hut.zero.util.NetworkState; import org.litepal.crud.DataSupport; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Random; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response;
package com.hut.zero.homepage; /** * Created by Zero on 2017/4/2. */ public class DoubanMomentPresenter implements DoubanMomentContract.Presenter { private Context mContext; private DoubanMomentContract.View mView; private Gson gson=new Gson();
private DoubanModelImpl model;
4
aolshevskiy/songo
src/main/java/songo/MainModule.java
[ "public class LoggingTypeListener implements TypeListener {\n\t@Override\n\tpublic <I> void hear(TypeLiteral<I> aTypeLiteral, TypeEncounter<I> aTypeEncounter) {\n\t\tfor(Field field : aTypeLiteral.getRawType().getDeclaredFields()) {\n\t\t\tif(field.getType() == Logger.class && field.isAnnotationPresent(InjectLogger...
import com.google.common.eventbus.EventBus; import com.google.inject.*; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.matcher.Matchers; import com.google.inject.servlet.SessionScoped; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig; import com.sun.jna.Native; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabItem; import songo.annotation.*; import songo.logging.LoggingTypeListener; import songo.model.Configuration; import songo.model.Playlist; import songo.model.streams.*; import songo.mpg123.Mpg123Native; import songo.view.MainView; import songo.vk.*; import javax.annotation.Nullable; import java.io.File; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package songo; public class MainModule extends AbstractModule { private static int getNativeBrowserStyle() { if(System.getProperty("os.name").equals("Linux")) return SWT.WEBKIT; return SWT.NONE; } private static boolean isRunningWindows() { return System.getProperty("os.name").toLowerCase().contains("windows"); } @Override protected void configure() { bind(Boolean.class).annotatedWith(RunningWindows.class).toInstance(isRunningWindows()); SimpleScope sessionScope = new SimpleScope(); bindScope(SessionScoped.class, sessionScope); bind(SimpleScope.class).annotatedWith(SessionScope.class).toInstance(sessionScope); bind(EventBus.class).annotatedWith(GlobalBus.class).to(EventBus.class).in(Singleton.class); bind(EventBus.class).annotatedWith(SessionBus.class).to(EventBus.class).in(SessionScoped.class); bind(String.class).annotatedWith(VkAppId.class).toInstance("3192319"); bind(String.class).annotatedWith(VkRegisterUrl.class).toInstance("http://vk.com/join"); bind(Integer.class).annotatedWith(BrowserStyle.class).toInstance(getNativeBrowserStyle()); bind(Stream.class).toProvider(StreamProvider.class); install( new FactoryModuleBuilder() .implement(RemoteStream.class, RemoteStream.class) .implement(LocalStream.class, LocalStream.class) .build(StreamFactory.class)); bindListener(Matchers.any(), new LoggingTypeListener()); } @Provides @VkAuthUrl @Singleton String provideAuthUrl(@VkAppId String appId) { return "https://oauth.vk.com/authorize?client_id=" + appId + "&scope=audio,offline&redirect_url=http://oauth.vk.com/blank.html&display=popup&response_type=token"; } @Provides Display provideDisplay(SongoService service) { return service.getDisplay(); } @Provides Shell provideShell(Display display) { return new Shell(display); } @Provides @VkAccessToken
String provideAccessToken(Configuration configuration) {
1
EndlessCodeGroup/RPGInventory
src/main/java/ru/endlesscode/rpginventory/inventory/craft/CraftManager.java
[ "public class RPGInventory extends PluginLifecycle {\n private static RPGInventory instance;\n\n private Permission perms;\n private Economy economy;\n\n private BukkitLevelSystem.Provider levelSystemProvider;\n private BukkitClassSystem.Provider classSystemProvider;\n\n private FileLanguage langu...
import ru.endlesscode.rpginventory.item.Texture; import ru.endlesscode.rpginventory.misc.config.Config; import ru.endlesscode.rpginventory.utils.Log; import java.util.ArrayList; import java.util.List; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.events.PacketAdapter; import com.comphenix.protocol.events.PacketEvent; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemorySection; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import ru.endlesscode.rpginventory.RPGInventory; import ru.endlesscode.rpginventory.compat.VersionHandler; import ru.endlesscode.rpginventory.event.listener.CraftListener;
/* * This file is part of RPGInventory. * Copyright (C) 2015-2017 Osip Fatkullin * * RPGInventory is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RPGInventory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with RPGInventory. If not, see <http://www.gnu.org/licenses/>. */ package ru.endlesscode.rpginventory.inventory.craft; /** * Created by OsipXD on 29.08.2016 * It is part of the RpgInventory. * All rights reserved 2014 - 2016 © «EndlessCode Group» */ public class CraftManager { @NotNull private static final List<CraftExtension> EXTENSIONS = new ArrayList<>(); private static Texture textureOfExtendable; private CraftManager() { } public static boolean init(@NotNull RPGInventory instance) { MemorySection config = (MemorySection) Config.getConfig().get("craft"); if (config == null) { Log.w("Section ''craft'' not found in config.yml"); return false; } if (!config.getBoolean("enabled")) { Log.i("Craft system is disabled in config"); return false; } try { Texture texture = Texture.parseTexture(config.getString("extendable")); if (texture.isEmpty()) { Log.s("Invalid texture in ''craft.extendable''"); return false; } textureOfExtendable = texture; @Nullable final ConfigurationSection extensions = config.getConfigurationSection("extensions"); if (extensions == null) { Log.s("Section ''craft.extensions'' not found in config.yml"); return false; } EXTENSIONS.clear(); for (String extensionName : extensions.getKeys(false)) { EXTENSIONS.add(new CraftExtension(extensionName, extensions.getConfigurationSection(extensionName))); } // Register listeners
ProtocolLibrary.getProtocolManager().addPacketListener(new CraftListener(instance));
2
suninformation/ymate-payment-v2
ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/impl/DefaultModuleCfg.java
[ "public interface IWxPay {\n\n String MODULE_NAME = \"payment.wxpay\";\n\n /**\n * @return 返回所属YMP框架管理器实例\n */\n YMP getOwner();\n\n /**\n * @return 返回模块配置对象\n */\n IWxPayModuleCfg getModuleCfg();\n\n /**\n * @return 返回模块是否已初始化\n */\n boolean isInited();\n\n /**\n ...
import net.ymate.payment.wxpay.IWxPay; import net.ymate.payment.wxpay.IWxPayAccountProvider; import net.ymate.payment.wxpay.IWxPayEventHandler; import net.ymate.payment.wxpay.IWxPayModuleCfg; import net.ymate.payment.wxpay.base.WxPayAccountMeta; import net.ymate.platform.core.YMP; import net.ymate.platform.core.lang.BlurObject; import net.ymate.platform.core.util.ClassUtils; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.lang.StringUtils; import java.util.Map;
/* * Copyright 2007-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.payment.wxpay.impl; /** * @author 刘镇 (suninformation@163.com) on 2017/06/15 下午 13:12 * @version 1.0 */ public class DefaultModuleCfg implements IWxPayModuleCfg { private IWxPayAccountProvider __accountProvider; private IWxPayEventHandler __eventHandler; private String __defaultAccountId; private String __jsApiView; private String __nativeView; private boolean __signCheckDisabled; public DefaultModuleCfg(YMP owner) { Map<String, String> _moduleCfgs = owner.getConfig().getModuleConfigs(IWxPay.MODULE_NAME); // __accountProvider = ClassUtils.impl(_moduleCfgs.get("account_provider_class"), IWxPayAccountProvider.class, getClass()); if (__accountProvider == null) { __accountProvider = new DefaultWxPayAccountProvider(); //
WxPayAccountMeta _meta = new WxPayAccountMeta(_moduleCfgs.get("app_id"),
4
shekhargulati/rx-docker-client
rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/DefaultRxDockerClient.java
[ "public abstract class Dates {\n public static final String DOCKER_DATE_TIME_FORMAT = \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\";\n}", "public abstract class StreamUtils {\n\n public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) {\n return StreamSupport.stream(Spliterators.spliteratorUnknownSize(...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.shekhargulati.reactivex.docker.client.representations.*; import com.shekhargulati.reactivex.docker.client.utils.Dates; import com.shekhargulati.reactivex.docker.client.utils.StreamUtils; import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.rxokhttp.*; import com.shekhargulati.reactivex.rxokhttp.functions.*; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE; import static com.shekhargulati.reactivex.docker.client.utils.StreamUtils.iteratorToStream; import static com.shekhargulati.reactivex.docker.client.utils.Validations.validate; import static com.shekhargulati.reactivex.rxokhttp.ClientConfig.defaultConfig; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap;
/* * The MIT License * * Copyright 2015 Shekhar Gulati <shekhargulati84@gmail.com>. * * 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 com.shekhargulati.reactivex.docker.client; class DefaultRxDockerClient implements RxDockerClient { private static final String EMPTY_BODY = ""; private final Logger logger = LoggerFactory.getLogger(DefaultRxDockerClient.class); private final String apiUri; private final RxHttpClient httpClient; private final Gson gson = new GsonBuilder() .setFieldNamingPolicy(UPPER_CAMEL_CASE)
.setDateFormat(Dates.DOCKER_DATE_TIME_FORMAT)
0
xcurator/xcurator
src/edu/toronto/cs/xcurator/discoverer/HashBasedEntityInterlinking.java
[ "public class RdfUriBuilder {\n\n private final String typeUriBase;\n private final String propertyUriBase;\n\n private final String typePrefix;\n private final String propertyPrefix;\n\n public RdfUriBuilder(RdfUriConfig config) {\n this.typeUriBase = config.getTypeResourceUriBase();\n ...
import edu.toronto.cs.xcurator.common.DataDocument; import edu.toronto.cs.xcurator.common.RdfUriBuilder; import edu.toronto.cs.xcurator.mapping.Attribute; import edu.toronto.cs.xcurator.mapping.Schema; import edu.toronto.cs.xcurator.mapping.Mapping; import edu.toronto.cs.xcurator.mapping.Reference; import edu.toronto.cs.xcurator.mapping.Relation; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set;
/* * Copyright (c) 2013, University of Toronto. * * 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 edu.toronto.cs.xcurator.discoverer; /** * * @author ekzhu */ public class HashBasedEntityInterlinking implements MappingDiscoveryStep { private final RdfUriBuilder rdfUriBuilder; public HashBasedEntityInterlinking(RdfUriBuilder rdfUriBuilder) { this.rdfUriBuilder = rdfUriBuilder; } @Override
public void process(List<DataDocument> dataDocuments, Mapping mapping) {
3
dariober/ASCIIGenome
src/test/java/samTextViewer/GenomicCoordsTest.java
[ "public class Config {\n\t\n\t// C O N S T R U C T O R \n\t\n\tprivate static final Map<ConfigKey, String> config= new HashMap<ConfigKey, String>();\n\n\tpublic Config(String source) throws IOException, InvalidConfigException {\n\t\t\n\t\tnew Xterm256();\n\t\t\n\t\tString RawConfigFile= Config.getConfigFileAsString...
import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import coloring.Config; import exceptions.InvalidColourException; import exceptions.InvalidCommandLineException; import exceptions.InvalidConfigException; import exceptions.InvalidGenomicCoordsException; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.samtools.SAMSequenceRecord; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory;
package samTextViewer; public class GenomicCoordsTest { static SamReaderFactory srf=SamReaderFactory.make(); static SamReader samReader= srf.open(new File("test_data/ds051.short.bam")); public static SAMSequenceDictionary samSeqDict= samReader.getFileHeader().getSequenceDictionary(); public static String fastaFile= "test_data/chr7.fa"; @Before public void initConfig() throws IOException, InvalidConfigException{
new Config(null);
0
pedrovgs/Nox
nox/src/main/java/com/github/pedrovgs/nox/NoxView.java
[ "public interface ImageLoader {\n\n /**\n * Configures an url to be downloaded.\n */\n ImageLoader load(String url);\n\n /**\n * Configures a resource id to be loaded.\n */\n ImageLoader load(Integer resourceId);\n\n /**\n * Loads a placeholder using a resource id to be shown while the external resou...
import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v4.view.GestureDetectorCompat; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import com.github.pedrovgs.nox.imageloader.ImageLoader; import com.github.pedrovgs.nox.imageloader.ImageLoaderFactory; import com.github.pedrovgs.nox.shape.Shape; import com.github.pedrovgs.nox.shape.ShapeConfig; import com.github.pedrovgs.nox.shape.ShapeFactory; import java.util.List; import java.util.Observable; import java.util.Observer;
/* * Copyright (C) 2015 Pedro Vicente Gomez Sanchez. * * 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.github.pedrovgs.nox; /** * Main library component. This custom view receives a List of Nox objects and creates a awesome * panel full of images following different shapes. This new UI component is going to be similar to * the Apple's watch main menu user interface. * * NoxItem objects are going to be used to render the user interface using the resource used * to render inside each element and a view holder. * * @author Pedro Vicente Gomez Sanchez. */ public class NoxView extends View { private NoxConfig noxConfig;
private Shape shape;
2
chipKIT32/chipKIT-importer
src/com/microchip/mplab/nbide/embedded/arduino/wizard/ProjectSetupStep.java
[ "public abstract class ArduinoConfig {\n \n \n public static final String ROOT_PLATFORM_VENDOR = \"arduino\";\n public static final String ROOT_PLATFORM_ARCH = \"avr\";\n \n private static final Logger LOGGER = Logger.getLogger(ArduinoConfig.class.getName());\n private static ArduinoConfig INST...
import com.microchip.crownking.opt.Version; import com.microchip.mplab.mdbcore.MessageMediator.ActionList; import com.microchip.mplab.mdbcore.MessageMediator.DialogBoxType; import com.microchip.mplab.mdbcore.MessageMediator.Message; import com.microchip.mplab.mdbcore.MessageMediator.MessageMediator; import com.microchip.mplab.nbide.embedded.api.ui.TypeAheadComboBox; import com.microchip.mplab.nbide.embedded.arduino.importer.ArduinoConfig; import com.microchip.mplab.nbide.embedded.arduino.importer.Platform; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.swing.JFileChooser; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectManager; import org.netbeans.spi.project.ui.support.ProjectChooser; import org.openide.WizardDescriptor; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.HelpCtx; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.NbPreferences; import com.microchip.mplab.nbide.embedded.makeproject.ui.wizards.SelectProjectInfoPanel; import javax.swing.JTextField; import static com.microchip.mplab.nbide.embedded.makeproject.api.wizards.WizardProperty.*; import static com.microchip.mplab.nbide.embedded.arduino.wizard.ImportWizardProperty.*; import static com.microchip.mplab.nbide.embedded.arduino.importer.Requirements.MINIMUM_ARDUINO_VERSION; import com.microchip.mplab.nbide.embedded.arduino.importer.Board; import com.microchip.mplab.nbide.embedded.arduino.importer.BoardConfiguration; import com.microchip.mplab.nbide.embedded.arduino.importer.PlatformFactory; import com.microchip.mplab.nbide.embedded.arduino.utils.ArduinoProjectFileFilter; import java.awt.event.FocusEvent; import java.awt.event.ItemEvent; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.filechooser.FileFilter; import org.openide.util.Exceptions;
// Set the error message to null if there is no warning message to display if (wizardDescriptor.getProperty(WizardDescriptor.PROP_WARNING_MESSAGE) == null) { wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, null); } return true; } @Override public final void addChangeListener(ChangeListener l) { synchronized (listeners) { listeners.add(l); } } @Override public final void removeChangeListener(ChangeListener l) { synchronized (listeners) { listeners.remove(l);// NOI18N } } @Override public void readSettings(WizardDescriptor settings) { wizardDescriptor = settings; // Source Project Location File lastSourceProjectLocation = (File) wizardDescriptor.getProperty(SOURCE_PROJECT_DIR.key()); if (lastSourceProjectLocation == null) { String loc = NbPreferences.forModule(SelectProjectInfoPanel.class).get(LAST_SOURCE_PROJECT_LOCATION.key(), null); if (loc == null) { loc = System.getProperty("user.home"); } lastSourceProjectLocation = new File(loc); } view.sourceProjectLocationField.setText(lastSourceProjectLocation.getAbsolutePath()); // Target Project Location File lastTargetProjectLocation = (File) wizardDescriptor.getProperty(PROJECT_LOCATION.key()); if (lastTargetProjectLocation == null) { String loc = NbPreferences.forModule(SelectProjectInfoPanel.class).get(LAST_PROJECT_LOCATION.key(), null); if (loc == null) { loc = System.getProperty("netbeans.projects.dir"); } if (loc == null) { loc = System.getProperty("user.home"); } lastTargetProjectLocation = new File(loc); } view.targetProjectLocationField.setText(lastTargetProjectLocation.getAbsolutePath()); // Platform Location File platformCoreDir = (File) wizardDescriptor.getProperty(ARDUINO_PLATFORM_DIR.key()); if (platformCoreDir == null) { String lastPlatformCoreLocation = NbPreferences.forModule(SelectProjectInfoPanel.class).get(LAST_ARDUINO_PLATFORM_LOCATION.key(), null); if ( lastPlatformCoreLocation != null && Files.exists( Paths.get(lastPlatformCoreLocation) ) ) { platformCoreDir = new File(lastPlatformCoreLocation); } } if (platformCoreDir != null) { view.platformLocationField.setText( platformCoreDir.getAbsolutePath() ); resolvePlatformFromPath(); } // Platform if (currentPlatform == null) { try { List<Platform> allPlatforms = new PlatformFactory().getAllPlatforms( arduinoConfig.getSettingsPath() ); currentPlatform = allPlatforms.stream().filter(p -> p.getVendor().contains("chipKIT") ).findFirst().orElse(null); if ( currentPlatform != null ) { view.platformLocationField.setText( currentPlatform.getRootPath().toString() ); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } } // Target Device: String boardName = (String) wizardDescriptor.getProperty(BOARD_NAME.key()); loadBoardsToCombo(); if (boardName == null) { boardName = NbPreferences.forModule(SelectProjectInfoPanel.class).get(BOARD_NAME.key(), null); } if (boardName != null) { if ( boardIdLookup.containsKey(boardName) ) { view.boardCombo.setSelectedItem(boardName); updateBoard(); } else { boardName = null; } } // Copy all dependencies: Object copyDependencies = wizardDescriptor.getProperty(COPY_CORE_FILES.key()); view.copyDependenciesCheckBox.setSelected( copyDependencies != null ? (boolean) copyDependencies : true); // Target Project Directory: setTargetProjectDirectoryField(); } @Override public void storeSettings(WizardDescriptor settings) { String projectName = readLocationStringFromField( view.projectNameField ); String sourceProjectDir = readLocationStringFromField( view.sourceProjectLocationField ); String platformDir = readLocationStringFromField(view.platformLocationField ); String boardName = readSelectedValueFromComboBox(view.boardCombo); String targetLocation = readLocationStringFromField( view.targetProjectLocationField ); String targetDir = readLocationStringFromField( view.projectDirectoryField ); boolean copyCoreFiles = view.copyDependenciesCheckBox.isSelected(); settings.putProperty(SOURCE_PROJECT_DIR.key(), new File(sourceProjectDir)); settings.putProperty(ARDUINO_DIR.key(), arduinoConfig.findInstallPath().get().toFile() ); settings.putProperty(ARDUINO_PLATFORM.key(), currentPlatform ); settings.putProperty(ARDUINO_PLATFORM_DIR.key(), new File(platformDir)); settings.putProperty(BOARD_NAME.key(), boardName); settings.putProperty(BOARD.key(), board); if ( !board.hasOptions() ) { deviceAssistant.storeSettings(settings);
settings.putProperty(BOARD_CONFIGURATION.key(), new BoardConfiguration(board));
4
richkmeli/Richkware-Manager-Server
src/main/java/it/richkmeli/rms/data/LoadDatabase.java
[ "@Component\npublic class ConfigurationDatabaseManager {\n private static ConfigurationRepository configurationRepository;\n\n @Autowired\n public ConfigurationDatabaseManager(ConfigurationRepository configurationRepository) {\n this.configurationRepository = configurationRepository;\n }\n\n p...
import it.richkmeli.jframework.util.RandomStringGenerator; import it.richkmeli.rms.data.entity.configuration.ConfigurationDatabaseManager; import it.richkmeli.rms.data.entity.configuration.ConfigurationEnum; import it.richkmeli.rms.data.entity.configuration.ConfigurationManager; import it.richkmeli.rms.data.entity.device.DeviceDatabaseSpringManager; import it.richkmeli.rms.data.entity.device.model.Device; import it.richkmeli.rms.data.entity.rmc.RmcDatabaseSpringManager; import it.richkmeli.rms.data.entity.rmc.model.Rmc; import it.richkmeli.rms.data.entity.user.AuthDatabaseSpringManager; import it.richkmeli.rms.data.entity.user.model.User; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
package it.richkmeli.rms.data; // Annotating a class with the @Configuration annotation indicates // that the class will be used by JavaConfig as a source of bean definitions. @Configuration class LoadDatabase { @Bean
CommandLineRunner initDatabase(AuthDatabaseSpringManager authDatabaseSpringManager, DeviceDatabaseSpringManager deviceDatabaseSpringManager, RmcDatabaseSpringManager rmcDatabaseSpringManager, ConfigurationDatabaseManager configurationDatabaseManager) {
5
theblackwidower/KanaQuiz
app/src/main/java/com/noprestige/kanaquiz/options/QuestionSelectionDetail.java
[ "public class KanaQuestion extends Question\n{\n private final String kana;\n private final String defaultRomaji;\n private final Map<RomanizationSystem, String> altRomaji;\n\n KanaQuestion(String kana, String romaji)\n {\n this(kana, romaji, null);\n }\n\n KanaQuestion(String kana, Stri...
import static com.noprestige.kanaquiz.questions.QuestionManagement.SUBPREFERENCE_DELIMITER; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import com.noprestige.kanaquiz.R; import com.noprestige.kanaquiz.questions.KanaQuestion; import com.noprestige.kanaquiz.questions.KanjiQuestion; import com.noprestige.kanaquiz.questions.Question; import com.noprestige.kanaquiz.questions.WordQuestion; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.DialogFragment;
/* * Copyright 2021 T Duke Perry * * 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.noprestige.kanaquiz.options; public class QuestionSelectionDetail extends DialogFragment { private static final String ARG_PREFID = "prefId"; private static final String ARG_QUESTION_NAMES = "questionNames"; private static final String ARG_QUESTION_PREFIDS = "questionPrefIds"; private boolean[] isCheckedSet; private QuestionSelectionItem parent; public static QuestionSelectionDetail newInstance(String prefId, Question[] questions) { Bundle args = new Bundle(); QuestionSelectionDetail dialog = new QuestionSelectionDetail(); args.putString(ARG_PREFID, prefId); String[] questionNames = new String[questions.length]; String[] questionPrefIds = new String[questions.length]; for (int i = 0; i < questions.length; i++) { if (questions[i].getClass().equals(KanaQuestion.class) || questions[i].getClass().equals(KanjiQuestion.class)) questionNames[i] = questions[i].getQuestionText() + " - " + questions[i].fetchCorrectAnswer();
else if (questions[i].getClass().equals(WordQuestion.class))
3
yyxhdy/ManyEAs
src/jmetal/problems/Tanaka.java
[ "public abstract class Problem implements Serializable {\n\n\t/**\n\t * Defines the default precision of binary-coded variables\n\t */\n\tprivate final static int DEFAULT_PRECISSION = 16;\n\n\t/**\n\t * Stores the number of variables of the problem\n\t */\n\tprotected int numberOfVariables_;\n\n\t/**\n\t * Stores t...
import jmetal.core.Problem; import jmetal.core.Solution; import jmetal.core.Variable; import jmetal.encodings.solutionType.BinaryRealSolutionType; import jmetal.encodings.solutionType.RealSolutionType; import jmetal.util.JMException;
// Tanaka.java // // Author: // Antonio J. Nebro <antonio@lcc.uma.es> // Juan J. Durillo <durillo@lcc.uma.es> // // Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package jmetal.problems; /** * Class representing problem Tanaka */ public class Tanaka extends Problem{ /** * Constructor. * Creates a default instance of the problem Tanaka * @param solutionType The solution type must "Real" or "BinaryReal". */ public Tanaka(String solutionType) { numberOfVariables_ = 2; numberOfObjectives_ = 2; numberOfConstraints_= 2; problemName_ = "Tanaka"; upperLimit_ = new double[numberOfVariables_]; lowerLimit_ = new double[numberOfVariables_]; for (int var = 0; var < numberOfVariables_; var++){ lowerLimit_[var] = 10e-5; upperLimit_[var] = Math.PI; } // for if (solutionType.compareTo("BinaryReal") == 0) solutionType_ = new BinaryRealSolutionType(this) ; else if (solutionType.compareTo("Real") == 0) solutionType_ = new RealSolutionType(this) ; else { System.out.println("Error: solution type " + solutionType + " invalid") ; System.exit(-1) ; } } /** * Evaluates a solution * @param solution The solution to evaluate * @throws JMException */
public void evaluate(Solution solution) throws JMException {
1
wolispace/soft-pixel-dungeon
src/com/shatteredpixel/shatteredpixeldungeon/windows/WndBag.java
[ "public class Assets {\n\n\tpublic static final String ARCS_BG\t\t= \"arcs1.png\";\n\tpublic static final String ARCS_FG\t\t= \"arcs2.png\";\n\tpublic static final String DASHBOARD\t= \"dashboard.png\";\n\t\n\tpublic static final String BANNERS\t= \"banners.png\";\n\tpublic static final String BADGES\t= \"badges.pn...
import android.graphics.RectF; import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Belongings; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero; import com.shatteredpixel.shatteredpixeldungeon.items.EquipableItem; import com.shatteredpixel.shatteredpixeldungeon.items.Gold; import com.shatteredpixel.shatteredpixeldungeon.items.Item; import com.shatteredpixel.shatteredpixeldungeon.items.armor.Armor; import com.shatteredpixel.shatteredpixeldungeon.items.bags.Bag; import com.shatteredpixel.shatteredpixeldungeon.items.bags.ScrollHolder; import com.shatteredpixel.shatteredpixeldungeon.items.bags.SeedPouch; import com.shatteredpixel.shatteredpixeldungeon.items.bags.WandHolster; import com.shatteredpixel.shatteredpixeldungeon.items.food.Food; import com.shatteredpixel.shatteredpixeldungeon.items.potions.Potion; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.Scroll; import com.shatteredpixel.shatteredpixeldungeon.items.wands.Wand; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.MeleeWeapon; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.missiles.Boomerang; import com.shatteredpixel.shatteredpixeldungeon.plants.Plant.Seed; import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene; import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet; import com.shatteredpixel.shatteredpixeldungeon.ui.Icons; import com.shatteredpixel.shatteredpixeldungeon.ui.ItemSlot; import com.shatteredpixel.shatteredpixeldungeon.ui.QuickSlotButton; import com.shatteredpixel.shatteredpixeldungeon.utils.Utils; import com.watabou.gltextures.TextureCache; import com.watabou.noosa.BitmapText; import com.watabou.noosa.ColorBlock; import com.watabou.noosa.Image; import com.watabou.noosa.audio.Sample;
icon.y = y + (height - icon.height) / 2 - 2 - (selected ? 0 : 1); if (!selected && icon.y < y + CUT) { RectF frame = icon.frame(); frame.top += (y + CUT - icon.y) / icon.texture.height; icon.frame( frame ); icon.y = y + CUT; } } private Image icon() { if (bag instanceof SeedPouch) { return Icons.get( Icons.SEED_POUCH ); } else if (bag instanceof ScrollHolder) { return Icons.get( Icons.SCROLL_HOLDER ); } else if (bag instanceof WandHolster) { return Icons.get( Icons.WAND_HOLSTER ); } else { return Icons.get( Icons.BACKPACK ); } } } private static class Placeholder extends Item { { name = null; } public Placeholder( int image ) { this.image = image; } @Override public boolean isIdentified() { return true; } @Override public boolean isEquipped( Hero hero ) { return true; } } private class ItemButton extends ItemSlot { private static final int NORMAL = 0xFF4A4D44; private static final int EQUIPPED = 0xFF63665B; private Item item; private ColorBlock bg; public ItemButton( Item item ) { super( item ); this.item = item; if (item instanceof Gold) { bg.visible = false; } width = height = SLOT_SIZE; } @Override protected void createChildren() { bg = new ColorBlock( SLOT_SIZE, SLOT_SIZE, NORMAL ); add( bg ); super.createChildren(); } @Override protected void layout() { bg.x = x; bg.y = y; super.layout(); } @Override public void item( Item item ) { super.item( item ); if (item != null) { bg.texture( TextureCache.createSolid( item.isEquipped( Dungeon.hero ) ? EQUIPPED : NORMAL ) ); if (item.cursed && item.cursedKnown) { bg.ra = +0.2f; bg.ga = -0.1f; } else if (!item.isIdentified()) { bg.ra = 0.1f; bg.ba = 0.1f; } if (item.name() == null) { enable( false ); } else { enable( mode == Mode.FOR_SALE && (item.price() > 0) && (!item.isEquipped( Dungeon.hero ) || !item.cursed) || mode == Mode.UPGRADEABLE && item.isUpgradable() || mode == Mode.UNIDENTIFED && !item.isIdentified() || mode == Mode.QUICKSLOT && (item.defaultAction != null) || mode == Mode.WEAPON && (item instanceof MeleeWeapon || item instanceof Boomerang) || mode == Mode.ARMOR && (item instanceof Armor) || mode == Mode.WAND && (item instanceof Wand) || mode == Mode.SEED && (item instanceof Seed) || mode == Mode.FOOD && (item instanceof Food) || mode == Mode.POTION && (item instanceof Potion) || mode == Mode.SCROLL && (item instanceof Scroll) || mode == Mode.EQUIPMENT && (item instanceof EquipableItem) || mode == Mode.ALL ); } } else { bg.color( NORMAL ); } } @Override protected void onTouchDown() { bg.brightness( 1.5f );
Sample.INSTANCE.play( Assets.SND_CLICK, 0.7f, 0.7f, 1.2f );
0
handstudio/HzGrapher
sample/src/com/handstudio/android/hzgrapher/LineCompareGraphActivity.java
[ "public class GraphAnimation {\n\tpublic static final int LINEAR_ANIMATION = 1;\n\t\n\tpublic static final int CURVE_REGION_ANIMATION_1 = 2;\n\tpublic static final int CURVE_REGION_ANIMATION_2 = 3;\n\t\n\tpublic static final int DEFAULT_DURATION = 2000;\n\t\n\tprivate int animation = LINEAR_ANIMATION;\n\tprivate in...
import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.ViewGroup; import com.handstudio.android.hzgrapherlib.animation.GraphAnimation; import com.handstudio.android.hzgrapherlib.graphview.LineCompareGraphView; import com.handstudio.android.hzgrapherlib.vo.GraphNameBox; import com.handstudio.android.hzgrapherlib.vo.linegraph.LineGraph; import com.handstudio.android.hzgrapherlib.vo.linegraph.LineGraphVO;
package com.handstudio.android.hzgrapher; public class LineCompareGraphActivity extends Activity { private ViewGroup layoutGraphView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_graph); layoutGraphView = (ViewGroup) findViewById(R.id.layoutGraphView); setLineCompareGraph(); } private void setLineCompareGraph() { //all setting LineGraphVO vo = makeLineCompareGraphAllSetting(); //default setting // LineGraphVO vo = makeLineCompareGraphDefaultSetting(); layoutGraphView.addView(new LineCompareGraphView(this, vo)); } /** * make simple line graph * @return */ private LineGraphVO makeLineCompareGraphDefaultSetting() { String[] legendArr = {"1","2","3","4","5"}; float[] graph1 = {500,100,300,200,100}; float[] graph2 = {000,100,200,100,200}; List<LineGraph> arrGraph = new ArrayList<LineGraph>(); arrGraph.add(new LineGraph("android", 0xaa66ff33, graph1)); arrGraph.add(new LineGraph("ios", 0xaa00ffff, graph2)); LineGraphVO vo = new LineGraphVO(legendArr, arrGraph); return vo; } /** * make line graph using options * @return */ private LineGraphVO makeLineCompareGraphAllSetting() { //BASIC LAYOUT SETTING //padding int paddingBottom = LineGraphVO.DEFAULT_PADDING; int paddingTop = LineGraphVO.DEFAULT_PADDING; int paddingLeft = LineGraphVO.DEFAULT_PADDING; int paddingRight = LineGraphVO.DEFAULT_PADDING; //graph margin int marginTop = LineGraphVO.DEFAULT_MARGIN_TOP; int marginRight = LineGraphVO.DEFAULT_MARGIN_RIGHT; //max value int maxValue = LineGraphVO.DEFAULT_MAX_VALUE; //increment int increment = LineGraphVO.DEFAULT_INCREMENT; //GRAPH SETTING String[] legendArr = {"1","2","3","4","5"}; float[] graph1 = {500,100,300,200,100}; float[] graph2 = {000,300,200,100,200}; List<LineGraph> arrGraph = new ArrayList<LineGraph>(); arrGraph.add(new LineGraph("android", 0xaa66ff33, graph1, R.drawable.ic_launcher)); arrGraph.add(new LineGraph("ios", 0xaa00ffff, graph2)); LineGraphVO vo = new LineGraphVO( paddingBottom, paddingTop, paddingLeft, paddingRight, marginTop, marginRight, maxValue, increment, legendArr, arrGraph); //set animation
vo.setAnimation(new GraphAnimation(GraphAnimation.LINEAR_ANIMATION, GraphAnimation.DEFAULT_DURATION));
0
desht/ScrollingMenuSign
src/main/java/me/desht/scrollingmenusign/views/SMSSpoutView.java
[ "public class SMSException extends DHUtilsException {\n\n private static final long serialVersionUID = 1L;\n\n public SMSException(String message) {\n super(message);\n }\n\n}", "public class SMSMenu extends Observable implements SMSPersistable, SMSUseLimitable, ConfigurationListener, Comparable<S...
import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Observable; import java.util.UUID; import me.desht.dhutils.ConfigurationManager; import me.desht.dhutils.Debugger; import me.desht.dhutils.LogUtils; import me.desht.dhutils.PermissionUtils; import me.desht.scrollingmenusign.SMSException; import me.desht.scrollingmenusign.SMSMenu; import me.desht.scrollingmenusign.ScrollingMenuSign; import me.desht.scrollingmenusign.spout.HexColor; import me.desht.scrollingmenusign.spout.SMSSpoutKeyMap; import me.desht.scrollingmenusign.spout.SpoutViewPopup; import me.desht.scrollingmenusign.spout.TextEntryPopup; import me.desht.scrollingmenusign.views.action.ViewUpdateAction; import org.bukkit.Bukkit; import org.bukkit.configuration.Configuration; import org.bukkit.entity.Player; import org.getspout.spoutapi.SpoutManager; import org.getspout.spoutapi.gui.PopupScreen; import org.getspout.spoutapi.player.SpoutPlayer;
package me.desht.scrollingmenusign.views; /** * This view draws menus on a popped-up Spout view. */ public class SMSSpoutView extends SMSScrollableView implements PoppableView { // attributes public static final String AUTOPOPDOWN = "autopopdown"; public static final String SPOUTKEYS = "spoutkeys"; public static final String BACKGROUND = "background"; public static final String ALPHA = "alpha"; public static final String TEXTURE = "texture"; // list of all popups which have been created for this view, keyed by player ID private final Map<UUID, SpoutViewPopup> popups = new HashMap<UUID, SpoutViewPopup>(); // map a set of keypresses to the view which handles them private static final Map<String, String> keyMap = new HashMap<String, String>(); /** * Construct a new SMSSPoutView object * * @param name The view name * @param menu The menu to attach the object to * @throws SMSException */
public SMSSpoutView(String name, SMSMenu menu) throws SMSException {
1
isel-leic-mpd/mpd-2017-i41d
aula08-template-vs-strategy/src/test/java/LazyQueriesTest.java
[ "public class FileRequest implements IRequest{\n @Override\n public Iterable<String> getContent(String path) {\n String[] parts = path.split(\"/\");\n path = parts[parts.length-1]\n .replace('?', '-')\n .replace('&', '-')\n .replace('=', '-')\n ...
import org.junit.Test; import util.FileRequest; import util.queries.LazyQueries; import weather.WeatherWebApi; import weather.dto.WeatherInfo; import java.time.LocalDate; import static org.junit.Assert.assertEquals; import static util.queries.LazyQueries.*; import static util.queries.LazyQueries.filter;
/* * Copyright (c) 2017, Miguel Gamboa * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Miguel Gamboa * created on 15-03-2017 */ public class LazyQueriesTest { @Test public void testLazyFilterAndMapAndDistinct(){
WeatherWebApi api = new WeatherWebApi(new FileRequest());
2