text:
package com.jmv.frre.moduloestudiante.ui.Cells;
import com.jmv.frre.moduloestudiante.R;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;

import com.jmv.frre.moduloestudiante.android.AndroidUtilities;
import com.jmv.frre.moduloestudiante.messenger.FileLoader;
import com.jmv.frre.moduloestudiante.android.MediaController;
import com.jmv.frre.moduloestudiante.messenger.TLRPC;
import com.jmv.frre.moduloestudiante.android.MessagesController;
import com.jmv.frre.moduloestudiante.android.MessageObject;
import com.jmv.frre.moduloestudiante.android.ImageReceiver;
import com.jmv.frre.moduloestudiante.ui.Views.ProgressView;
import com.jmv.frre.moduloestudiante.ui.Views.SeekBar;

import java.io.File;

public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelegate, MediaController.FileDownloadProgressListener {

    private static Drawable[][] statesDrawable = new Drawable[8][2];
    private static TextPaint timePaint;

    private ImageReceiver avatarImage;
    private boolean needAvatarImage = false;
    private SeekBar seekBar;
    private ProgressView progressView;
    private int seekBarX;
    private int seekBarY;

    private int buttonState = 0;
    private int buttonX;
    private int buttonY;
    private boolean buttonPressed = false;

    private boolean avatarPressed = false;

    private StaticLayout timeLayout;
    private int timeX;
    private String lastTimeString = null;

    private int TAG;

    public TLRPC.User audioUser;
    private TLRPC.FileLocation currentPhoto;

    public ChatAudioCell(Context context) {
        super(context);
        TAG = MediaController.getInstance().generateObserverTag();

        avatarImage = new ImageReceiver(this);
        seekBar = new SeekBar(context);
        seekBar.delegate = this;
        progressView = new ProgressView();

        if (timePaint == null) {
            statesDrawable[0][0] = getResources().getDrawable(R.drawable.play1);
            statesDrawable[0][1] = getResources().getDrawable(R.drawable.play1_pressed);
            statesDrawable[1][0] = getResources().getDrawable(R.drawable.pause1);
            statesDrawable[1][1] = getResources().getDrawable(R.drawable.pause1_pressed);
            statesDrawable[2][0] = getResources().getDrawable(R.drawable.audioload1);
            statesDrawable[2][1] = getResources().getDrawable(R.drawable.audioload1_pressed);
            statesDrawable[3][0] = getResources().getDrawable(R.drawable.audiocancel1);
            statesDrawable[3][1] = getResources().getDrawable(R.drawable.audiocancel1_pressed);

            statesDrawable[4][0] = getResources().getDrawable(R.drawable.play2);
            statesDrawable[4][1] = getResources().getDrawable(R.drawable.play2_pressed);
            statesDrawable[5][0] = getResources().getDrawable(R.drawable.pause2);
            statesDrawable[5][1] = getResources().getDrawable(R.drawable.pause2_pressed);
            statesDrawable[6][0] = getResources().getDrawable(R.drawable.audioload2);
            statesDrawable[6][1] = getResources().getDrawable(R.drawable.audioload2_pressed);
            statesDrawable[7][0] = getResources().getDrawable(R.drawable.audiocancel2);
            statesDrawable[7][1] = getResources().getDrawable(R.drawable.audiocancel2_pressed);

            timePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
            timePaint.setTextSize(AndroidUtilities.dp(12));
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (avatarImage != null) {
            avatarImage.clearImage();
            currentPhoto = null;
        }
        MediaController.getInstance().removeLoadingFileObserver(this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        boolean result = seekBar.onTouch(event.getAction(), event.getX() - seekBarX, event.getY() - seekBarY);
        if (result) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            invalidate();
        } else {
            int side = AndroidUtilities.dp(36);
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (x >= buttonX && x <= buttonX + side && y >= buttonY && y <= buttonY + side) {
                    buttonPressed = true;
                    invalidate();
                    result = true;
                } else if (needAvatarImage && avatarImage.isInsideImage(x, y)) {
                    avatarPressed = true;
                    result = true;
                }
            } else if (buttonPressed) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    buttonPressed = false;
                    playSoundEffect(SoundEffectConstants.CLICK);
                    didPressedButton();
                    invalidate();
                } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                    buttonPressed = false;
                    invalidate();
                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    if (!(x >= buttonX && x <= buttonX + side && y >= buttonY && y <= buttonY + side)) {
                        buttonPressed = false;
                        invalidate();
                    }
                }
            } else if (avatarPressed) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    avatarPressed = false;
                    playSoundEffect(SoundEffectConstants.CLICK);
                    if (delegate != null) {
                        delegate.didPressedUserAvatar(this, audioUser);
                    }
                } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                    avatarPressed = false;
                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    if (!avatarImage.isInsideImage(x, y)) {
                        avatarPressed = false;
                    }
                }
            }
            if (!result) {
                result = super.onTouchEvent(event);
            }
        }

        return result;
    }

    private void didPressedButton() {
        if (buttonState == 0) {
            boolean result = MediaController.getInstance().playAudio(currentMessageObject);
            if (result) {
                buttonState = 1;
                invalidate();
            }
        } else if (buttonState == 1) {
            boolean result = MediaController.getInstance().pauseAudio(currentMessageObject);
            if (result) {
                buttonState = 0;
                invalidate();
            }
        } else if (buttonState == 2) {
            FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.audio, true);
            buttonState = 3;
            invalidate();
        } else if (buttonState == 3) {
            FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.audio);
            buttonState = 2;
            invalidate();
        }
    }

    public void updateProgress() {
        if (currentMessageObject == null) {
            return;
        }

        if (!seekBar.isDragging()) {
            seekBar.setProgress(currentMessageObject.audioProgress);
        }

        int duration = 0;
        if (!MediaController.getInstance().isPlayingAudio(currentMessageObject)) {
            duration = currentMessageObject.messageOwner.media.audio.duration;
        } else {
            duration = currentMessageObject.audioProgressSec;
        }
        String timeString = String.format("%02d:%02d", duration / 60, duration % 60);
        if (lastTimeString == null || lastTimeString != null && !lastTimeString.equals(timeString)) {
            int timeWidth = (int)Math.ceil(timePaint.measureText(timeString));
            timeLayout = new StaticLayout(timeString, timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        }
        invalidate();
    }

    public void downloadAudioIfNeed() {
        if (buttonState == 2) {
            FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.audio, true);
            buttonState = 3;
            invalidate();
        }
    }

    public void updateButtonState() {
        String fileName = currentMessageObject.getFileName();
        File cacheFile = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
        if (cacheFile.exists()) {
            MediaController.getInstance().removeLoadingFileObserver(this);
            boolean playing = MediaController.getInstance().isPlayingAudio(currentMessageObject);
            if (!playing || playing && MediaController.getInstance().isAudioPaused()) {
                buttonState = 0;
            } else {
                buttonState = 1;
            }
            progressView.setProgress(0);
        } else {
            MediaController.getInstance().addLoadingFileObserver(fileName, this);
            if (!FileLoader.getInstance().isLoadingFile(fileName)) {
                buttonState = 2;
                progressView.setProgress(0);
            } else {
                buttonState = 3;
                Float progress = FileLoader.getInstance().getFileProgress(fileName);
                if (progress != null) {
                    progressView.setProgress(progress);
                } else {
                    progressView.setProgress(0);
                }
            }
        }
        updateProgress();
    }

    @Override
    public void onFailedDownload(String fileName) {
        updateButtonState();
    }

    @Override
    public void onSuccessDownload(String fileName) {
        updateButtonState();
    }

    @Override
    public void onProgressDownload(String fileName, float progress) {
        progressView.setProgress(progress);
        if (buttonState != 3) {
            updateButtonState();
        }
        invalidate();
    }

    @Override
    public void onProgressUpload(String fileName, float progress, boolean isEncrypted) {

    }

    @Override
    public int getObserverTag() {
        return TAG;
    }

    @Override
    public void onSeekBarDrag(float progress) {
        if (currentMessageObject == null) {
            return;
        }
        currentMessageObject.audioProgress = progress;
        MediaController.getInstance().seekToProgress(currentMessageObject, progress);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        setMeasuredDimension(width, AndroidUtilities.dp(68));
        if (isChat) {
            backgroundWidth = Math.min(width - AndroidUtilities.dp(102), AndroidUtilities.dp(300));
        } else {
            backgroundWidth = Math.min(width - AndroidUtilities.dp(50), AndroidUtilities.dp(300));
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        int x;

        if (currentMessageObject.isOut()) {
            x = layoutWidth - backgroundWidth + AndroidUtilities.dp(8);
            seekBarX = layoutWidth - backgroundWidth + AndroidUtilities.dp(97);
            buttonX = layoutWidth - backgroundWidth + AndroidUtilities.dp(67);
            timeX = layoutWidth - backgroundWidth + AndroidUtilities.dp(71);
        } else {
            if (isChat) {
                x = AndroidUtilities.dp(69);
                seekBarX = AndroidUtilities.dp(158);
                buttonX = AndroidUtilities.dp(128);
                timeX = AndroidUtilities.dp(132);
            } else {
                x = AndroidUtilities.dp(16);
                seekBarX = AndroidUtilities.dp(106);
                buttonX = AndroidUtilities.dp(76);
                timeX = AndroidUtilities.dp(80);
            }
        }
        int diff = 0;
        if (needAvatarImage) {
            avatarImage.setImageCoords(x, AndroidUtilities.dp(9), AndroidUtilities.dp(50), AndroidUtilities.dp(50));
        } else {
            diff = AndroidUtilities.dp(56);
            seekBarX -= diff;
            buttonX -= diff;
            timeX -= diff;
        }

        seekBar.width = backgroundWidth - AndroidUtilities.dp(112) + diff;
        seekBar.height = AndroidUtilities.dp(30);
        progressView.width = backgroundWidth - AndroidUtilities.dp(136) + diff;
        progressView.height = AndroidUtilities.dp(30);
        seekBarY = AndroidUtilities.dp(13);
        buttonY = AndroidUtilities.dp(10);

        updateProgress();
    }

    @Override
    protected boolean isUserDataChanged() {
        TLRPC.User newUser = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.media.audio.user_id);
        TLRPC.FileLocation newPhoto = null;

        if (avatarImage != null && newUser != null && newUser.photo != null) {
            newPhoto = newUser.photo.photo_small;
        }

        return currentPhoto == null && newPhoto != null || currentPhoto != null && newPhoto == null || currentPhoto != null && newPhoto != null && (currentPhoto.local_id != newPhoto.local_id || currentPhoto.volume_id != newPhoto.volume_id) || super.isUserDataChanged();
    }

    @Override
    public void setMessageObject(MessageObject messageObject) {
        if (currentMessageObject != messageObject || isUserDataChanged()) {
            int uid = messageObject.messageOwner.media.audio.user_id;
            if (uid == 0) {
                uid = messageObject.messageOwner.from_id;
            }
            needAvatarImage = !(messageObject.messageOwner.to_id != null && messageObject.messageOwner.to_id.chat_id != 0 && !messageObject.isOut() && messageObject.messageOwner.media.audio.user_id == messageObject.messageOwner.from_id);
            audioUser = MessagesController.getInstance().getUser(uid);

            if (needAvatarImage) {
                if (audioUser != null) {
                    if (audioUser.photo != null) {
                        currentPhoto = audioUser.photo.photo_small;
                    }
                    avatarImage.setImage(currentPhoto, "50_50", getResources().getDrawable(AndroidUtilities.getUserAvatarForId(uid)), false);
                } else {
                    avatarImage.setImage(null, "50_50", getResources().getDrawable(AndroidUtilities.getUserAvatarForId(uid)), false);
                }
            }

            if (messageObject.isOut()) {
                seekBar.type = 0;
                progressView.setProgressColors(0xffb4e396, 0xff6ac453);
            } else {
                seekBar.type = 1;
                progressView.setProgressColors(0xffd9e2eb, 0xff86c5f8);
            }

            super.setMessageObject(messageObject);
        }
        updateButtonState();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (currentMessageObject == null) {
            return;
        }

        if (needAvatarImage) {
            avatarImage.draw(canvas);
        }

        canvas.save();
        if (buttonState == 0 || buttonState == 1) {
            canvas.translate(seekBarX, seekBarY);
            seekBar.draw(canvas);
        } else {
            canvas.translate(seekBarX + AndroidUtilities.dp(12), seekBarY);
            progressView.draw(canvas);
        }
        canvas.restore();

        int state = buttonState;
        if (!currentMessageObject.isOut()) {
            state += 4;
            timePaint.setColor(0xffa1aab3);
        } else {
            timePaint.setColor(0xff70b15c);
        }
        Drawable buttonDrawable = statesDrawable[state][buttonPressed ? 1 : 0];
        int side = AndroidUtilities.dp(36);
        int x = (side - buttonDrawable.getIntrinsicWidth()) / 2;
        int y = (side - buttonDrawable.getIntrinsicHeight()) / 2;
        setDrawableBounds(buttonDrawable, x + buttonX, y + buttonY);
        buttonDrawable.draw(canvas);

        canvas.save();
        canvas.translate(timeX, AndroidUtilities.dp(45));
        timeLayout.draw(canvas);
        canvas.restore();
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="theme-color" content="#F15E5E">
    <meta property="og:title" content="GitPie"/>
    <meta property="og:site_name" content="GitPie"/>
    <meta property="og:url" content="http://gitpie.org"/>
    <meta property="og:description" content="A Multiplatform Client for Git"/>
    <meta name="keywords" content="gitpie, GitPie, git, gui, git client, nodejs, angularjs, node, open source, version control, repository, fork, branch, merge, stash, checkout, checkin, push, pull, cross platform, mac, windows, linux, multiplatform git client" />
    <meta name="description" content="A Multiplatform Client for Git" />
    <meta name="robots" content="index, follow" />
    <meta name="googlebot" content="index, follow" />

    <title>GitPie</title>
    <link rel="shortcut icon" href="/images/icon.ico">
    <link rel="stylesheet" href="/css/all.css" media="screen" charset="utf-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,300,700' rel='stylesheet' type='text/css'>

GitPie

Download

Releases

A Multiplatform Client for Git

For any platform

          Use GitPie on Linux, Mac or Windows

Same workflow to any repository

              Add, Clone or Create repositories. Create branches, stashes, commit changes, perform merges... All with the same UX.

Use only your favorite git service. Or all!

              GitPie was made to handle any git repository with any remote

We ❤ Open Source

              We believe that the best way to build something awesome is together. For this, Pie is 100% open source.

        Licenced under MIT.

         with  by Matheus Paiva and contributors

redpajama_set_name: RedPajamaGithub


text:
module VagrantPlugins
  module ProviderVirtualBox
    module Action
      class ProvisionerCleanup
        def initialize(app, env)
          @app = app
        end

        def call(env)
          # Instantiate all the enabled provisioners
          provisioners = env[:machine].config.vm.provisioners.map do |provisioner|
            provisioner.provisioner.new(env, provisioner.config)
          end

          # Call cleanup on each
          provisioners.each do |instance|
            instance.cleanup
          end

          @app.call(env)
        end
      end
    end
  end
end


text:
import sys
import requests
import json
from opentreetesting import config, summarize_json_response
DOMAIN = config('host', 'golshost')
p = '/ext/GoLS/graphdb/getSyntheticTree'
if DOMAIN.startswith('http://127.0.0.1'):
    p = '/db/data' + p
SUBMIT_URI = DOMAIN + p
payload = {
    'treeID' : 'otol.draft.22',
    'format' : 'arguson',
    'maxDepth' : 2
}
if len(sys.argv) > 1:
    payload['subtreeNodeID'] = sys.argv[1]
headers = {
    'content-type' : 'application/json',
    'accept' : 'application/json',
}
resp = requests.post(SUBMIT_URI,
                     headers=headers,
                     data=json.dumps(payload),
                     allow_redirects=True)
summarize_json_response(resp) or sys.exit(1)


text:
<?php
	$edit_mode = false;
	if(isset($_GET['page']) && $_GET['page']=='edit'){
		$edit_mode = true;
		printf('You are editing paste '.$_GET['id']);
		printf('<form role="form" method="post" action="../post.php" onsubmit="document.getElementById(\'submit\').disabled=true;document.getElementById(\'submit\').value=\'Please wait...\';">');
	}else printf('<form role="form" method="post" action="post.php" onsubmit="document.getElementById(\'submit\').disabled=true;document.getElementById(\'submit\').value=\'Please wait...\';">');
?>

        Paste title:
		<?php
			if($edit_mode == true){
				printf('<input type="title" class="form-control" value="'.$row['title'].'" id="title" name="title">');
			} else printf('<input type="title" class="form-control" id="title" name="title">');
		?>

        New paste:
		<?php
			if($edit_mode == true){
				echo '<textarea class="form-control" rows="5" id="text" name="text">'.$row['text'].'</textarea>';
			} else printf('<textarea class="form-control" rows="5" id="text" name="text"></textarea>');
		?>

	  <?php
		if($edit_mode == true){
		  printf("<input type='hidden' name='type' value='edit_paste'></input>");
		  printf("<input type='hidden' name='uid' value='".$row['uid']."'></input>");
		} else printf("<input type='hidden' name='type' value='paste'></input>");
	  ?>

				<input type="checkbox" name="asguest">Post as guest

            <button type="submit" class="btn btn-default">Submit</button>

              Expiration:
              <select class="form-control" id="expire" name="expire">
                <option>Never</option>
                <option value="600">10 Minutes</option>
                <option value="3600">1 Hour</option>
                <option value="86400">1 Day</option>
                <option value="2592000">1 Month</option>
              </select>

              Syntax Highlight:
              <select data-placeholder="None" class="form-control chosen-select" id="syntax" name="syntax">
			    <?php
				  if($edit_mode == true)
					  print '<option value="'.$row['highlight'].'">Current ('.$row['highlight'].')</option>';
				?>
			    <option value="plain">Plain</option>
			    <option value="applescript">AppleScript</option>
				<option value="as3">ActionScript3 (AS3)</option>
				<option value="bash">Bash</option>
				<option value="cf">ColdFusion</option>
				<option value="cpp">C++</option>
				<option value="csharp">C#</option>
				<option value="css">CSS</option>
				<option value="delphi">Delphi</option>
				<option value="diff">Diff</option>
				<option value="erlang">Erlang</option>
				<option value="groovy">Groovy</option>
				<option value="java">Java</option>
				<option value="javafx">JavaFX</option>
				<option value="jscript">JScript</option>
				<option value="perl">Perl</option>
				<option value="php">Php</option>
				<option value="powershell">PowerShell</option>
				<option value="python">Python</option>
				<option value="ruby">Ruby</option>
				<option value="sass">Sass</option>
				<option value="scala">Scala</option>
				<option value="sql">Sql</option>
				<option value="vb">VB</option>
				<option value="xml">Xml</option>
              </select>

              Type:
              <select class="form-control" id="exposure" name="exposure">
                <?php
				  print '<option value="0">Public</option>';
				  if($edit_mode == true && $row['exposure'] == 1)
					print '<option selected="selected" value="1">Unlisted</option>';
				  else print '<option value="1">Unlisted</option>';
				  include_once "includes/user.php";
				  $userID = -1;
		          if(isset($_COOKIE["pp_sid"]) && isset($_COOKIE["pp_skey"]))
		            $userID = GetUsersIDBySession($_COOKIE["pp_sid"],$_COOKIE["pp_skey"]);
				  if($userID==-1)
				    print '<option value="2" disabled>Private (Members only)</option>';
				  else {
					if($edit_mode === true && $row['exposure'] === 2)
					  print '<option selected="selected" value="2" >Private</option>';
				    else print '<option value="2" >Private</option>';
				  }
				?>
              </select>

    </form>


text:
package org.apache.jackrabbit.commons.iterator;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.version.VersionIterator;

import javax.jcr.version.Version;

/**
 * Implements a node iterator that takes a version iterator and returns the
 * frozen nodes of the underlying versions.
 */
public class FrozenNodeIteratorAdapter extends RangeIteratorAdapter implements NodeIterator {

    public FrozenNodeIteratorAdapter(VersionIterator iterator) {
        super(iterator);
    }

    /**
     * {@inheritDoc}
     *
     * @return the next frozen node.
     */
    public Node nextNode() {
        try {
            return ((Version) next()).getFrozenNode();
        } catch (RepositoryException e) {
            throw (IllegalStateException) new IllegalStateException(e.toString()).initCause(e);
        }
    }
}


text:
void stack_item_init( stack_item_type * item, expr_type * val, stack_item_type * prev ) {
  item->val = val;
  item->prev = prev;
}

void stack_item_denit( stack_item_type * item ) {
  expr_denit( item->val );
  item->prev = NULL;
}

void stack_init( stack_type * stack ) {
  stack->top = NULL;
  stack->size = 0;
}

int stack_push( stack_type * stack, expr_type * expr ) {
  stack_item_type * old_top = stack->top;
  // TODO: don't malloc each item; malloc arenas and allocate from the arena
  stack_item_type * new_top = malloc( sizeof( stack_item_type ) );

  if( !new_top ) {
    return 1;
  }

  stack_item_init( new_top, expr, old_top );
  stack->top = new_top;
  ++stack->size;
  return 0;
}

void stack_pop( stack_type * stack ) {
  if( stack->size == 0 ) {
    LSP_ABORT( "Can't pop empty stack!" );
  }
  stack_item_type * old_top = stack->top;
  stack->top = old_top->prev;
  stack->size--;
  stack_item_denit( old_top );
}

expr_type * stack_top( stack_type * stack ) {
  return stack->top->val;
}

size_t stack_size( stack_type * stack ) {
  return stack->size;
}

expr_type * stack_at( stack_type * stack, size_t n ) {
  stack_item_type * itr = stack->top;
  size_t i = 0;
  while( itr && i < n ) {
    itr = itr->prev;
    ++i;
  }
  if( i != n || !itr ) {
    return NULL;
  }
  return itr->val;
}


text:
<Type Name="TestBase" FullName="Hyena.Tests.TestBase">
  <TypeSignature Language="C#" Value="public abstract class TestBase" />
  <AssemblyInfo>
    <AssemblyName>Hyena</AssemblyName>
    <AssemblyVersion>1.3.1.0</AssemblyVersion>
    <AssemblyVersion>1.4.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Object</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>

    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="protected TestBase ();" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>

      <AssemblyVersion>1.3.1.0</AssemblyVersion><AssemblyVersion>1.4.0.0</AssemblyVersion></AssemblyInfo>
      <Parameters />
      <Docs>To be added.<remarks>To be added.</remarks></Docs>
    </Member><Member MemberName="AssertForEach<T>">
      <MemberSignature Language="C#" Value="public static void AssertForEach<T> (System.Collections.Generic.IEnumerable<T> objects, Action<T> runner);" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>

      <AssemblyVersion>1.3.1.0</AssemblyVersion><AssemblyVersion>1.4.0.0</AssemblyVersion></AssemblyInfo>
      <ReturnValue><ReturnType>System.Void</ReturnType></ReturnValue>
      <Parameters><Parameter Name="objects" Type="System.Collections.Generic.IEnumerable<T>" /><Parameter Name="runner" Type="System.Action<T>" /></Parameters>
      <Docs><typeparam name="T">To be added.</typeparam><param name="objects">To be added.</param><param name="runner">To be added.</param>To be added.<remarks>To be added.</remarks></Docs>
    </Member><Member MemberName="BinDir">
      <MemberSignature Language="C#" Value="public string BinDir { get; }" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>

      <AssemblyVersion>1.3.1.0</AssemblyVersion><AssemblyVersion>1.4.0.0</AssemblyVersion></AssemblyInfo>
      <ReturnValue><ReturnType>System.String</ReturnType></ReturnValue>
      <Docs>To be added.<value>To be added.</value><remarks>To be added.</remarks></Docs>
    </Member>
  </Members>
</Type>


text:
class Postgresql < Formula
  desc "Object-relational database system"
  homepage "https://www.postgresql.org/"
  url "https://ftp.postgresql.org/pub/source/v12.1/postgresql-12.1.tar.bz2"
  sha256 "a09bf3abbaf6763980d0f8acbb943b7629a8b20073de18d867aecdb7988483ed"
  head "https://github.com/postgres/postgres.git"

  bottle do
    rebuild 1
    sha256 "10d46b2d2fba43e24ad03583e3243d928c4dcf8531ded3630c9a942a1ee7e9b6" => :catalina
    sha256 "c620a1f26b954d2e27b37117dde1ce0c0b8a965879a39398ecabc8e548717fa3" => :mojave
    sha256 "6eb005a6b35c7637589733eb2ebd932d5e840023bf71322b1a609909d9035390" => :high_sierra
    sha256 "44027516c21508237a214c40f9652aca1400ca6c71324cb18aeb51a7d1f1d65f" => :x86_64_linux
  end

  depends_on "pkg-config" => :build
  depends_on "icu4c"

  # GSSAPI provided by Kerberos.framework crashes when forked.
  # See https://github.com/Homebrew/homebrew-core/issues/47494.
  depends_on "krb5"

  depends_on "openssl@1.1"
  depends_on "readline"
  uses_from_macos "libxml2"
  uses_from_macos "libxslt"
  uses_from_macos "perl"
  depends_on "util-linux" unless OS.mac? # for libuuid

  def install
    # avoid adding the SDK library directory to the linker search path
    ENV["XML2_CONFIG"] = "xml2-config --exec-prefix=/usr"

    ENV.prepend "LDFLAGS", "-L#{Formula["openssl@1.1"].opt_lib} -L#{Formula["readline"].opt_lib}"
    ENV.prepend "CPPFLAGS", "-I#{Formula["openssl@1.1"].opt_include} -I#{Formula["readline"].opt_include}"

    args = %W[
      --disable-debug
      --prefix=#{prefix}
      --datadir=#{HOMEBREW_PREFIX}/share/postgresql
      --libdir=#{HOMEBREW_PREFIX}/lib
      --includedir=#{HOMEBREW_PREFIX}/include
      --sysconfdir=#{etc}
      --docdir=#{doc}
      --enable-thread-safety
      --with-icu
      --with-libxml
      --with-libxslt
      --with-openssl
      --with-perl
      --with-uuid=e2fs
    ]
    if OS.mac?
      args += %w[
        --with-bonjour
        --with-gssapi
        --with-ldap
        --with-pam
      ]
    end

    # The CLT is required to build Tcl support on 10.7 and 10.8 because
    # tclConfig.sh is not part of the SDK
    if OS.mac?
      args << "--with-tcl"
      if File.exist?("#{MacOS.sdk_path}/System/Library/Frameworks/Tcl.framework/tclConfig.sh")
        args << "--with-tclconfig=#{MacOS.sdk_path}/System/Library/Frameworks/Tcl.framework"
      end
    end

    system "./configure", *args
    system "make"
    system "make", "install-world", "datadir=#{pkgshare}",
                                    "libdir=#{lib}",
                                    "pkglibdir=#{lib}/postgresql",
                                    "includedir=#{include}",
                                    "pkgincludedir=#{include}/postgresql",
                                    "includedir_server=#{include}/postgresql/server",
                                    "includedir_internal=#{include}/postgresql/internal"
  end

  def post_install
    (var/"log").mkpath
    (var/"postgres").mkpath
    if !Process.euid.zero? && !(File.exist? "#{var}/#{name}/PG_VERSION")
      system "#{bin}/initdb", "--locale=C", "-E", "UTF-8", "#{var}/postgres"
    end
  end

  def caveats; <<~EOS
    To migrate existing data from a previous major version of PostgreSQL run:
      brew postgresql-upgrade-database
  EOS
  end

  plist_options :manual => "pg_ctl -D #{HOMEBREW_PREFIX}/var/postgres start"

  def plist; <<~EOS
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
      <key>KeepAlive</key>
      <true/>
      <key>Label</key>
      <string>#{plist_name}</string>
      <key>ProgramArguments</key>
      <array>
        <string>#{opt_bin}/postgres</string>
        <string>-D</string>
        <string>#{var}/postgres</string>
      </array>
      <key>RunAtLoad</key>
      <true/>
      <key>WorkingDirectory</key>
      <string>#{HOMEBREW_PREFIX}</string>
      <key>StandardOutPath</key>
      <string>#{var}/log/postgres.log</string>
      <key>StandardErrorPath</key>
      <string>#{var}/log/postgres.log</string>
    </dict>
    </plist>
  EOS
  end

  test do
    system "#{bin}/initdb", testpath/"test"
    assert_equal "#{HOMEBREW_PREFIX}/share/postgresql", shell_output("#{bin}/pg_config --sharedir").chomp
    assert_equal "#{HOMEBREW_PREFIX}/lib", shell_output("#{bin}/pg_config --libdir").chomp
    assert_equal "#{HOMEBREW_PREFIX}/lib/postgresql", shell_output("#{bin}/pg_config --pkglibdir").chomp
  end
end


text:
<?php

  namespace osCommerce\OM\Core\Site\Admin\Application\TaxClasses;

  use osCommerce\OM\Core\OSCOM;

  class Controller extends \osCommerce\OM\Core\Site\Admin\ApplicationAbstract {
    protected $_group = 'configuration';
    protected $_icon = 'taxclasses.png';
    protected $_sort_order = 800;

    protected function initialize() {
      $this->_title = OSCOM::getDef('app_title');
    }

    protected function process() {
      $this->_page_title = OSCOM::getDef('heading_title');

      if ( isset($_GET['id']) && is_numeric($_GET['id']) ) {
        $this->_page_contents = 'entries.php';
        $this->_page_title .= ': ' . TaxClasses::get($_GET['id'], 'tax_class_title');
      }
    }
  }
?>


text:
social-glyph
============
CardUI:
https://github.com/virtual-dev/CardUICss

css animations:
http://daneden.github.io/animate.css/

MVC done in Angular.js
https://angularjs.org

RESTful services in RAX-RS (Jersey implementation)

JSON to Java conversion in gson:
http://code.google.com/p/google-gson

Roboto font using Google Fonts:
https://www.google.com/fonts


text:
-	[`2.1.16`, `2.1` (*2.1/Dockerfile*)](https://github.com/docker-library/cassandra/blob/4bb926527d4a9eb534508fe0bbae604dee81f40a/2.1/Dockerfile)
-	[`2.2.8`, `2.2`, `2` (*2.2/Dockerfile*)](https://github.com/docker-library/cassandra/blob/4bb926527d4a9eb534508fe0bbae604dee81f40a/2.2/Dockerfile)
-	[`3.0.10`, `3.0` (*3.0/Dockerfile*)](https://github.com/docker-library/cassandra/blob/d3a91560b21e73994235a72a4c3153e775e1654d/3.0/Dockerfile)
-	[`3.9`, `3`, `latest` (*3.9/Dockerfile*)](https://github.com/docker-library/cassandra/blob/4bb926527d4a9eb534508fe0bbae604dee81f40a/3.9/Dockerfile)

For more information about this image and its history, please see [the relevant manifest file (`library/cassandra`)](https://github.com/docker-library/official-images/blob/master/library/cassandra). This image is updated via [pull requests to the `docker-library/official-images` GitHub repo](https://github.com/docker-library/official-images/pulls?q=label%3Alibrary%2Fcassandra).

For detailed information about the virtual/transfer sizes and individual layers of each of the above supported tags, please see [the `repos/cassandra/tag-details.md` file](https://github.com/docker-library/repo-info/blob/master/repos/cassandra/tag-details.md) in [the `docker-library/repo-info` GitHub repo](https://github.com/docker-library/repo-info).

# What is Cassandra?

Apache Cassandra is an open source distributed database management system designed to handle large amounts of data across many commodity servers, providing high availability with no single point of failure. Cassandra offers robust support for clusters spanning multiple datacenters, with asynchronous masterless replication allowing low latency operations for all clients.

> [wikipedia.org/wiki/Apache_Cassandra](https://en.wikipedia.org/wiki/Apache_Cassandra)

![logo](https://raw.githubusercontent.com/docker-library/docs/fb8596d619703fc556e6d56e12584d8bfdf13785/cassandra/logo.png)

# How to use this image

## Start a `cassandra` server instance

Starting a Cassandra instance is simple:

```console
$ docker run --name some-cassandra -d cassandra:tag
```

... where `some-cassandra` is the name you want to assign to your container and `tag` is the tag specifying the Cassandra version you want. See the list above for relevant tags.

## Connect to Cassandra from an application in another Docker container

This image exposes the standard Cassandra ports (see the [Cassandra FAQ](https://wiki.apache.org/cassandra/FAQ#ports)), so container linking makes the Cassandra instance available to other application containers. Start your application container like this in order to link it to the Cassandra container:

```console
$ docker run --name some-app --link some-cassandra:cassandra -d app-that-uses-cassandra
```

## Make a cluster

Using the environment variables documented below, there are two cluster scenarios: instances on the same machine and instances on separate machines. For the same machine, start the instance as described above. To start other instances, just tell each new node where the first is.

```console
$ docker run --name some-cassandra2 -d -e CASSANDRA_SEEDS="$(docker inspect --format='{{ .NetworkSettings.IPAddress }}' some-cassandra)" cassandra:tag
```

... where `some-cassandra` is the name of your original Cassandra Server container, taking advantage of `docker inspect` to get the IP address of the other container.

Or you may use the docker run --link option to tell the new node where the first is:

```console
$ docker run --name some-cassandra2 -d --link some-cassandra:cassandra cassandra:tag
```

For separate machines (ie, two VMs on a cloud provider), you need to tell Cassandra what IP address to advertise to the other nodes (since the address of the container is behind the docker bridge).

Assuming the first machine's IP address is `10.42.42.42` and the second's is `10.43.43.43`, start the first with exposed gossip port:

```console
$ docker run --name some-cassandra -d -e CASSANDRA_BROADCAST_ADDRESS=10.42.42.42 -p 7000:7000 cassandra:tag
```

Then start a Cassandra container on the second machine, with the exposed gossip port and seed pointing to the first machine:

```console
$ docker run --name some-cassandra -d -e CASSANDRA_BROADCAST_ADDRESS=10.43.43.43 -p 7000:7000 -e CASSANDRA_SEEDS=10.42.42.42 cassandra:tag
```

## Connect to Cassandra from `cqlsh`

The following command starts another Cassandra container instance and runs `cqlsh` (Cassandra Query Language Shell) against your original Cassandra container, allowing you to execute CQL statements against your database instance:

```console
$ docker run -it --link some-cassandra:cassandra --rm cassandra sh -c 'exec cqlsh "$CASSANDRA_PORT_9042_TCP_ADDR"'
```

... or (simplified to take advantage of the `/etc/hosts` entry Docker adds for linked containers):

```console
$ docker run -it --link some-cassandra:cassandra --rm cassandra cqlsh cassandra
```

... where `some-cassandra` is the name of your original Cassandra Server container.

More information about the CQL can be found in the [Cassandra documentation](https://cassandra.apache.org/doc/cql3/CQL.html).

## Container shell access and viewing Cassandra logs

The `docker exec` command allows you to run commands inside a Docker container. The following command line will give you a bash shell inside your `cassandra` container:

```console
$ docker exec -it some-cassandra bash
```

The Cassandra Server log is available through Docker's container log:

```console
$ docker logs some-cassandra
```

## Environment Variables

When you start the `cassandra` image, you can adjust the configuration of the Cassandra instance by passing one or more environment variables on the `docker run` command line.

### `CASSANDRA_LISTEN_ADDRESS`

This variable is for controlling which IP address to listen for incoming connections on. The default value is `auto`, which will set the [`listen_address`](http://docs.datastax.com/en/cassandra/3.0/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__listen_address) option in `cassandra.yaml` to the IP address of the container as it starts. This default should work in most use cases.

### `CASSANDRA_BROADCAST_ADDRESS`

This variable is for controlling which IP address to advertise to other nodes. The default value is the value of `CASSANDRA_LISTEN_ADDRESS`. It will set the [`broadcast_address`](http://docs.datastax.com/en/cassandra/3.0/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__broadcast_address) and [`broadcast_rpc_address`](http://docs.datastax.com/en/cassandra/3.0/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__broadcast_rpc_address) options in `cassandra.yaml`.

### `CASSANDRA_RPC_ADDRESS`

This variable is for controlling which address to bind the thrift rpc server to. If you do not specify an address, the wildcard address (`0.0.0.0`) will be used. It will set the [`rpc_address`](http://docs.datastax.com/en/cassandra/3.0/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__rpc_address) option in `cassandra.yaml`.

### `CASSANDRA_START_RPC`

This variable is for controlling if the thrift rpc server is started. It will set the [`start_rpc`](http://docs.datastax.com/en/cassandra/3.0/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__start_rpc) option in `cassandra.yaml`.

### `CASSANDRA_SEEDS`

This variable is the comma-separated list of IP addresses used by gossip for bootstrapping new nodes joining a cluster. It will set the `seeds` value of the [`seed_provider`](http://docs.datastax.com/en/cassandra/3.0/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__seed_provider) option in `cassandra.yaml`. The `CASSANDRA_BROADCAST_ADDRESS` will be added the the seeds passed in so that the sever will talk to itself as well.

### `CASSANDRA_CLUSTER_NAME`

This variable sets the name of the cluster and must be the same for all nodes in the cluster. It will set the [`cluster_name`](http://docs.datastax.com/en/cassandra/3.0/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__cluster_name) option of `cassandra.yaml`.

### `CASSANDRA_NUM_TOKENS`

This variable sets number of tokens for this node. It will set the [`num_tokens`](http://docs.datastax.com/en/cassandra/3.0/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__num_tokens) option of `cassandra.yaml`.

### `CASSANDRA_DC`

This variable sets the datacenter name of this node. It will set the [`dc`](http://docs.datastax.com/en/cassandra/3.0/cassandra/architecture/archsnitchGossipPF.html) option of `cassandra-rackdc.properties`.

### `CASSANDRA_RACK`

This variable sets the rack name of this node. It will set the [`rack`](http://docs.datastax.com/en/cassandra/3.0/cassandra/architecture/archsnitchGossipPF.html) option of `cassandra-rackdc.properties`.

### `CASSANDRA_ENDPOINT_SNITCH`

This variable sets the snitch implementation this node will use. It will set the [`endpoint_snitch`](http://docs.datastax.com/en/cassandra/3.0/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__endpoint_snitch) option of `cassandra.yml`.

# Caveats

## Where to Store Data

Important note: There are several ways to store data used by applications that run in Docker containers. We encourage users of the `cassandra` images to familiarize themselves with the options available, including:

-	Let Docker manage the storage of your database data [by writing the database files to disk on the host system using its own internal volume management](https://docs.docker.com/engine/tutorials/dockervolumes/#adding-a-data-volume). This is the default and is easy and fairly transparent to the user. The downside is that the files may be hard to locate for tools and applications that run directly on the host system, i.e. outside containers.
-	Create a data directory on the host system (outside the container) and [mount this to a directory visible from inside the container](https://docs.docker.com/engine/tutorials/dockervolumes/#mount-a-host-directory-as-a-data-volume). This places the database files in a known location on the host system, and makes it easy for tools and applications on the host system to access the files. The downside is that the user needs to make sure that the directory exists, and that e.g. directory permissions and other security mechanisms on the host system are set up correctly.

The Docker documentation is a good starting point for understanding the different storage options and variations, and there are multiple blogs and forum postings that discuss and give advice in this area. We will simply show the basic procedure here for the latter option above:

1.	Create a data directory on a suitable volume on your host system, e.g. `/my/own/datadir`.
2.	Start your `cassandra` container like this:

	```console
	$ docker run --name some-cassandra -v /my/own/datadir:/var/lib/cassandra -d cassandra:tag
	```

The `-v /my/own/datadir:/var/lib/cassandra` part of the command mounts the `/my/own/datadir` directory from the underlying host system as `/var/lib/cassandra` inside the container, where Cassandra by default will write its data files.

Note that users on host systems with SELinux enabled may see issues with this. The current workaround is to assign the relevant SELinux policy type to the new data directory so that the container will be allowed to access it:

```console
$ chcon -Rt svirt_sandbox_file_t /my/own/datadir
```

## No connections until Cassandra init completes

If there is no database initialized when the container starts, then a default database will be created. While this is the expected behavior, this means that it will not accept incoming connections until such initialization completes. This may cause issues when using automation tools, such as `docker-compose`, which start several containers simultaneously.

# Supported Docker versions

This image is officially supported on Docker version 1.12.3.

Support for older versions (down to 1.6) is provided on a best-effort basis.

Please see [the Docker installation documentation](https://docs.docker.com/installation/) for details on how to upgrade your Docker daemon.

# User Feedback

## Issues

If you have any problems with or questions about this image, please contact us through a [GitHub issue](https://github.com/docker-library/cassandra/issues). If the issue is related to a CVE, please check for [a `cve-tracker` issue on the `official-images` repository first](https://github.com/docker-library/official-images/issues?q=label%3Acve-tracker).

You can also reach many of the official image maintainers via the `#docker-library` IRC channel on [Freenode](https://freenode.net).

## Contributing

You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can.

Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/docker-library/cassandra/issues), especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing.

## Documentation

Documentation for this image is stored in the [`cassandra/` directory](https://github.com/docker-library/docs/tree/master/cassandra) of the [`docker-library/docs` GitHub repo](https://github.com/docker-library/docs). Be sure to familiarize yourself with the [repository's `README.md` file](https://github.com/docker-library/docs/blob/master/README.md) before attempting a pull request.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.apache.cassandra.gms.VersionedValue (apache-cassandra API)</title>
<meta name="date" content="2016-04-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.cassandra.gms.VersionedValue

Packages that use VersionedValue

Package
Description

org.apache.cassandra.gms

org.apache.cassandra.locator

org.apache.cassandra.repair

org.apache.cassandra.service

org.apache.cassandra.streaming

Uses of VersionedValue in org.apache.cassandra.gms

Fields in org.apache.cassandra.gms with type parameters of type VersionedValue

Modifier and Type
Field and Description

static IVersionedSerializer<VersionedValue>
VersionedValue.serializer

Methods in org.apache.cassandra.gms that return VersionedValue

Modifier and Type
Method and Description

VersionedValue
VersionedValue.VersionedValueFactory.bootstrapping(java.util.Collection<Token> tokens)

VersionedValue
VersionedValue.VersionedValueFactory.cloneWithHigherVersion(VersionedValue value)

VersionedValue
VersionedValue.VersionedValueFactory.datacenter(java.lang.String dcId)

VersionedValue
EndpointState.getApplicationState(ApplicationState key)

VersionedValue
VersionedValue.VersionedValueFactory.hibernate(boolean value)

VersionedValue
VersionedValue.VersionedValueFactory.hostId(java.util.UUID hostId)

VersionedValue
VersionedValue.VersionedValueFactory.internalIP(java.lang.String private_ip)

VersionedValue
VersionedValue.VersionedValueFactory.leaving(java.util.Collection<Token> tokens)

VersionedValue
VersionedValue.VersionedValueFactory.left(java.util.Collection<Token> tokens,
    long expireTime)

VersionedValue
VersionedValue.VersionedValueFactory.load(double load)

VersionedValue
VersionedValue.VersionedValueFactory.moving(Token token)

VersionedValue
VersionedValue.VersionedValueFactory.networkVersion()

VersionedValue
VersionedValue.VersionedValueFactory.normal(java.util.Collection<Token> tokens)

VersionedValue
VersionedValue.VersionedValueFactory.rack(java.lang.String rackId)

VersionedValue
VersionedValue.VersionedValueFactory.releaseVersion()

VersionedValue
VersionedValue.VersionedValueFactory.removalCoordinator(java.util.UUID hostId)

VersionedValue
VersionedValue.VersionedValueFactory.removedNonlocal(java.util.UUID hostId,
               long expireTime)

VersionedValue
VersionedValue.VersionedValueFactory.removingNonlocal(java.util.UUID hostId)

VersionedValue
VersionedValue.VersionedValueFactory.rpcaddress(java.net.InetAddress endpoint)

VersionedValue
VersionedValue.VersionedValueFactory.rpcReady(boolean value)

VersionedValue
VersionedValue.VersionedValueFactory.schema(java.util.UUID newVersion)

VersionedValue
VersionedValue.VersionedValueFactory.severity(double value)

VersionedValue
VersionedValue.VersionedValueFactory.shutdown(boolean value)

VersionedValue
VersionedValue.VersionedValueFactory.tokens(java.util.Collection<Token> tokens)

Methods in org.apache.cassandra.gms that return types with arguments of type VersionedValue

Modifier and Type
Method and Description

java.util.Set<java.util.Map.Entry<ApplicationState,VersionedValue>>
EndpointState.states()

Methods in org.apache.cassandra.gms with parameters of type VersionedValue

Modifier and Type
Method and Description

void
EndpointState.addApplicationState(ApplicationState key,
                   VersionedValue value)

void
Gossiper.addLocalApplicationState(ApplicationState applicationState,
                        VersionedValue value)

void
IEndpointStateChangeSubscriber.beforeChange(java.net.InetAddress endpoint,
            EndpointState currentState,
            ApplicationState newStateKey,
            VersionedValue newValue)

VersionedValue
VersionedValue.VersionedValueFactory.cloneWithHigherVersion(VersionedValue value)

int
VersionedValue.compareTo(VersionedValue value)

void
Gossiper.injectApplicationState(java.net.InetAddress endpoint,
                      ApplicationState state,
                      VersionedValue value)

void
IEndpointStateChangeSubscriber.onChange(java.net.InetAddress endpoint,
        ApplicationState state,
        VersionedValue value)

Method parameters in org.apache.cassandra.gms with type arguments of type VersionedValue

Modifier and Type
Method and Description

void
EndpointState.addApplicationStates(java.util.Map<ApplicationState,VersionedValue> values)

void
EndpointState.addApplicationStates(java.util.Set<java.util.Map.Entry<ApplicationState,VersionedValue>> values)

void
Gossiper.addLocalApplicationStates(java.util.List<Pair<ApplicationState,VersionedValue>> states)

void
Gossiper.start(int generationNbr,
     java.util.Map<ApplicationState,VersionedValue> preloadLocalStates)

Start the gossiper with the generation number, preloading the map of application states before starting

Uses of VersionedValue in org.apache.cassandra.locator

Methods in org.apache.cassandra.locator with parameters of type VersionedValue

Modifier and Type
Method and Description

void
ReconnectableSnitchHelper.beforeChange(java.net.InetAddress endpoint,
            EndpointState currentState,
            ApplicationState newStateKey,
            VersionedValue newValue)

void
ReconnectableSnitchHelper.onChange(java.net.InetAddress endpoint,
        ApplicationState state,
        VersionedValue value)

Uses of VersionedValue in org.apache.cassandra.repair

Methods in org.apache.cassandra.repair with parameters of type VersionedValue

Modifier and Type
Method and Description

void
RepairSession.beforeChange(java.net.InetAddress endpoint,
            EndpointState currentState,
            ApplicationState newStateKey,
            VersionedValue newValue)

void
RepairSession.onChange(java.net.InetAddress endpoint,
        ApplicationState state,
        VersionedValue value)

Uses of VersionedValue in org.apache.cassandra.service

Methods in org.apache.cassandra.service with parameters of type VersionedValue

Modifier and Type
Method and Description

void
LoadBroadcaster.beforeChange(java.net.InetAddress endpoint,
            EndpointState currentState,
            ApplicationState newStateKey,
            VersionedValue newValue)

void
StorageService.beforeChange(java.net.InetAddress endpoint,
            EndpointState currentState,
            ApplicationState newStateKey,
            VersionedValue newValue)

void
LoadBroadcaster.onChange(java.net.InetAddress endpoint,
        ApplicationState state,
        VersionedValue value)

void
StorageService.onChange(java.net.InetAddress endpoint,
        ApplicationState state,
        VersionedValue value)

Uses of VersionedValue in org.apache.cassandra.streaming

Methods in org.apache.cassandra.streaming with parameters of type VersionedValue

Modifier and Type
Method and Description

void
StreamSession.beforeChange(java.net.InetAddress endpoint,
            EndpointState currentState,
            ApplicationState newStateKey,
            VersionedValue newValue)

void
StreamSession.onChange(java.net.InetAddress endpoint,
        ApplicationState state,
        VersionedValue value)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016 The Apache Software Foundation


text:
package com.facebook.react.bridge;

/**
 * Listener for receiving activity lifecycle events.
 *
 *
When multiple activities share a react instance, only the most recent one's lifecycle events
 * get forwarded to listeners. Consider the following scenarios:
 *
 *

 *
Navigating from Activity A to B will trigger two events: A#onHostPause and B#onHostResume.
 *       Any subsequent lifecycle events coming from Activity A, such as onHostDestroy, will be
 *       ignored.
 *
Navigating back from Activity B to Activity A will trigger the same events: B#onHostPause
 *       and A#onHostResume. Any subsequent events coming from Activity B, such as onHostDestroy,
 *       are ignored.
 *
Navigating back from Activity A to a non-React Activity or to the home screen will trigger
 *       two events: onHostPause and onHostDestroy.
 *
Navigating from Activity A to a non-React Activity B will trigger one event: onHostPause.
 *       Later, if Activity A is destroyed (e.g. because of resource contention), onHostDestroy is
 *       triggered.
 *

 */
public interface LifecycleEventListener {

  /**
   * Called either when the host activity receives a resume event (e.g. {@link Activity#onResume} or
   * if the native module that implements this is initialized while the host activity is already
   * resumed. Always called for the most current activity.
   */
  void onHostResume();

  /**
   * Called when host activity receives pause event (e.g. {@link Activity#onPause}. Always called
   * for the most current activity.
   */
  void onHostPause();

  /**
   * Called when host activity receives destroy event (e.g. {@link Activity#onDestroy}. Only called
   * for the last React activity to be destroyed.
   */
  void onHostDestroy();
}


text:
import numpy as np
import scipy as sp
import scipy.interpolate
import requests
from io import StringIO

def qvalues(pv, m = None, verbose = False, lowmem = False, pi0 = None):
    """
    Copyright (c) 2012, Nicolo Fusi, University of Sheffield
    All rights reserved.

    Estimates q-values from p-values

    Args
    =====

    m: number of tests. If not specified m = pv.size
    verbose: print verbose messages? (default False)
    lowmem: use memory-efficient in-place algorithm
    pi0: if None, it's estimated as suggested in Storey and Tibshirani, 2003.
         For most GWAS this is not necessary, since pi0 is extremely likely to be
         1

    :param pv:
    :param m:
    :param verbose:
    :param lowmem:
    :param pi0:
    :return:
    """

    assert(pv.min() >= 0 and pv.max() <= 1), "p-values should be between 0 and 1"

    original_shape = pv.shape
    pv = pv.ravel() # flattens the array in place, more efficient than flatten()

    if m == None:
        m = float(len(pv))
    else:
        # the user has supplied an m
        m *= 1.0

    # if the number of hypotheses is small, just set pi0 to 1
    if len(pv) < 100 and pi0 == None:
        pi0 = 1.0
    elif pi0 != None:
        pi0 = pi0
    else:
        # evaluate pi0 for different lambdas
        pi0 = []
        lam = sp.arange(0, 0.90, 0.01)
        counts = sp.array([(pv > i).sum() for i in sp.arange(0, 0.9, 0.01)])

        for l in range(len(lam)):
            pi0.append(counts[l]/(m*(1-lam[l])))

        pi0 = sp.array(pi0)

        # fit natural cubic spline
        tck = sp.interpolate.splrep(lam, pi0, k = 3)
        pi0 = sp.interpolate.splev(lam[-1], tck)

        if pi0 > 1:
            if verbose:
                print("got pi0 > 1 (%.3f) while estimating qvalues, setting it to 1" % pi0)

            pi0 = 1.0

    assert(pi0 >= 0 and pi0 <= 1), "pi0 is not between 0 and 1: %f" % pi0

    if lowmem:
        # low memory version, only uses 1 pv and 1 qv matrices
        qv = sp.zeros((len(pv),))
        last_pv = pv.argmax()
        qv[last_pv] = (pi0*pv[last_pv]*m)/float(m)
        pv[last_pv] = -sp.inf
        prev_qv = last_pv
        for i in range(int(len(pv))-2, -1, -1):
            cur_max = pv.argmax()
            qv_i = (pi0*m*pv[cur_max]/float(i+1))
            pv[cur_max] = -sp.inf
            qv_i1 = prev_qv
            qv[cur_max] = min(qv_i, qv_i1)
            prev_qv = qv[cur_max]

    else:
        p_ordered = sp.argsort(pv)
        pv = pv[p_ordered]
        qv = pi0 * m/len(pv) * pv
        qv[-1] = min(qv[-1],1.0)

        for i in range(len(pv)-2, -1, -1):
            qv[i] = min(pi0*m*pv[i]/(i+1.0), qv[i+1])

        # reorder qvalues
        qv_temp = qv.copy()
        qv = sp.zeros_like(qv)
        qv[p_ordered] = qv_temp

        # reshape qvalues
        qv = qv.reshape(original_shape)

    return qv

def get_protein_id(s):
    """
    Return a shortened string, split on spaces, underlines and semicolons.

    Extract the first, highest-ranked protein ID from a string containing
    protein IDs in MaxQuant output format: e.g. P07830;P63267;Q54A44;P63268

    Long names (containing species information) are eliminated (split on ' ') and
    isoforms are removed (split on '_').

    :param s:  protein IDs in MaxQuant format
    :type s: str or unicode
    :return: string
    """
    return str(s).split(';')[0].split(' ')[0].split('_')[0]

def get_protein_ids(s):
    """
    Return a list of shortform protein IDs.

    Extract all protein IDs from a string containing
    protein IDs in MaxQuant output format: e.g. P07830;P63267;Q54A44;P63268

    Long names (containing species information) are eliminated (split on ' ') and
    isoforms are removed (split on '_').

    :param s:  protein IDs in MaxQuant format
    :type s: str or unicode
    :return: list of string ids
    """
    return [p.split(' ')[0].split('_')[0]  for p in s.split(';') ]

def get_protein_id_list(df, level=0):
    """
    Return a complete list of shortform IDs from a DataFrame

    Extract all protein IDs from a dataframe from multiple rows containing
    protein IDs in MaxQuant output format: e.g. P07830;P63267;Q54A44;P63268

    Long names (containing species information) are eliminated (split on ' ') and
    isoforms are removed (split on '_').

    :param df: DataFrame
    :type df: pandas.DataFrame
    :param level: Level of DataFrame index to extract IDs from
    :type level: int or str
    :return: list of string ids
    """
    protein_list = []
    for s in df.index.get_level_values(level):
        protein_list.extend( get_protein_ids(s) )

    return list(set(protein_list))

def get_shortstr(s):
    """
    Return the first part of a string before a semicolon.

    Extract the first, highest-ranked protein ID from a string containing
    protein IDs in MaxQuant output format: e.g. P07830;P63267;Q54A44;P63268

    :param s:  protein IDs in MaxQuant format
    :type s: str or unicode
    :return: string
    """
    return str(s).split(';')[0]

def get_index_list(l, ms):
    """

    :param l:
    :param ms:
    :return:
    """
    if type(ms) != list and type(ms) != tuple:
        ms = [ms]
    return [l.index(s) for s in ms if s in l]

def format_label(sl, fmt=None):
    """
    Combine a list of strings to a single str, joined by sep.
    Passes through single strings.
    :param sl:
    :return:
    """
    if isinstance(sl, str):
        # Already is a string.
        return sl

    if fmt:
        return fmt.format(*sl)

    return ' '.join(str(s) for s in sl)

def build_combined_label(sl, idxs, sep=' ', label_format=None):
    """
    Generate a combined label from a list of indexes
    into sl, by joining them with `sep` (str).

    :param sl: Strings to combine
    :type sl: dict of str
    :param idxs: Indexes into sl
    :type idxs: list of sl keys
    :param sep:

    :return: `str` of combined label
    """

    if label_format:
        return label_format % tuple([get_shortstr(str(sl[n])) for n in idxs])
    else:
        return sep.join([get_shortstr(str(sl[n])) for n in idxs])

def hierarchical_match(d, k, default=None):
    """
    Match a key against a dict, simplifying element at a time

    :param df: DataFrame
    :type df: pandas.DataFrame
    :param level: Level of DataFrame index to extract IDs from
    :type level: int or str
    :return: hiearchically matched value or default
    """
    if d is None:
        return default

    if type(k) != list and type(k) != tuple:
        k = [k]

    for n, _ in enumerate(k):
        key = tuple(k[0:len(k)-n])
        if len(key) == 1:
            key = key[0]

        try:
            d[key]
        except:
            pass
        else:
            return d[key]
    return default

def chunks(seq, num):
    """
    Separate `seq` (`np.array`) into `num` series of as-near-as possible equal
    length values.

    :param seq: Sequence to split
    :type seq: np.array
    :param num: Number of parts to split sequence into
    :type num: int
    :return: np.array of split parts
    """

    avg = len(seq) / float(num)
    out = []
    last = 0.0

    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg

    return np.array(out)

def calculate_s0_curve(s0, minpval, maxpval, minratio, maxratio, curve_interval=0.1):
    """
    Calculate s0 curve for volcano plot.

    Taking an min and max p value, and a min and max ratio, calculate an smooth
    curve starting from parameter `s0` in each direction.

    The `curve_interval` parameter defines the smoothness of the resulting curve.

    :param s0: `float` offset of curve from interset
    :param minpval: `float` minimum p value
    :param maxpval: `float` maximum p value
    :param minratio: `float` minimum ratio
    :param maxratio: `float` maximum ratio
    :param curve_interval: `float` stepsize (smoothness) of curve generator
    :return: x, y, fn  x,y points of curve, and fn generator
    """

    mminpval = -np.log10(minpval)
    mmaxpval = -np.log10(maxpval)
    maxpval_adjust = mmaxpval - mminpval

    ax0 = (s0 + maxpval_adjust * minratio) / maxpval_adjust
    edge_offset = (maxratio-ax0) % curve_interval
    max_x = maxratio-edge_offset

    if (max_x > ax0):
        x = np.arange(ax0, max_x, curve_interval)
    else:
        x = np.arange(max_x, ax0, curve_interval)

    fn = lambda x: 10 ** (-s0/(x-minratio) - mminpval)
    y = fn(x)

    return x, y, fn

def find_nearest_idx(array,value):
    """

    :param array:
    :param value:
    :return:
    """
    array = array.copy()
    array[np.isnan(array)] = 1
    idx = (np.abs(array-value)).argmin()
    return idx

def get_uniprot_id_mapping_pairs(f, t, seqids):

    r = requests.post(
        'https://www.uniprot.org/uploadlists/',
        files={'file': StringIO(' '.join(seqids))},
        params={
            'from': 'ACC+ID',
            'to': 'KEGG_ID',
            'format': 'tab',
        },
        headers={'User-Agent': 'Python / padua - martin.fitzpatrick@gmail.com'}
    )
    result = {}

    if r.text and 'html' not in r.text[:500].lower():
        # Looks legitimate data.
        lines = r.text.splitlines()
        for line in lines[1:]:
            key, value = line.split('\t')
            if key in result:
                result[key].add(value)
            else:
                result[key] = set([value])

    return result


text:
<?php

namespace ItePHP\Core;

/**
 * Throw when service not found.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class ServiceNotFoundException extends Exception{

	/**
	 * Constructor.
	 *
	 * @param string $service
	 */
	public function __construct($service){
		parent::__construct(5,'Service "'.$service.'" not found.','Internal server error.');
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>BKFAbstractType (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

org.apache.poi.hwpf.model.types

Class BKFAbstractType

java.lang.Object

org.apache.poi.hwpf.model.types.BKFAbstractType

Direct Known Subclasses:

BookmarkFirstDescriptor

@Internal
public abstract class BKFAbstractType
extends java.lang.Object

BooKmark First descriptor (BKF).

 Class and fields descriptions are quoted from Microsoft Office Word 97-2007
 Binary File Format (.doc) Specification

 NOTE: This source is automatically generated please do not modify this file.
 Either subclass or remove the record in src/types/definitions.

Author:

Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary
         File Format (.doc) Specification

Field Summary

Fields

Modifier and Type
Field and Description

protected short
field_1_ibkl

protected short
field_2_bkf_flags

Constructor Summary

Constructors

Modifier
Constructor and Description

protected
BKFAbstractType()

Method Summary

Methods

Modifier and Type
Method and Description

protected void
fillFields(byte[] data,
          int offset)

short
getBkf_flags()

Get the bkf_flags field for the BKF record.

short
getIbkl()

Index to BKL entry in plcfbkl that describes the ending position of this bookmark in the CP stream.

byte
getItcFirst()

When bkf.fCol==1, this is the index to the first column of a table column bookmark

byte
getItcLim()

When bkf.fCol==1, this is the index to limit column of a table column bookmark

static int
getSize()

Size of record

boolean
isFCol()

When 1, this bookmark marks a range of columns in a table specified by (bkf.itcFirst, bkf.itcLim)

boolean
isFPub()

When 1, this indicates that this bookmark is marking the range of a Macintosh Publisher section

void
serialize(byte[] data,
         int offset)

void
setBkf_flags(short field_2_bkf_flags)

Set the bkf_flags field for the BKF record.

void
setFCol(boolean value)

Sets the fCol field value.

void
setFPub(boolean value)

Sets the fPub field value.

void
setIbkl(short field_1_ibkl)

Index to BKL entry in plcfbkl that describes the ending position of this bookmark in the CP stream.

void
setItcFirst(byte value)

Sets the itcFirst field value.

void
setItcLim(byte value)

Sets the itcLim field value.

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

field_1_ibkl

protected short field_1_ibkl

field_2_bkf_flags

protected short field_2_bkf_flags

Constructor Detail

BKFAbstractType

protected BKFAbstractType()

Method Detail

fillFields

protected void fillFields(byte[] data,
              int offset)

serialize

public void serialize(byte[] data,
             int offset)

getSize

public static int getSize()

Size of record

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

getIbkl

public short getIbkl()

Index to BKL entry in plcfbkl that describes the ending position of this bookmark in the CP stream.

setIbkl

public void setIbkl(short field_1_ibkl)

Index to BKL entry in plcfbkl that describes the ending position of this bookmark in the CP stream.

getBkf_flags

public short getBkf_flags()

Get the bkf_flags field for the BKF record.

setBkf_flags

public void setBkf_flags(short field_2_bkf_flags)

Set the bkf_flags field for the BKF record.

setItcFirst

public void setItcFirst(byte value)

Sets the itcFirst field value.
 When bkf.fCol==1, this is the index to the first column of a table column bookmark

getItcFirst

public byte getItcFirst()

When bkf.fCol==1, this is the index to the first column of a table column bookmark

Returns:

the itcFirst field value.

setFPub

public void setFPub(boolean value)

Sets the fPub field value.
 When 1, this indicates that this bookmark is marking the range of a Macintosh Publisher section

isFPub

public boolean isFPub()

When 1, this indicates that this bookmark is marking the range of a Macintosh Publisher section

Returns:

the fPub field value.

setItcLim

public void setItcLim(byte value)

Sets the itcLim field value.
 When bkf.fCol==1, this is the index to limit column of a table column bookmark

getItcLim

public byte getItcLim()

When bkf.fCol==1, this is the index to limit column of a table column bookmark

Returns:

the itcLim field value.

setFCol

public void setFCol(boolean value)

Sets the fCol field value.
 When 1, this bookmark marks a range of columns in a table specified by (bkf.itcFirst, bkf.itcLim)

isFCol

public boolean isFCol()

When 1, this bookmark marks a range of columns in a table specified by (bkf.itcFirst, bkf.itcLim)

Returns:

the fCol field value.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

                Copyright 2016 The Apache Software Foundation or
        its licensors, as applicable.


text:
<?php
session_start();
/*Display what is in the _POST*/
/*
echo '
Display full contents of the _POST:
';
var_dump($_POST); */
if ( !empty($_POST)) {
// Store data from html form POST action into variables
$NewNav = $_POST['NewNav'];
$_SESSION['CurNav'] = $NewNav;
echo "New Nav: ".$NewNav;
/*Forward User Back to Main View*/
header("Location: index.php");
}
?>


text:
import {checkData} from '../../src/3p';

/**
 * @param {!Window} global
 * @param {!Object} data
 */
export function adsense(global, data) {
  checkData(data, ['adClient', 'adSlot']);
  if (global.context.clientId) {
    // Read by GPT for GA/GPT integration.
    global.gaGlobal = {
      vid: global.context.clientId,
      hid: global.context.pageViewId,
    };
  }
  const s = global.document.createElement('script');
  s.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
  global.document.body.appendChild(s);

  const i = global.document.createElement('ins');
  i.setAttribute('data-ad-client', data['adClient']);
  if (data['adSlot']) {
    i.setAttribute('data-ad-slot', data['adSlot']);
  }
  i.setAttribute('data-page-url', global.context.canonicalUrl);
  i.setAttribute('class', 'adsbygoogle');
  i.style.cssText = 'display:inline-block;width:100%;height:100%;';
  global.document.getElementById('c').appendChild(i);
  (global.adsbygoogle = global.adsbygoogle || []).push({});
}


text:
package com.devicehive.service;

import com.devicehive.configuration.Constants;
import com.devicehive.configuration.Messages;
import com.devicehive.dao.NetworkDao;
import com.devicehive.dao.UserDao;
import com.devicehive.exceptions.HiveException;
import com.devicehive.exceptions.InvalidPrincipalException;
import com.devicehive.model.enums.UserStatus;
import com.devicehive.service.configuration.ConfigurationService;
import com.devicehive.service.helpers.PasswordProcessor;
import com.devicehive.service.time.TimestampService;
import com.devicehive.util.HiveValidator;
import com.devicehive.vo.NetworkVO;
import com.devicehive.vo.NetworkWithUsersAndDevicesVO;
import com.devicehive.vo.UserVO;
import com.devicehive.vo.UserWithDeviceTypeVO;
import com.devicehive.vo.UserWithNetworkVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.Objects;
import java.util.Optional;

import static java.util.Optional.empty;
import static java.util.Optional.of;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;

/**
 * This class serves all requests to database from controller.
 */
@Component
public class BaseUserService {

    private static final Logger logger = LoggerFactory.getLogger(BaseUserService.class);

    protected final PasswordProcessor passwordService;
    protected final UserDao userDao;
    protected final NetworkDao networkDao;
    protected final TimestampService timestampService;
    protected final ConfigurationService configurationService;
    protected final HiveValidator hiveValidator;

    @Autowired
    public BaseUserService(PasswordProcessor passwordService,
                       UserDao userDao,
                       NetworkDao networkDao,
                       TimestampService timestampService,
                       ConfigurationService configurationService,
                       HiveValidator hiveValidator) {
        this.passwordService = passwordService;
        this.userDao = userDao;
        this.networkDao = networkDao;
        this.timestampService = timestampService;
        this.configurationService = configurationService;
        this.hiveValidator = hiveValidator;
    }

    @Transactional(noRollbackFor = InvalidPrincipalException.class)
    public UserVO getActiveUser(String login, String password) {
        Optional<UserVO> userOpt = userDao.findByName(login);
        if (!userOpt.isPresent()) {
            logger.error("Can't find user with login {} and password {}", login, password);
            throw new InvalidPrincipalException(String.format(Messages.USER_LOGIN_NOT_FOUND, login));
        } else if (userOpt.get().getStatus() != UserStatus.ACTIVE) {
            logger.error("User with login {} is not active", login);
            throw new InvalidPrincipalException(Messages.USER_NOT_ACTIVE);
        }
        return checkPassword(userOpt.get(), password)
                .orElseThrow(() -> new InvalidPrincipalException(String.format(Messages.INCORRECT_CREDENTIALS, login)));
    }

    /**
     * Retrieves user by id (no networks fetched in this case)
     *
     * @param id user id
     * @return User model without networks, or null if there is no such user
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public UserVO findById(@NotNull long id) {
        return userDao.find(id);
    }

    /**
     * Retrieves user with networks by id, if there is no networks user has
     * access to networks will be represented by empty set
     *
     * @param id user id
     * @return User model with networks, or null, if there is no such user
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public UserWithNetworkVO findUserWithNetworks(@NotNull long id) {
        return userDao.getWithNetworksById(id);
    }

    /**
     * Retrieves user with device types by id, if there is no device types user has
     * access to device types will be represented by empty set
     *
     * @param id user id
     * @return User model with device types, or null, if there is no such user
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public UserWithDeviceTypeVO findUserWithDeviceType(@NotNull long id) {
        return userDao.getWithDeviceTypeById(id);
    }

    @Transactional
    public UserVO refreshUserLoginData(UserVO user) {
        hiveValidator.validate(user);
        final long loginTimeout = configurationService.getLong(Constants.LAST_LOGIN_TIMEOUT, Constants.LAST_LOGIN_TIMEOUT_DEFAULT);
        return updateStatisticOnSuccessfulLogin(user, loginTimeout);
    }

    protected Optional<UserVO> checkPassword(UserVO user, String password) {
        boolean validPassword = passwordService.checkPassword(password, user.getPasswordSalt(), user.getPasswordHash());

        long loginTimeout = configurationService.getLong(Constants.LAST_LOGIN_TIMEOUT, Constants.LAST_LOGIN_TIMEOUT_DEFAULT);
        boolean mustUpdateLoginStatistic = user.getLoginAttempts() != 0
                || user.getLastLogin() == null
                || timestampService.getTimestamp() - user.getLastLogin().getTime() > loginTimeout;

        if (validPassword && mustUpdateLoginStatistic) {
            UserVO user1 = updateStatisticOnSuccessfulLogin(user, loginTimeout);
            return of(user1);
        } else if (!validPassword) {
            user.setLoginAttempts(user.getLoginAttempts() + 1);
            if (user.getLoginAttempts()
                    >= configurationService.getInt(Constants.MAX_LOGIN_ATTEMPTS, Constants.MAX_LOGIN_ATTEMPTS_DEFAULT)) {
                user.setStatus(UserStatus.LOCKED_OUT);
                logger.info("User with login {} has been locked out after {} login attempts.", user.getLogin(), user.getLoginAttempts());
                user.setLoginAttempts(0);
            }
            userDao.merge(user);
            return empty();
        }
        return of(user);
    }

    private UserVO updateStatisticOnSuccessfulLogin(UserVO user, long loginTimeout) {
        boolean update = false;
        if (user.getLoginAttempts() != 0) {
            update = true;
            user.setLoginAttempts(0);
        }
        if (user.getLastLogin() == null || timestampService.getTimestamp() - user.getLastLogin().getTime() > loginTimeout) {
            update = true;
            user.setLastLogin(timestampService.getDate());
        }
        return update ? userDao.merge(user) : user;
    }

    /**
     * Allows user access to given network
     *
     * @param userId id of user
     * @param networkId id of network
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void assignNetwork(@NotNull long userId, @NotNull long networkId) {
        UserVO existingUser = userDao.find(userId);
        if (existingUser == null) {
            logger.error("Can't assign network with id {}: user {} not found", networkId, userId);
            throw new HiveException(String.format(Messages.USER_NOT_FOUND, userId), NOT_FOUND.getStatusCode());
        }
        NetworkWithUsersAndDevicesVO existingNetwork = networkDao.findWithUsers(networkId).orElse(null);
        if (Objects.isNull(existingNetwork)) {
            throw new HiveException(String.format(Messages.NETWORK_NOT_FOUND, networkId), NOT_FOUND.getStatusCode());
        }

        networkDao.assignToNetwork(existingNetwork, existingUser);
    }

    /**
     * Revokes user access to given network
     *
     * @param userId id of user
     * @param networkId id of network
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void unassignNetwork(@NotNull long userId, @NotNull long networkId) {
        UserVO existingUser = userDao.find(userId);
        if (existingUser == null) {
            logger.error("Can't unassign network with id {}: user {} not found", networkId, userId);
            throw new HiveException(String.format(Messages.USER_NOT_FOUND, userId), NOT_FOUND.getStatusCode());
        }
        NetworkVO existingNetwork = networkDao.find(networkId);
        if (existingNetwork == null) {
            logger.error("Can't unassign user with id {}: network {} not found", userId, networkId);
            throw new HiveException(String.format(Messages.NETWORK_NOT_FOUND, networkId), NOT_FOUND.getStatusCode());
        }
        userDao.unassignNetwork(existingUser, networkId);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
    <preConditions>
            <dbms type="derby"/>
    </preConditions>

    <changeSet id="1" author="nvoxland">
        <createTable tableName="news">
            <column name="id" type="int" autoIncrement="true">
                <constraints primaryKey="true" nullable="false"/>
            </column>
            <column name="title" type="varchar(50)"/>
        </createTable>
    </changeSet>

    <changeSet id="2" author="nvoxland" context="test">
        <insert tableName="news">
            <column name="title" value="Liquibase 0.8 Released"/>
        </insert>
        <insert tableName="news">
            <column name="title" value="Liquibase 0.9 Released"/>
        </insert>
    </changeSet>

    <changeSet id="3" author="nvoxland" context="demo">
        <insert tableName="news">
            <column name="title" value="Liquibase 1.0 Released"/>
        </insert>
    </changeSet>
</databaseChangeLog>


text:
""" Node tree example. """

# Standard library imports.
import os, sys

# Put the Enthought library on the Python path.
sys.path.append(os.path.abspath(r'..\..\..'))

# Enthought library imports.
from pyface.api import GUI, PythonShell, SplitApplicationWindow
from traits.api import Float, Str

# Local imports.
from file_node_tree import node_manager
from pyface.tree.api import NodeTree, NodeTreeModel

class MainWindow(SplitApplicationWindow):
    """ The main application window. """

    #### 'SplitApplicationWindow' interface ###################################

    # The ratio of the size of the left/top pane to the right/bottom pane.
    ratio = Float(0.3)

    # The direction in which the window is split.
    direction = Str('vertical')

    ###########################################################################
    # Protected 'SplitApplicationWindow' interface.
    ###########################################################################

    def _create_lhs(self, parent):
        """ Creates the left hand side or top depending on the split. """

        model = NodeTreeModel(node_manager=node_manager)
        model.root = os.path.abspath(os.curdir)

        self._tree = NodeTree(parent, model=model)
        self._tree.on_trait_change(self._on_tree_anytrait_changed)

        return self._tree.control

    def _create_rhs(self, parent):
        """ Creates the right hand side or bottom depending on the split. """

        self._python_shell = PythonShell(parent)
        self._python_shell.bind('widget', self._tree)
        self._python_shell.bind('w', self._tree)

        return self._python_shell.control

    ###########################################################################
    # Private interface.
    ###########################################################################

    #### Trait event handlers #################################################

    def _on_tree_anytrait_changed(self, tree, trait_name, old, new):
        """ Called when any trait on the tree has changed. """

        print 'trait', trait_name, 'value', new

        return

# Application entry point.
if __name__ == '__main__':
    # Create the GUI (this does NOT start the GUI event loop).
    gui = GUI()

    # Create and open the main window.
    window = MainWindow()
    window.open()

    # Start the GUI event loop.
    gui.start_event_loop()

##### EOF #####################################################################


text:
package com.gizwits.opensource.appkit.ConfigModule;

import java.util.ArrayList;
import java.util.List;
import com.gizwits.opensource.appkit.CommonModule.GosDeploy;
import com.gizwits.opensource.appkit.ConfigModule.GosModeListActivity.ModeListAdapter;
import com.gizwits.opensource.appkit.utils.NetUtils;
import com.gizwits.opensource.smartlight.R;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

@SuppressLint("InflateParams")
public class GosAirlinkChooseDeviceWorkWiFiActivity extends GosConfigModuleBaseActivity implements OnClickListener {

	private AlertDialog create;
	private ArrayList<ScanResult> wifiList;

	/** wifi信息 */
	public WifiInfo wifiInfo;

	/** The et SSID */
	private EditText etSSID;

	/** The et Psw */
	private EditText etPsw;

	/** The btn Next */
	private Button btnNext;

	/** The ll ChooseMode */
	private LinearLayout llChooseMode;

	/** The cb Laws */
	private CheckBox cbLaws;

	/** The tv Mode */
	private TextView tvMode;

	/** The img WiFiList */
	private ImageView imgWiFiList;

	/** 配置用参数 */
	private String workSSID, workSSIDPsw;

	/** The data */
	List<String> modeList;

	/** The Adapter */
	ModeListAdapter modeListAdapter;

	/** The modeNum */
	static int modeNum = 4;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gos_airlink_choose_device_workwifi);
		// 设置ActionBar
		String title = getString(R.string.add_device) + GosDeploy.setAddDeviceTitle();
		setActionBar(true, true, title);

		initData();
		initView();
		ininEvent();
	}

	@Override
	protected void onResume() {
		super.onResume();

		tvMode.setText(modeList.get(modeNum));
		// 预设workSSID && workSSIDPsw
		if (!TextUtils.isEmpty(workSSID)) {
			etSSID.setText(workSSID);
			if (checkworkSSIDUsed(workSSID)) {
				if (!TextUtils.isEmpty(spf.getString("workSSIDPsw", ""))) {
					etPsw.setText(spf.getString("workSSIDPsw", ""));
				}
			}
		} else {
			etSSID.setText(NetUtils.getCurentWifiSSID(this));
		}
	}

	private void initView() {
		tvMode = (TextView) findViewById(R.id.tvMode);
		etSSID = (EditText) findViewById(R.id.etSSID);
		etPsw = (EditText) findViewById(R.id.etPsw);
		cbLaws = (CheckBox) findViewById(R.id.cbLaws);
		btnNext = (Button) findViewById(R.id.btnNext);
		llChooseMode = (LinearLayout) findViewById(R.id.llChooseMode);
		imgWiFiList = (ImageView) findViewById(R.id.imgWiFiList);

		// 配置文件部署
		btnNext.setBackgroundDrawable(GosDeploy.setButtonBackgroundColor());
		btnNext.setTextColor(GosDeploy.setButtonTextColor());
		llChooseMode.setVisibility(GosDeploy.setModuleSelectOn());
	}

	private void ininEvent() {
		btnNext.setOnClickListener(this);
		imgWiFiList.setOnClickListener(this);
		llChooseMode.setOnClickListener(this);

		cbLaws.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				String psw = etPsw.getText().toString();

				if (isChecked) {
					etPsw.setInputType(0x90);
				} else {
					etPsw.setInputType(0x81);
				}
				etPsw.setSelection(psw.length());
			}
		});
	}

	private void initData() {
		workSSID = spf.getString("workSSID", "");

		modeList = new ArrayList<String>();
		String[] modes = this.getResources().getStringArray(R.array.mode);
		for (String string : modes) {
			modeList.add(string);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnNext:
			workSSID = etSSID.getText().toString();
			workSSIDPsw = etPsw.getText().toString();

			if (TextUtils.isEmpty(workSSID)) {
				Toast.makeText(GosAirlinkChooseDeviceWorkWiFiActivity.this, R.string.choose_wifi_list_title,
						2000).show();
				return;
			}
			if (TextUtils.isEmpty(workSSIDPsw)) {
				final Dialog dialog = new AlertDialog.Builder(this).setView(new EditText(this)).create();
				dialog.show();

				Window window = dialog.getWindow();
				window.setContentView(R.layout.alert_gos_empty);

				LinearLayout llNo, llSure;
				llNo = (LinearLayout) window.findViewById(R.id.llNo);
				llSure = (LinearLayout) window.findViewById(R.id.llSure);

				llNo.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.cancel();
					}
				});

				llSure.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						toAirlinkReady();
					}
				});
			} else {
				toAirlinkReady();
			}

			break;

		case R.id.imgWiFiList:
			AlertDialog.Builder dia = new AlertDialog.Builder(GosAirlinkChooseDeviceWorkWiFiActivity.this);
			View view = View.inflate(GosAirlinkChooseDeviceWorkWiFiActivity.this, R.layout.alert_gos_wifi_list, null);
			ListView listview = (ListView) view.findViewById(R.id.wifi_list);
			List<ScanResult> rsList = NetUtils.getCurrentWifiScanResult(this);
			List<String> localList = new ArrayList<String>();
			localList.clear();
			wifiList = new ArrayList<ScanResult>();
			wifiList.clear();
			for (ScanResult sss : rsList) {

				if (sss.SSID.contains(SoftAP_Start)) {
				} else {
					if (localList.toString().contains(sss.SSID)) {
					} else {
						localList.add(sss.SSID);
						wifiList.add(sss);
					}
				}
			}
			WifiListAdapter adapter = new WifiListAdapter(wifiList);
			listview.setAdapter(adapter);
			listview.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					ScanResult sResult = wifiList.get(arg2);
					String sSID = sResult.SSID;
					etSSID.setText(sSID);
					etPsw.setText("");
					create.dismiss();
				}
			});
			dia.setView(view);
			create = dia.create();
			create.show();

			break;

		case R.id.llChooseMode:
			Intent intent = new Intent(this, GosModeListActivity.class);
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	private void toAirlinkReady() {
		// TODO
		spf.edit().putString("workSSID", workSSID).commit();
		spf.edit().putString("workSSIDPsw", workSSIDPsw).commit();

		Intent intent = new Intent(this, GosAirlinkReadyActivity.class);
		startActivity(intent);
		finish();
	}

	// 检查当前使用的WiFi是否曾经用过
	protected boolean checkworkSSIDUsed(String workSSID) {
		if (spf.contains("workSSID")) {
			if (spf.getString("workSSID", "").equals(workSSID)) {
				return true;
			}
		}
		return false;
	}

	// 屏蔽掉返回键
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			quitAlert(this);
			return true;
		}
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			quitAlert(this);
			break;
		}
		return true;
	}

	class WifiListAdapter extends BaseAdapter {

		ArrayList<ScanResult> xpgList;

		public WifiListAdapter(ArrayList<ScanResult> list) {
			this.xpgList = list;
		}

		@Override
		public int getCount() {
			return xpgList.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			Holder holder;
			if (view == null) {
				view = LayoutInflater.from(GosAirlinkChooseDeviceWorkWiFiActivity.this)
						.inflate(R.layout.item_gos_wifi_list, null);
				holder = new Holder(view);
				view.setTag(holder);
			} else {
				holder = (Holder) view.getTag();
			}

			String ssid = xpgList.get(position).SSID;
			holder.getTextView().setText(ssid);

			return view;
		}

	}

	class Holder {
		View view;

		public Holder(View view) {
			this.view = view;
		}

		TextView textView;

		public TextView getTextView() {
			if (textView == null) {
				textView = (TextView) view.findViewById(R.id.SSID_text);
			}
			return textView;
		}

	}
}


text:
/*!
 * jsodvcs
 * https://github.com/wortex17/jsodvcs
 * Created 24.04.2016 by Patrick Michael Hopf
 *
 * Released under The MIT License
 */
"use strict";

/**
 * @readonly
 * @enum {String}
 * @memberOf jsodvcs
 */
let RepositoryObjectType = {
    blob: 'b',
    tree: 't',
    commit: 'c'
};

module.exports = RepositoryObjectType;


text:
require 'spec_helper'

describe MemeCaptainWeb::Config do

  context 'when the MC_SET_FRONT_PAGE_MIN_QUALITY env var is not set' do

    it 'uses the default' do
      expect(MemeCaptainWeb::Config::SetFrontPageMinQuality).to eq 0
    end

  end

  context 'when the MC_SET_FRONT_PAGE_MIN_QUALITY env var is set' do

    it 'uses the environment variable' do
      pending
    end

  end

end


text:
import { Component, OnInit } from '@angular/core';
import { datacode } from './display-data.data';

@Component({
    selector: 'app-display-data',
    templateUrl: './display-data.component.html',
})
export class DisplayDataComponent implements OnInit {
    // 代码
    data = datacode;

    tabs = [
        {
            title: 1,
            content: '123'
        },
        {
            title: 2,
            content: '123'
        },
        {
            title: 3,
            content: '123'
        }
    ];

    constructor() { }

    ngOnInit() {
    }

}


text:
layout: post
title: 'GPL Versions of SourceForge'
date: 2006-02-11 20:02
comments: true
categories : []
---

If you head over to the Software page you can download all the GPL versions of SourceForge that we made available over the years when I was employed at VA Linux Systems.


text:
{% extends 'base.html' %}
{% load i18n %}
{% block title %}{% trans "Template Versions" %}{% endblock %}

{% block main %}
    {{ table.render }}
{% endblock %}