code
stringlengths
73
34.1k
label
stringclasses
1 value
protected String getBaseString() { StringBuilder sb = new StringBuilder(HAWK_HEADER_PREFIX).append(SLF); sb.append(getTs()).append(SLF); sb.append(getNonce()).append(SLF); sb.append(getMethod()).append(SLF); sb.append(getPath()).append(SLF); sb.append(getHost()).append(SLF); sb.append(getPort()).append(SL...
java
public static HawkContextBuilder_B request(String method, String path, String host, int port) { return new HawkContextBuilder().method(method).path(path).host(host) .port(port); }
java
@Override public byte[] decompress(InputStream strm) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); LZFInputStream in = new LZFInputStream(strm); byte[] buffer = new byte[8192]; int len = 0; //Decode and copy to output ...
java
public static GregorianCalendar getRandomDate(long seed) { GregorianCalendar gc = new GregorianCalendar(); Random rand = new Random(seed); gc.set(GregorianCalendar.YEAR,1900+rand.nextInt(120)); //Between 1900 & 2020 gc.set(GregorianCalendar.DAY_OF_YEAR,rand.nextInt(364)+1); //Day of year...
java
public void setCookies(List<HttpCookie> cookies) { Map<String, HttpCookie> map = new HashMap<String, HttpCookie>(); for (HttpCookie cookie : cookies) { map.put(cookie.getName(), cookie); } this.cookies = map; }
java
private static <T extends Comparable<T>> List<Interval<T>> combine(Partition<T> p1, Partition<T> p2) throws MIDDException { Set<EndPoint<T>> boundSet = new HashSet<EndPoint<T>>(); //collect all bounds and remove duplicated items for (Interval<T> interval : p1.getIntervals()) { boun...
java
public List<Interval<T>> complement(final Interval<T> op) throws MIDDException { final boolean disJoined = (this.lowerBound.compareTo(op.upperBound) >= 0) || (this.upperBound.compareTo(op.lowerBound) <= 0); if (disJoined) { Interval<T> newInterval = new Interval<>(this.lowe...
java
public boolean contains(final Interval<T> i) { int compareLow, compareUp; compareLow = this.lowerBound.compareTo(i.lowerBound); compareUp = this.upperBound.compareTo(i.upperBound); if (compareLow < 0) { // check the upper bound if (compareUp > 0) { ...
java
public boolean hasValue(final T value) throws MIDDException { //special processing when missing attribute if (value == null) { return this.isLowerInfinite() || this.isUpperInfinite(); } EndPoint<T> epValue = new EndPoint<>(value); int compareLow = this.lowerBound....
java
public static <T extends Comparable<T>> Interval<T> of(final T v) throws MIDDException { return new Interval(v); }
java
public void logLocalCommands(final List<Command> commands) { if (singleValue == null) { return; } for (final Command command : commands) { if (command instanceof SetPropertyValue) { singleValue.logLocalCommand((SetPropertyValue) command); } els...
java
public void setModel(SoundCloudTrack track) { mModel = track; if (mModel != null) { Picasso.with(getContext()) .load(SoundCloudArtworkHelper.getArtworkUrl(mModel, SoundCloudArtworkHelper.XLARGE)) .placeholder(R.color.grey_light) .fi...
java
private void setTrack(SoundCloudTrack track) { if (track == null) { mTitle.setText(""); mArtwork.setImageDrawable(null); mPlayPause.setImageResource(R.drawable.ic_play_white); mSeekBar.setProgress(0); String none = String.format(getResources().getStrin...
java
public String getFinalReason(Path path) { StringBuilder sb = new StringBuilder(path + " cannot be modified; "); StringBuilder finalPath = new StringBuilder("/"); // Step through the nodes based on the given path. If any intermediate // nodes are marked as final, we can just return true. Node currentNode = r...
java
public void setFinal(Path path) { // Step through the nodes creating any nodes which don't exist. Node currentNode = root; for (Term t : path.getTerms()) { Node nextNode = currentNode.getChild(t); if (nextNode == null) { nextNode = currentNode.newChild(t); } currentNode = nextNode; } // The ...
java
public List<String> toList() { List<String> list = new LinkedList<String>(); if (authority != null) { list.add(authority); } for (Term t : terms) { list.add(t.toString()); } return list; }
java
public int compareTo(Path o) { // Sanity check. if (o == null) { throw new NullPointerException(); } // If these are not the same type, do the simple comparison. if (this.type != o.type) { return type.compareTo(o.type); } // Same type of...
java
private void sendAction(Context context, String action) { Intent intent = new Intent(context, PlaybackService.class); intent.setAction(action); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); }
java
public void updateMemoryInfo() { MemoryMXBean meminfo = ManagementFactory.getMemoryMXBean(); MemoryUsage usage = meminfo.getHeapMemoryUsage(); long _heapUsed = usage.getUsed(); updateMaximum(heapUsed, _heapUsed); updateMaximum(heapTotal, usage.getMax()); usage = meminfo.getNonHeapMemoryUsage(); updateM...
java
private static void updateMaximum(AtomicLong counter, long currentValue) { boolean unset = true; long counterValue = counter.get(); while ((currentValue > counterValue) && unset) { unset = !counter.compareAndSet(counterValue, currentValue); counterValue = counter.get(); } }
java
public String getResults(long totalErrors) { Object[] info = { fileCount, doneTasks.get(COMPILED).get(), startedTasks.get(COMPILED).get(), doneTasks.get(ANNOTATION).get(), startedTasks.get(ANNOTATION).get(), doneTasks.get(XML).get(), startedTasks.get(XML).get(), doneTasks.get(DEP).get(), startedT...
java
@Override public void onConnect(final Object newClient) { meta.commandsForDomainModel(new CommandsForDomainModelCallback() { @Override public void commandsReady(final List<Command> commands) { networkLayer.onConnectFinished(newClient); networkLayer.sen...
java
@Override public void onClientConnectionError(final Object client, final SynchronizeFXException e) { serverCallback.onClientConnectionError(client, e); }
java
private void removeDefinedFields(Context context, List<Term> undefinedFields) throws ValidationException { // Loop through all of the required and optional fields removing each // from the list of undefined fields. for (Term term : reqKeys) { undefinedFields.remove(term); } for (Term term : optKeys) { ...
java
public static void activateLoggers(String loggerList) { // Create an empty set. This will contain the list of all of the loggers // to activate. (Note that NONE may be a logger; in this case, all // logging will be deactivated.) EnumSet<LoggingType> flags = EnumSet.noneOf(LoggingType.class); // Split on com...
java
private static void initializeLogger(Logger logger) { // Do NOT send any logging information to parent loggers. topLogger.setUseParentHandlers(false); // Remove any existing handlers. for (Handler handler : topLogger.getHandlers()) { try { topLogger.removeHandler(handler); } catch (SecurityException...
java
public synchronized static void setLogFile(File logfile) { // Add a file logger that will use the compiler's customized // formatter. This formatter provides a terse representation of the // logging information. try { if (logfile != null) { String absolutePath = logfile.getAbsolutePath(); if (initia...
java
public void put(String url, String result) { if (TextUtils.isEmpty(url)) { return; } ContentValues contentValues = new ContentValues(); contentValues.put(OfflinerDBHelper.REQUEST_RESULT, result); contentValues.put(OfflinerDBHelper.REQUEST_URL, url); contentVa...
java
public String get(Context context, String url) { final Cursor cursor = context.getContentResolver().query(getUri(OfflinerDBHelper.TABLE_CACHE), OfflinerDBHelper.PARAMS_CACHE, OfflinerDBHelper.REQUEST_URL + " = '" + url + "'", null, null); String result = null; ...
java
private Uri getUri(String string) { return Uri.parse(OfflinerProvider.CONTENT + OfflinerProvider.getAuthority(mPackageName) + OfflinerProvider.SLASH + string); }
java
public void setPlaybackState(int state) { if (sHasRemoteControlAPIs) { try { sRCCSetPlayStateMethod.invoke(mActualRemoteControlClient, state); } catch (Exception e) { throw new RuntimeException(e); } } }
java
public void setTransportControlFlags(int transportControlFlags) { if (sHasRemoteControlAPIs) { try { sRCCSetTransportControlFlags.invoke(mActualRemoteControlClient, transportControlFlags); } catch (Exception e) { throw new RuntimeEx...
java
@SuppressWarnings("deprecation") public void onDestroy() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED); mAudioManager.unregisterMediaButtonEventReceiver(mMediaButtonReceiverComponent); ...
java
@SuppressWarnings("deprecation") public void setMetaData(SoundCloudTrack track, Bitmap artwork) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { // set meta data on the lock screen for pre lollipop. mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTA...
java
private void setRemoteControlClientPlaybackState(int state) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { mRemoteControlClientCompat.setPlaybackState(state); } }
java
private void setMediaSessionCompatPlaybackState(int state) { mStateBuilder.setState(state, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f); mMediaSession.setPlaybackState(mStateBuilder.build()); }
java
private void initPlaybackStateBuilder() { mStateBuilder = new PlaybackStateCompat.Builder(); mStateBuilder.setActions( PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE ...
java
@SuppressWarnings("deprecation") private void initLockScreenRemoteControlClient(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { mMediaButtonReceiverComponent = new ComponentName( mRuntimePackageName, MediaSessionReceiver.class.getName()); ...
java
private void registerLockScreenReceiver(Context context) { mLockScreenReceiver = new LockScreenReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ACTION_TOGGLE_PLAYBACK); intentFilter.addAction(ACTION_NEXT_TRACK); intentFilter.addAction(ACTION_PREV...
java
public void repairLocalCommandsVersion(final Queue<ListCommand> localCommands, final ListCommand originalRemoteCommand) { localCommands.add(repairCommand(localCommands.poll(), originalRemoteCommand.getListVersionChange() .getToVersion(), randomUUID())); final int count = lo...
java
public List<? extends ListCommand> repairRemoteCommandVersion( final List<? extends ListCommand> indexRepairedRemoteCommands, final List<ListCommand> versionRepairedLocalCommands) { final int commandCount = indexRepairedRemoteCommands.size(); final ListCommand lastLocalCommand =...
java
private void checkRangeValues(long minimum, long maximum) { if (minimum > maximum) { throw EvaluationException.create( MSG_MIN_MUST_BE_LESS_OR_EQUAL_TO_MAX, minimum, maximum); } }
java
@Override public void shutdown() { synchronized (connections) { parent.channelCloses(this); for (final MessageInbound connection : connections) { try { connection.getWsOutbound().close(0, null); } catch (final IOException e) { ...
java
public List<Command> setPropertyValue(final UUID propertyId, final Object value) throws SynchronizeFXException { final State state = createCommandList(new WithCommandType() { @Override public void invoke(final State state) { setPropertyValue(propertyId, value, state); ...
java
public List<Command> addToList(final UUID listId, final int position, final Object value, final int newSize) { final State state = createCommandList(new WithCommandType() { @Override public void invoke(final State state) { addToList(listId, position, value, newSize, state...
java
public List<Command> addToSet(final UUID setId, final Object value) { final State state = createCommandList(new WithCommandType() { @Override public void invoke(final State state) { addToSet(setId, value, state); } }, true); return state.comman...
java
public List<Command> putToMap(final UUID mapId, final Object key, final Object value) { final State state = createCommandList(new WithCommandType() { @Override public void invoke(final State state) { putToMap(mapId, key, value, state); } }, true); ...
java
public List<Command> removeFromList(final UUID listId, final int startPosition, final int removeCount) { final ListVersionChange change = increaseListVersion(listId); final RemoveFromList msg = new RemoveFromList(listId, change, startPosition, removeCount); final List<Command> commands = new Arr...
java
public List<Command> removeFromMap(final UUID mapId, final Object key) { final State state = createCommandList(new WithCommandType() { @Override public void invoke(final State state) { createObservableObject(key, state); } }, false); final boo...
java
public List<Command> removeFromSet(final UUID setId, final Object value) { final State state = createCommandList(new WithCommandType() { @Override public void invoke(final State state) { createObservableObject(value, state); } }, false); final...
java
public List<Command> replaceInList(final UUID listId, final int position, final Object value) { final State state = createCommandList(new WithCommandType() { @Override public void invoke(final State state) { final boolean isObservableObject = createObservableObject(value,...
java
static void replaceHeredocStrings(ASTTemplate tnode, List<StringProperty> strings) { // Only something to do if there were heredoc strings defined. if (strings.size() > 0) { processHeredocStrings(tnode, strings); } }
java
static void processSingleQuotedString(StringBuilder sb) { // Sanity checking. Make sure input string has at least two characters // and that the first and last are single quotes. assert (sb.length() >= 2); assert (sb.charAt(0) == '\'' && sb.charAt(sb.length() - 1) == '\''); // ...
java
public SourceFile retrievePanSource(String name, List<String> loadpath) { String cacheKey = name + ((String) " ") + String.join(":", loadpath); SourceFile cachedResult = retrievePanCacheLoadpath.get(cacheKey); if (cachedResult == null) { File file = lookupSource(name, loadpath); ...
java
public Resource.Iterator get(Resource resource) { Integer key = Integer.valueOf(System.identityHashCode(resource)); return map.get(key); }
java
public void put(Resource resource, Resource.Iterator iterator) { assert (resource != null); Integer key = Integer.valueOf(System.identityHashCode(resource)); if (iterator != null) { map.put(key, iterator); } else { map.remove(key); } }
java
private void addFiles(FileSet fs) { // Get the files included in the fileset. DirectoryScanner ds = fs.getDirectoryScanner(getProject()); // The base directory for all files. File basedir = ds.getBasedir(); // Loop over each file creating a File object. for (String f :...
java
public void setWarnings(String warnings) { try { deprecationWarnings = CompilerOptions.DeprecationWarnings .fromString(warnings); } catch (IllegalArgumentException e) { throw new BuildException("invalid value for warnings: " + warnings); } }
java
public void setObjectAndLoadpath() { StringProperty sname = StringProperty.getInstance(objectTemplate.name); setGlobalVariable("OBJECT", sname, true); setGlobalVariable("LOADPATH", new ListResource(), false); }
java
public void setIterator(Resource resource, Resource.Iterator iterator) { iteratorMap.put(resource, iterator); }
java
public Element getVariable(String name) { Element result = localVariables.get(name); // If the result is null, then try to look up a global variable. if (result == null) { result = getGlobalVariable(name); } return result; }
java
public Element dereferenceVariable(String name, boolean lookupOnly, Term[] terms) throws InvalidTermException { boolean duplicate = false; Element result = localVariables.get(name); // If the result is null, then try to look up a global variable. if (result == null) { duplicate = true; result = getGl...
java
protected int convertMatchFlags(Element opts) { int flags = 0; String sopts = ((StringProperty) opts).getValue(); for (int i = 0; i < sopts.length(); i++) { char c = sopts.charAt(i); switch (c) { case 'i': flags |= Pattern.CASE_INSENSITIVE; break; case 's': flags |= Pattern.DOTALL; b...
java
protected Pattern compilePattern(Element regex, int flags) { Pattern p = null; try { String re = ((StringProperty) regex).getValue(); p = Pattern.compile(re, flags); } catch (PatternSyntaxException pse) { throw EvaluationException.create(sourceRange, MSG_INVALID_REGEXP, pse.getLocalizedMessage()); ...
java
synchronized public void setDependency(String objectName, String dependencyName) throws EvaluationException { // Determine if adding this dependency will create a cycle. String nextObjectName = dependencies.get(dependencyName); while (nextObjectName != null) { if (objectName.equals(nextObjectName)) { t...
java
synchronized private String getCycle(String objectName, String dependencyName) { // Determine if adding this dependency will create a cycle. StringBuilder sb = new StringBuilder(); sb.append(objectName); sb.append(" -> "); sb.append(dependencyName); String nextObjectName = dependencies.get(dependencyNa...
java
@Override public Element execute(Context context) { try { Element[] args = calculateArgs(context); Property a = (Property) args[0]; Property b = (Property) args[1]; return execute(sourceRange, a, b); } catch (ClassCastException cce) { throw new EvaluationException(MessageUtils .format(MSG_INVA...
java
private static Element execute(SourceRange sourceRange, Property a, Property b) { assert (a != null); assert (b != null); Element result = null; if ((a instanceof LongProperty) && (b instanceof LongProperty)) { long l1 = ((Long) a.getValue()).longValue(); long l2 = ((Long) b.getValue()).longValue()...
java
public void setIncludeRoot(File includeroot) { this.includeroot = includeroot; if (!includeroot.exists()) { throw new BuildException("includeroot doesn't exist: " + includeroot); } if (!includeroot.isDirectory()) { throw new BuildException("i...
java
public void setIncludes(String includes) { // Split the string into separate file globs. String[] globs = includes.split("[\\s,]+"); // Loop over these globs and create dirsets from them. // Do not set the root directory until the task is // executed. for (String glob :...
java
private void addPaths(Path p) { for (String d : p.list()) { File dir = new File(d); if (dir.exists() && dir.isDirectory()) { if (!includeDirectories.contains(dir)) includeDirectories.add(dir); } } }
java
public HashResource restoreRelativeRoot(HashResource previousValue) { HashResource value = relativeRoot; relativeRoot = previousValue; return value; }
java
public Set<SourceFile> getDependencies() { Set<SourceFile> sourceFiles = new TreeSet<SourceFile>(); // Include all of the standard dependencies. for (Template t : dependencies.values()) { sourceFiles.add(t.sourceFile); } // Add the files that were looked-up but not found as well as the files // includ...
java
public Template globalLoad(String name, boolean lookupOnly) { // If this context was created without a Compiler object specified, then // no global lookups can be done. Just return null indicating that the // requested template can't be found. if (compiler == null) { return null; } // Use the full look...
java
public void setBinding(Path path, FullType fullType, Template template, SourceRange sourceRange) { assert (path != null); assert (path.isAbsolute()); assert (fullType != null); // Must make sure that all of the subtypes for the given type are // defined before adding the binding. try { fullType.veri...
java
public void setGlobalVariable(String name, Element value) { assert (name != null); GlobalVariable gvar = globalVariables.get(name); gvar.setValue(value); }
java
public void setGlobalVariable(String name, GlobalVariable variable) { assert (name != null); if (variable != null) { globalVariables.put(name, variable); } else { globalVariables.remove(name); } }
java
public GlobalVariable replaceGlobalVariable(String name, Element value, boolean finalFlag) { assert (name != null); GlobalVariable oldVariable = globalVariables.get(name); GlobalVariable newVariable = new GlobalVariable(finalFlag, value); globalVariables.put(name, newVariable); return oldVariable; }
java
public void setGlobalVariable(String name, Element value, boolean finalFlag) { assert (name != null); // Either modify an existing value (with appropriate checks) or add a // new one. if (globalVariables.containsKey(name)) { GlobalVariable gvar = globalVariables.get(name); gvar.setValue(value); gvar...
java
public Element getGlobalVariable(String name) { GlobalVariable gvar = globalVariables.get(name); return (gvar != null) ? gvar.getValue() : null; }
java
public Element getElement(Path path, boolean errorIfNotFound) throws EvaluationException { // Set the initial node to use. Element node = null; // The initial element to use depends on the type of path. Define the // correct root element. switch (path.getType()) { case ABSOLUTE: // Typical, very ea...
java
public void setLocalVariable(String name, Term[] terms, Element value) throws EvaluationException { assert (name != null); // Only truly local variables can be set via this method. Throw an // exception if a global variable is found which matches the name. if (globalVariables.containsKey(name)) { throw ...
java
public void execute(final Object observable, final Runnable change) { listeners.disableFor(observable); change.run(); listeners.enableFor(observable); }
java
protected void executeWithNamedTemplate(Context context, String name) throws EvaluationException { assert (context != null); assert (name != null); Template template = null; boolean runStatic = false; try { template = context.localLoad(name); if (template == null) { template = context.globalLo...
java
static private Element runDefaultDml(Operation dml) throws SyntaxException { // If the argument is null, return null as the value immediately. if (dml == null) { return null; } // Create a nearly empty execution context. There are no global // variables by default (including no 'SELF' variable). Only the...
java
private String retrieveFromCache(String url) { String savedJson; savedJson = mCacheQueryHandler.get(getContext(), url); log("---------- body found in offline saver : " + savedJson); log("----- NO NETWORK : retrieving ends"); return savedJson; }
java
private Context getContext() { Context context = mContext.get(); if (context == null) { throw new IllegalStateException("Context used by the instance has been destroyed."); } return context; }
java
private Response save(Response response) { String jsonBody; String key = response.request().url().toString(); log("----- SAVE FOR OFFLINE : saving starts"); log("---------- for request : " + key); log("---------- trying to parse response body"); //Try to get response bo...
java
public void destroy() { if (mIsClosed) { return; } if (mState != STATE_STOPPED) { mDestroyDelayed = true; return; } mIsClosed = true; PlaybackService.unregisterListener(getContext(), mInternalListener); mInternalListener = null...
java
public void play(int position) { checkState(); ArrayList<SoundCloudTrack> tracks = mPlayerPlaylist.getPlaylist().getTracks(); if (position >= 0 && position < tracks.size()) { SoundCloudTrack trackToPlay = tracks.get(position); mPlayerPlaylist.setPlayingTrack(position); ...
java
public void addTrack(SoundCloudTrack track, boolean playNow) { checkState(); mPlayerPlaylist.add(track); for (CheerleaderPlaylistListener listener : mCheerleaderPlaylistListeners) { listener.onTrackAdded(track); } if (playNow) { play(mPlayerPlaylist.size()...
java
public void addTracks(List<SoundCloudTrack> tracks) { checkState(); for (SoundCloudTrack track : tracks) { addTrack(track); } }
java
public void registerPlayerListener(CheerleaderPlayerListener listener) { checkState(); mCheerleaderPlayerListeners.add(listener); if (mState == STATE_PLAYING) { listener.onPlayerPlay(mPlayerPlaylist.getCurrentTrack(), mPlayerPlaylist.getCurrentTrackIndex()); } else if (mState...
java
private void initInternalListener(Context context) { mInternalListener = new PlaybackListener() { @Override protected void onPlay(SoundCloudTrack track) { super.onPlay(track); mState = STATE_PLAYING; for (CheerleaderPlayerListener listener ...
java
public static String getMessageString(String msgKey) { assert (msgKey != null); try { return bundle.getString(msgKey); } catch (MissingResourceException mre) { throw new CompilerError(mre.getLocalizedMessage()); } catch (ClassCastException cce) { t...
java
public static String format(String msgKey, Object... args) { try { return MessageFormat.format(getMessageString(msgKey), args); } catch (IllegalArgumentException iae) { throw new CompilerError( "bundle contains invalid message format for key '" + msgKey + "...
java
@SuppressWarnings({ "rawtypes", "unchecked" }) // The alternative would be to change the TopologolyLayerCallback.send() to take List<? extends Command> private void execute(final ListCommand command) { getMetaData(command); final Queue<ListCommand> log = metaData.getUnapprovedCommands(); ...
java
public void checkValidReplacement(Element newValue) throws EvaluationException { // Only need to check if new values is not undef or null. Undef or null // can replace any value. if (!(newValue instanceof Undef) && !(newValue instanceof Null)) { if (!this.getClass().isAssignableFrom(newValue.getClass())) ...
java
public Element rget(Term[] terms, int index, boolean protect, boolean lookupOnly) throws InvalidTermException { if (!lookupOnly) { throw new EvaluationException(MessageUtils.format( MSG_ILLEGAL_DEREFERENCE, this.getTypeAsString())); } return null; }
java
public ListResource rgetList(Term[] terms, int index) throws InvalidTermException { throw new EvaluationException(MessageUtils.format( MSG_ILLEGAL_DEREFERENCE, this.getTypeAsString())); }
java