text:
import type { FC } from 'react'
import React, { useState, useEffect, useCallback } from 'react'
import styled, { createGlobalStyle } from 'styled-components'
import {
  Aside,
  ComponentsProvider,
  Divider,
  Heading,
  IconButton,
  Layout,
  Page,
  Space,
} from '@looker/components'
import { FirstPage } from '@styled-icons/material/FirstPage'
import { LastPage } from '@styled-icons/material/LastPage'
import {
  registerEnvAdaptor,
  unregisterEnvAdaptor,
} from '@looker/extension-utils'
import { useSelector } from 'react-redux'
import { useLocation } from 'react-router-dom'

import type { IApixAdaptor } from './utils'
import {
  Header,
  SideNav,
  ErrorBoundary,
  SelectorContainer,
  HEADER_TOGGLE_LABEL,
  Loader,
  Banner,
} from './components'
import { AppRouter } from './routes'
import { apixFilesHost } from './utils/lodeUtils'
import {
  useSettingActions,
  useLodeActions,
  useLodesStoreState,
  useSpecActions,
  useSpecStoreState,
  selectSpecs,
  selectCurrentSpec,
  useSettingStoreState,
} from './state'
import { getSpecKey, findSdk, useGlobalStoreSync } from './utils'

export interface ApiExplorerProps {
  adaptor: IApixAdaptor
  examplesLodeUrl?: string
  declarationsLodeUrl?: string
  headless?: boolean
}

const BodyOverride = createGlobalStyle` html { height: 100%; overflow: hidden; } `

export const ApiExplorer: FC<ApiExplorerProps> = ({
  adaptor,
  examplesLodeUrl = 'https://raw.githubusercontent.com/looker-open-source/sdk-codegen/main/examplesIndex.json',
  declarationsLodeUrl = `${apixFilesHost}/declarationsIndex.json`,
  headless = false,
}) => {
  useLodesStoreState()
  const { working, description } = useSpecStoreState()
  const specs = useSelector(selectSpecs)
  const spec = useSelector(selectCurrentSpec)
  const { initLodesAction } = useLodeActions()
  const { initialized } = useSettingStoreState()
  const { initSettingsAction, setSearchPatternAction, setSdkLanguageAction } =
    useSettingActions()
  const { initSpecsAction, setCurrentSpecAction } = useSpecActions()

  const location = useLocation()
  useGlobalStoreSync()
  const [hasNavigation, setHasNavigation] = useState(true)
  const toggleNavigation = (target?: boolean) =>
    setHasNavigation(target || !hasNavigation)

  const hasNavigationToggle = useCallback((e: MessageEvent<any>) => {
    if (e.origin === window.origin && e.data.action === 'toggle_sidebar') {
      setHasNavigation((currentHasNavigation) => !currentHasNavigation)
    }
  }, [])

  registerEnvAdaptor(adaptor)

  useEffect(() => {
    initSettingsAction()
    initLodesAction({ examplesLodeUrl, declarationsLodeUrl })

    const specKey = getSpecKey(location)
    initSpecsAction({ specKey })
    return () => unregisterEnvAdaptor()
  }, [])

  useEffect(() => {
    const maybeSpec = location.pathname?.split('/')[1]
    if (spec && maybeSpec && maybeSpec !== spec.key) {
      setCurrentSpecAction({ currentSpecKey: maybeSpec })
    }
  }, [location.pathname, spec])

  useEffect(() => {
    if (!initialized) return
    const searchParams = new URLSearchParams(location.search)
    const searchPattern = searchParams.get('s') || ''
    const sdkParam = searchParams.get('sdk') || 'all'
    const { language: sdkLanguage } = findSdk(sdkParam)
    setSearchPatternAction({ searchPattern })
    setSdkLanguageAction({ sdkLanguage })
  }, [location.search])

  useEffect(() => {
    if (headless) {
      window.addEventListener('message', hasNavigationToggle)
    }
    return () => {
      if (headless) {
        window.removeEventListener('message', hasNavigationToggle)
      }
    }
  }, [headless, hasNavigationToggle])

  const themeOverrides = adaptor.themeOverrides()

  let neededSpec = location.pathname?.split('/')[1]
  if (!neededSpec) {
    neededSpec = spec?.key
  }

  return (
    <>
      <ComponentsProvider
        loadGoogleFonts={themeOverrides.loadGoogleFonts}
        themeCustomizations={themeOverrides.themeCustomizations}
      >
        {working || !neededSpec || neededSpec !== spec.key ? (
          <Loader message={description} themeOverrides={themeOverrides} />
        ) : (
          <ErrorBoundary logError={adaptor.logError.bind(adaptor)}>
            <Banner adaptor={adaptor} specs={specs} />
            <Page style={{ overflow: 'hidden' }}>
              {!headless && (
                <Header spec={spec} toggleNavigation={toggleNavigation} />
              )}
              <Layout hasAside height="100%">
                <AsideBorder
                  borderRight
                  isOpen={hasNavigation}
                  headless={headless}
                >
                  {headless && (
                    <>
                      <Space
                        alignItems="center"
                        py="u3"
                        px={hasNavigation ? 'u5' : '0'}
                        justifyContent={
                          hasNavigation ? 'space-between' : 'center'
                        }
                      >
                        {hasNavigation && (
                          <Heading
                            as="h2"
                            fontSize="xsmall"
                            fontWeight="bold"
                            color="text2"
                          >
                            API DOCUMENTATION
                          </Heading>
                        )}
                        <IconButton
                          size="xsmall"
                          shape="round"
                          icon={hasNavigation ? <FirstPage /> : <LastPage />}
                          label={HEADER_TOGGLE_LABEL}
                          onClick={() => toggleNavigation()}
                        />
                      </Space>
                      {hasNavigation && (
                        <>
                          <Divider mb="u3" appearance="light" />
                          <SelectorContainer
                            spec={spec}
                            ml="large"
                            mr="large"
                          />
                        </>
                      )}
                    </>
                  )}
                  {hasNavigation && <SideNav headless={headless} spec={spec} />}
                </AsideBorder>
                <AppRouter
                  specKey={spec.key}
                  api={spec.api!}
                  toggleNavigation={toggleNavigation}
                />
              </Layout>
            </Page>
          </ErrorBoundary>
        )}
      </ComponentsProvider>
      {!headless && <BodyOverride />}
    </>
  )
}

const AsideBorder = styled(Aside)<{
  isOpen: boolean
  headless: boolean
}>`
  width: ${({ isOpen, headless }) =>
    isOpen ? '20rem' : headless ? '2.75rem' : '0rem'};
`


text:
React.render(

Hello, world!
,
	document.getElementById('example')
);

redpajama_set_name: RedPajamaGithub


text:
/*
 *
 * Header constants
 *
 */

export const SET_APPBAR = 'app/Header/SET_APPBAR';


text:
import React, { FC } from 'react'
import { Switch, Select, Slider } from 'antd'
import { useTranslate } from '@/_helpers/i18n'
import { isFirefox } from '@/_helpers/saladict'
import { useSelector } from '@/content/redux'
import { getConfigPath } from '@/options/helpers/path-joiner'
import {
  SaladictForm,
  pixelSlideFormatter
} from '@/options/components/SaladictForm'

export const Popup: FC = () => {
  const { t } = useTranslate(['options', 'menus'])
  const menusIds = useSelector(state => {
    const ids = Object.keys(state.config.contextMenus.all)
    if (isFirefox) {
      return ids.filter(id => {
        switch (id) {
          case 'youdao_page_translate':
          case 'caiyuntrs':
            return false
        }
        return true
      })
    }
    return ids
  })
  const { availWidth } = window.screen

  return (
    <SaladictForm
      items={[
        {
          name: getConfigPath('baOpen'),
          children: (
            <Select>
              <Select.Option value="popup_panel">
                {t('config.opt.baOpen.popup_panel')}
              </Select.Option>
              <Select.Option value="popup_fav">
                {t('config.opt.baOpen.popup_fav')}
              </Select.Option>
              <Select.Option value="popup_options">
                {t('config.opt.baOpen.popup_options')}
              </Select.Option>
              <Select.Option value="popup_standalone">
                {t('config.opt.baOpen.popup_standalone')}
              </Select.Option>
              {menusIds.map(id => (
                <Select.Option key={id} value={id}>
                  {t(`menus:${id}`)}
                </Select.Option>
              ))}
            </Select>
          )
        },
        {
          name: getConfigPath('baWidth'),
          hide: values => values[getConfigPath('baOpen')] !== 'popup_panel',
          children: (
            <Slider
              tipFormatter={pixelSlideFormatter}
              min={-1}
              max={availWidth}
              marks={{
                '-1': '-1',
                450: '450px',
                [availWidth]: `${availWidth}px`
              }}
            />
          )
        },
        {
          name: getConfigPath('baHeight'),
          hide: values => values[getConfigPath('baOpen')] !== 'popup_panel',
          children: (
            <Slider
              tipFormatter={pixelSlideFormatter}
              min={250}
              max={availWidth}
              marks={{
                250: '250px',
                550: '550px',
                [availWidth]: `${availWidth}px`
              }}
            />
          )
        },
        {
          name: getConfigPath('baPreload'),
          label: t('preload.title'),
          help: t('preload.help'),
          hide: values => values[getConfigPath('baOpen')] !== 'popup_panel',
          children: (
            <Select>
              <Select.Option value="">{t('common:none')}</Select.Option>
              <Select.Option value="clipboard">
                {t('preload.clipboard')}
              </Select.Option>
              <Select.Option value="selection">
                {t('preload.selection')}
              </Select.Option>
            </Select>
          )
        },
        {
          name: getConfigPath('baAuto'),
          label: t('preload.auto'),
          help: t('preload.auto_help'),
          hide: values =>
            values[getConfigPath('baOpen')] !== 'popup_panel' ||
            !values[getConfigPath('baPreload')],
          valuePropName: 'checked',
          children: <Switch />
        }
      ]}
    />
  )
}


text:
CloseAttribute = function(group) {
  this.perceive(group);
}
CloseAttribute.prototype.key = "close";
CloseAttribute.prototype.targetType = 'group';
CloseAttribute.prototype.arity = 1;
CloseAttribute.prototype.constant = false;

CloseAttribute.prototype.perceive = function(group) {
  this.group = group;
  if (group.objs.length < 2) this.val = NaN;
  else {
    // var pobjs = group.objs.map(function (on) { return on.phys_obj });
    // var tgs = group.scene_node.oracle.getSpatialGroups(20 * group.objs[0].phys_scale, pobjs);
    // if (tgs.length == 1) this.val = 1;
    // else this.val = 0;
    var nodes = [];
    for (var i=0; i<group.objs.length; i++) { nodes.push(i) }
    var edges = [], scale = group.objs[0].phys_scale;
    for (var i=1; i<group.objs.length; i++) for (var j=0; j<i; j++) {
      edges.push({a:i, b:j, dist: group.objs[i].phys_obj.distance(group.objs[j].phys_obj) / scale});
    };
    var mst = CloseAttribute.getMST(nodes, edges);
    // the last edge in the MST has the bigges distance
    this.val = mst[mst.length-1].dist;
  }
}

CloseAttribute.prototype.get_activity = function() {
  return (isNaN(this.val) ? 0 : CloseRelationship.membership(this.val));
}

CloseAttribute.prototype.get_label = function() {
  return 'close';
}

/// Nodes should be numbers, edges should be {a: node1, b: node2, dist: 1.34}.
CloseAttribute.getMST = function(nodes, edges) {
  var mst = [];
  var sets = nodes.map(function(node) { var s = {}; s[node] = true; return s });
  edges.sort(function(a,b) { return a.dist-b.dist} );
  for (var i=0; i<edges.length; i++) {
    var a = edges[i].a, b = edges[i].b;
    var idx_a, idx_b;
    for (var j=0; j<sets.length; j++) {
      if (a in sets[j]) idx_a = j;
      if (b in sets[j]) idx_b = j;
    }
    if (idx_a === idx_b) continue;
    mst.push(edges[i]);
    for (var key in sets[idx_b]) sets[idx_a][key] = true;
    sets[idx_b] = {};
  }
  return mst;
}


text:
package com.pivotal.gemfirexd.internal.impl.store.raw.data;

import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;

/**
  A ByteHolder that stores all its bytes in memory.
  */
public class MemByteHolder
implements ByteHolder
{
	int bufSize;

	boolean writing = true;

	Vector bufV;
	int curBufVEleAt;

	byte[] curBuf;
	int curBufPos;

	//
	//We use this to determine when we have reached the end
	//of the current buffer whild reading. For the last
	//buffer this may be less than bufSize.
	int curBufDataBytes;

	//
	//We use these to remember the location of the last byte
	//of data we have stored. The read methods use these to
	//avoid reading more bytes than we have stored. These
	//values are set by startReading.
	int lastBufVEleAt = 0;
	int lastBufDataBytes = 0;

	/**
	  Create a new MemByteHolder. Store bytes as a list of buffers
	  of size 'bufSize'.
	  */
	public MemByteHolder(int bufSize)
	{
		this.bufSize = bufSize;

		this.curBuf = new byte[bufSize];
		this.curBufPos = 0;

		this.bufV = new Vector(128);
		bufV.addElement(curBuf);
		this.curBufVEleAt = 0;
	}

	/**
	  @see ByteHolder#write
	  @exception IOException		Thrown on error
	  */
	public void write(int b) throws IOException
	{
		if (SanityManager.DEBUG)
			SanityManager.ASSERT(writing == true,
								 "Writing should be true 1");

		if(curBufPos>=curBuf.length)
			getNextBuffer_w();

		curBuf[curBufPos++] = (byte)b;
	}

	/**
	  @see ByteHolder#write
	  @exception IOException		Thrown on error
	  */
	public void write(byte[] data, int offset, int len) throws IOException
	{
		if (SanityManager.DEBUG)
			SanityManager.ASSERT(writing == true,
								 "Writing should be true 2");

		while(len > 0)
		{
			if(curBufPos>=curBuf.length)
				getNextBuffer_w();

			int bytesToCopyThisTime = len;
			int bytesInCurBuf = curBuf.length - curBufPos;

			if (bytesToCopyThisTime > bytesInCurBuf)
				bytesToCopyThisTime = bytesInCurBuf;
			System.arraycopy(data,offset,curBuf,curBufPos,bytesToCopyThisTime);
			offset += bytesToCopyThisTime;
			curBufPos += bytesToCopyThisTime;
			len -= bytesToCopyThisTime;
		}
	}

	/**
	  @see ByteHolder#write
	  @exception IOException		Thrown on error
	  */
	public long write(InputStream is, long count) throws IOException
	{
		long bytesToTransfer = count;
		int bytesTransferredThisTime = 0;

		do
		{
			if(curBufPos>=curBuf.length)
				getNextBuffer_w();

			int bytesToTransferThisTime;
			int bytesInCurBuf = curBuf.length - curBufPos;

			if (bytesToTransfer >= bytesInCurBuf)
				bytesToTransferThisTime = bytesInCurBuf;
			else
				 bytesToTransferThisTime = (int)bytesToTransfer;
			//
			//Note read should never return 0. Thus we keep looping
			//transferring bytes from the stream to our buffer until
			//we transfer count bytes or reach the end of the stream.
			//
			bytesTransferredThisTime =
				is.read(curBuf,curBufPos,bytesToTransferThisTime);

			if (bytesTransferredThisTime > 0)
			{
                if (SanityManager.DEBUG)
                    SanityManager.ASSERT(
                        writing == true, "Writing should be true 3");

				bytesToTransfer -= bytesTransferredThisTime;
				curBufPos += bytesTransferredThisTime;
			}
		} while (bytesToTransfer > 0 &&
				 bytesTransferredThisTime > 0);

		return count - bytesToTransfer;
	}

	/**
	  @see ByteHolder#clear

	  @exception IOException		Thrown on error
	  */
	public void clear() throws IOException
	{
		writing = true;

		curBuf = (byte[])bufV.elementAt(0);
		this.curBufVEleAt = 0;
		this.curBufPos = 0;

		lastBufVEleAt = 0;
		lastBufDataBytes = 0;
	}

	/**
	  @see ByteHolder#startReading
	  */
	public void startReading()
        throws IOException
	{
		if (writing == true)
		{
			//Enter read mode.
			writing = false;
			lastBufDataBytes = curBufPos;
			lastBufVEleAt = curBufVEleAt;
		}
		//
		//Reposition so reads start from the first
		//byte.
		curBuf = (byte[])bufV.elementAt(0);
		this.curBufVEleAt = 0;
		this.curBufPos = 0;
		if (curBufVEleAt == lastBufVEleAt)
			curBufDataBytes = lastBufDataBytes;
		else
			curBufDataBytes = bufSize;
	}

	/**
	  @see ByteHolder#read
	  @exception IOException	Thrown on error
	  */
	public int read() throws IOException
	{
		if (SanityManager.DEBUG)
			SanityManager.ASSERT(writing == false,
								 "Reading should be true 2");

		if (curBufPos >= curBufDataBytes)
			getNextBuffer_r();

		if (curBufPos >= curBufDataBytes)
			return -1;
		else
			return 0xff & curBuf[curBufPos++];
	}

	/**
	  @see ByteHolder#read
	  @exception IOException	Thrown on error
	  */
	public int read(byte b[],
					int off,
					int len)
		throws IOException
	{
		return (read(b, off, (OutputStream) null, len));
	}

	/**
	  @see ByteHolder#read
	  @exception IOException	Thrown on error
	  */
	public int read(OutputStream out,
					int len)
		throws IOException
	{
		return(read((byte []) null, 0, out, len));
	}

	/**
	  @see ByteHolder#read
	  @exception IOException	Thrown on error
	  */
	public int read(byte b[],
					int off,
					OutputStream out,
					int len)
		throws IOException
	{
		int bytesIRead = 0;
		boolean eof = false;

		if (SanityManager.DEBUG)
			SanityManager.ASSERT(writing == false,
								 "Reading should be true 3");

		if (curBufPos >= curBufDataBytes)
			eof = getNextBuffer_r();

		if (eof) return -1;

		while (len > 0 && !eof)
		{
			int bytesInCurBuf = curBufDataBytes - curBufPos;
			int bytesIReadThisTime;
			if (len >= bytesInCurBuf)
				bytesIReadThisTime = bytesInCurBuf;
			else
				 bytesIReadThisTime = len;

			if (out == null) {
				// write the data to the byte array
				System.arraycopy(curBuf,curBufPos,b,off,bytesIReadThisTime);
			} else {
				// write the data to the output stream
				out.write(curBuf, curBufPos, bytesIReadThisTime);
			}
			off+=bytesIReadThisTime;
			curBufPos+=bytesIReadThisTime;
			len -= bytesIReadThisTime;
			bytesIRead+=bytesIReadThisTime;
			if (curBufPos >= curBufDataBytes)
				eof = getNextBuffer_r();
		}

		return bytesIRead;
	}

	/**
	  @see ByteHolder#shiftToFront
	  @exception IOException	Thrown on error
	  */
	public int shiftToFront() throws IOException
	{
		int remainingBytes = available();
		remainingBytes = remainingBytes > 0 ? remainingBytes : (-1) * remainingBytes;

		byte b[] = new byte[remainingBytes + 1];
		int bytesRead = read(b, 0, remainingBytes);

		// clear the buffer
		clear();

		// put the bytes at the beginning of the buffer
		writing = true;
		write(b, 0, bytesRead);

		curBufDataBytes = 0;

		return bytesRead;
	}

	/**
	  @see ByteHolder#available
	  */
	public int available()
	{
		//if (SanityManager.DEBUG)
		//	SanityManager.ASSERT(writing == false,
		//						 "Reading should be true 3");

		int curBufAvailable = curBufDataBytes - curBufPos;
		int lastBufAvailable = 0;
		int middleBuffers = 0;
		if (curBufVEleAt != lastBufVEleAt)
		{
			middleBuffers = lastBufVEleAt - curBufVEleAt - 1;
			lastBufAvailable = lastBufDataBytes;
		}
		int availableBytes =
			curBufAvailable +
			lastBufAvailable +
			middleBuffers * bufSize;

		return availableBytes;
	}

    /**
 	  Return the number of bytes that have been saved to this byte holder.
      This result is different from available() as it is unaffected by the
      current read position on the ByteHolder.

	  @see ByteHolder#numBytesSaved
	  */
	public int numBytesSaved()
	{
        int ret_val;

        if (writing)
        {
            // still writing, so use the cur* variables
            if (SanityManager.DEBUG)
                SanityManager.ASSERT(
                    lastBufVEleAt == 0 && lastBufDataBytes == 0,
                    "counters were somehow bumped during writing");

            ret_val = (curBufVEleAt * bufSize) + curBufPos;
        }
        else
        {
            ret_val = (lastBufVEleAt * bufSize) + lastBufDataBytes;
        }

        return(ret_val);
	}

	/**
	  @see ByteHolder#skip
	  @exception IOException	Thrown on error
	  */
	public long skip(long count) throws IOException
	{
		long bytesISkipped = 0;
		boolean eof = false;

		if (SanityManager.DEBUG)
			SanityManager.ASSERT(writing == false,
								 "Reading should be true 4");

		if (curBufPos >= curBufDataBytes)
			eof = getNextBuffer_r();

		while (count > 0 && !eof)
		{
			int bytesInCurBuf = curBufDataBytes - curBufPos;
			int bytesISkippedThisTime;

			if (count >= bytesInCurBuf)
				bytesISkippedThisTime = bytesInCurBuf;
			else
				 bytesISkippedThisTime = (int)count;

			curBufPos+=bytesISkippedThisTime;
			count -= bytesISkippedThisTime;
			bytesISkipped+=bytesISkippedThisTime;

			if (count > 0)
				eof = getNextBuffer_r();
		}

		return bytesISkipped;
	}

	/**
	  @see ByteHolder#writingMode
	 */
	public boolean writingMode()
	{
		return writing;
	}

	/**
	  Get the next buffer for writing bytes.
	  @exception IOException	Thrown on error
	  */
	protected void getNextBuffer_w() throws IOException
	{
		if (SanityManager.DEBUG)
		{
			getNextBuffer_w_Sanity();
		}

		curBufVEleAt++;

		if (bufV.size() <= curBufVEleAt)
		{
			curBuf = new byte[bufSize];
			bufV.addElement(curBuf);
		}
		else
		{
			curBuf = (byte[])bufV.elementAt(curBufVEleAt);
		}

		initBuffer_w();
	}

	/** Do sanity checking when getting the next write buffer */
	protected void getNextBuffer_w_Sanity()
	{
		if (SanityManager.DEBUG)
		{
			SanityManager.ASSERT(curBufPos == curBuf.length,
								 "partial write");

			SanityManager.ASSERT(writing == true,
								 "Writing should be true 5");
		}
	}

	/** Initialize a buffer for writing */
	protected void initBuffer_w()
	{
		curBufPos = 0;

		if (SanityManager.DEBUG)
		{
		    SanityManager.ASSERT(curBuf.length == bufSize,
								 "bad Buf Length "+curBuf.length);
		}
	}

	/**
	  Get the next buffer for reading bytes.

	  @return true if the user has read all the bytes
	  in this ByteHolder.

	  @exception IOException		Thrown on error
	  */
	protected boolean getNextBuffer_r() throws IOException
	{
		if (SanityManager.DEBUG)
			SanityManager.ASSERT(writing == false,
								 "Reading should be true 5");
		if (curBufVEleAt >= lastBufVEleAt) return true;
		curBuf = (byte[])bufV.elementAt(++curBufVEleAt);
		curBufPos = 0;
		if (curBufVEleAt == lastBufVEleAt)
			curBufDataBytes = lastBufDataBytes;
		else
			curBufDataBytes = bufSize;
		return false;
	}

	/**
	  Create a string representation of an internal buffer of bytes.
	  This is useful during debugging.
	  */
	private String dumpBuf(int bufVEleAt)
	{
		StringBuilder sb = new StringBuilder(100);

		byte[] buf = (byte[])bufV.elementAt(bufVEleAt);
		sb.append("(");
		for (int ix = 0;ix<buf.length;ix++)
			sb.append(buf[ix]+".");
		sb.append(")");
		return sb.toString();
	}

	/**
	  Produce a string describing the state of this ByteHolder.
	  This is mainly for debugging.
	  */
	public String toString()
	{
		return
			" writing: "+writing+
			" curBufVEleAt: "+curBufVEleAt+
			" curBufPos: "+curBufPos+
			" curBufDataBytes: "+curBufDataBytes+
			" lastBufVEleAt: "+lastBufVEleAt+
            " lastBufDataBytes: "+lastBufDataBytes+
			" curBuf: "+dumpBuf(curBufVEleAt);
	}
}


text:
set -e

full_path=$(realpath $0)
PLUGIN_FOLDER=`dirname $full_path`

ln -sf "$PLUGIN_FOLDER/.profile" "$HOME/.profile"
ln -sf "$PLUGIN_FOLDER/.bash_profile" "$HOME/.bash_profile"
ln -sf "$PLUGIN_FOLDER/.bash_login" "$HOME/.bash_login"
ln -sf "$PLUGIN_FOLDER/.bashrc" "$HOME/.bashrc"
ln -sf "$PLUGIN_FOLDER/.inputrc" "$HOME/.inputrc"

if [ ! -f ~/.envvars.sh ]; then
  echo 'Copying envvars example for you to fill in.'
   cp "$PLUGIN_FOLDER/envvars.example.sh"  ~/.envvars.sh
else
  echo 'Seems you have an envvars file on your $HOME. in case you need a bit of guidance on what it should contain:'
  echo '------- ENVVARS EXAMPLE -------'
  cat "$PLUGIN_FOLDER/envvars.example.sh"
  echo '-------------------------------'
fi


text:
!
! libui-draw-sample1.f90
! Fortran から libui を使う。
!
! Author Yoji.Hosokawa 2016/4
!
! gfortran -O2 -g -Wall -o libui-window libui-window.f90 -L.-lui `pkg-config gtk+-3.0 --libs`
!

module handlers
  use iso_c_binding
  use libuif_structs
  use libuif
  implicit none

    type(c_ptr) :: mainwin;
    type(c_ptr) :: histogram;
    type(uiAreaHandler) :: handler
    type(uiDrawBrush) :: brush
    type(uiDrawStrokeParams) :: sp
    type(uiDrawMatrix) :: m
    real(c_double) :: graphWidth, graphHeight
    real(c_double) :: graphR, graphG, graphB, graphA
    integer(c_int32_t) :: color
    real(c_double) :: alpha

!    integer :: currentPoint = -1

!  some metrics
    integer,parameter :: xoffLeft = 20
    integer,parameter :: yoffTop = 20
    integer,parameter :: xoffRight = 20
    integer,parameter :: yoffBottom = 20
    integer,parameter :: pointRadius = 5

!// and some colors
!// names and values from https://msdn.microsoft.com/en-us/library/windows/desktop/dd370907%28v=vs.85%29.aspx
    integer,parameter :: colorWhite = x'FFFFFF'
    integer,parameter :: colorBlack = x'000000'
    integer,parameter :: colorDodgerBlue = x'1E90FF'
    integer,parameter :: d2dBlack = x'000000'
    integer,parameter :: d2dLightSlateGray = x'778899'
    integer,parameter :: d2dCornflowerBlue = x'6495ED'
    integer,parameter :: d2dWhite = x'FFFFFF'
    integer,parameter :: d2dYellowGreen = x'9ACD32'
    integer,parameter :: d2dYellow = x'FFFF00'
    integer,parameter :: d2dForestGreen = x'228B22'
    integer,parameter :: d2dOliveDrab = x'6B8E23'
    integer,parameter :: d2dLightSkyBlue = x'87CEFA'

contains

  ! "close mainwindow" is a this app

  subroutine onClosing()
    use iso_c_binding
    use libuif
      call uiQuit()
  end subroutine onClosing

  subroutine setSolidBrush(linetype, color, alpha)
    use iso_c_binding
    use libuif
    implicit none
       integer :: linetype,color
       double precision :: alpha

         brush%Type = linetype
         brush%R = dble(ibits(color,16,8)) / 255.0d0
         brush%G = dble(ibits(color,8,8)) / 255.0d0
         brush%B = dble(ibits(color,0,8)) / 255.0d0
         brush%A = alpha
  end subroutine setSolidBrush

!  subroutine graphSize(clientWidth, clientHeight)
!    use iso_c_binding
!    implicit none
!      double precision :: clientWidth, clientHeight
!        graphWidth = clientWidth - xoffLeft - xoffRight;
!        graphHeight = clientHeight - yoffTop - yoffBottom;
!  end subroutine graphSize

  subroutine d2dColorToRGB(color, r, g, b)
    use iso_c_binding
    use libuif
      integer :: color
      double precision :: r,g,b
        r = dble(ibits(color,16,8)) / 255.0d0
        g = dble(ibits(color,8,8)) / 255.0d0
        b = dble(ibits(color,0,8)) / 255.0d0
  end subroutine d2dColorToRGB

  subroutine d2dSolidBrush(brush, color, alpha)
    use iso_c_binding
    use libuif_structs
    use libuif
      type(uiDrawBrush) :: brush
      integer :: color
      double precision :: alpha
        brush%Type = uiDrawBrushTypeSolid
        call d2dColorToRGB(color, brush%R, brush%G, brush%B)
        brush%A = alpha;
  end subroutine d2dSolidBrush

  subroutine d2dClear(p, color, alpha)
    use iso_c_binding
    use libuif_structs
    use libuif
      type(uiAreaDrawParams) :: p
      integer :: color
      double precision :: alpha
      type(c_ptr) :: path
      type(uiDrawBrush) :: brush

        call d2dSolidBrush(brush, color, alpha)
        path = uiDrawNewPath(uiDrawFillModeWinding)
        call uiDrawPathAddRectangle(path, 0.0d0, 0.0d0, p%AreaWidth, p%AreaHeight)
        call uiDrawPathEnd(path)
        call uiDrawFill(p%Context, path, brush)
        call uiDrawFreePath(path)
  end subroutine d2dClear

  subroutine drawD2DLinearBrush(p)
    use iso_c_binding
    use libuif_structs
    use libuif
      type(uiAreaDrawParams) :: p
      type(c_ptr) :: path
      type(uiDrawBrush) :: black
      type(uiDrawBrush) :: gradient
      type(uiDrawStrokeParams) :: sp
      type(uiDrawMatrix) :: m

      type(uiDrawBrushGradientStop),pointer :: stops(:)
      allocate( stops(2))

      sp%Dashes = c_null_ptr
      sp%NumDashes = 0
      sp%DashPhase = 0.0d0

!   leave some room
      call uiDrawMatrixSetIdentity(m)
      call uiDrawMatrixTranslate(m, 25.0d0, 25.0d0)
      call uiDrawTransform(p%Context, m)

      gradient%Type = uiDrawBrushTypeLinearGradient
      gradient%X0 = 0 + 400
      gradient%Y0 = 0
      gradient%X1 = 150 + 400
      gradient%Y1 = 150
      stops(1)%Pos = 0.0
      call d2dColorToRGB(d2dYellow, stops(1)%R, stops(1)%G, stops(1)%B)
      stops(1)%A = 1.0
      stops(2)%Pos = 1.0
      call d2dColorToRGB(d2dForestGreen, stops(2)%R, stops(2)%G, stops(2)%B)
      stops(2)%A = 1.0
      gradient%Stops = c_loc(stops(1))
      gradient%NumStops = 2

      call d2dSolidBrush(black, d2dBlack, 1.0d0)

      path = uiDrawNewPath(uiDrawFillModeWinding)
      call uiDrawPathAddRectangle(path, 0.0d0 + 400.0d0, 0.0d0, 150.0d0, 150.0d0)
      call uiDrawPathEnd(path)

      call uiDrawFill(p%Context, path, gradient)
      sp%Thickness = 1.0
      sp%Cap = uiDrawLineCapFlat
      sp%Join = uiDrawLineJoinMiter
      sp%MiterLimit = uiDrawDefaultMiterLimit
      call uiDrawStroke(p%Context, path, black, sp)

      call uiDrawFreePath(path)
  end subroutine drawD2DLinearBrush

  subroutine drawD2DRadialBrush(p)
    use iso_c_binding
    use libuif_structs
    use libuif
      type(uiAreaDrawParams) :: p
      type(c_ptr) :: path
      type(uiDrawBrush) :: black
      type(uiDrawBrush) :: gradient
      type(uiDrawStrokeParams) :: sp
      type(uiDrawMatrix) :: m

      type(uiDrawBrushGradientStop),pointer :: stops(:)
      allocate(stops(2))

      sp%Dashes = c_null_ptr
      sp%NumDashes = 0
      sp%DashPhase = 0.0d0

!   leave some room
      call uiDrawMatrixSetIdentity(m)
      call uiDrawMatrixTranslate(m, 25.0d0, 25.0d0)
      call uiDrawTransform(p%Context, m)

      gradient%Type = uiDrawBrushTypeRadialGradient
      gradient%X0 = 75
      gradient%Y0 = 75 + 200
      gradient%X1 = 75
      gradient%Y1 = 75 + 200
      gradient%OuterRadius = 75
      stops(1)%Pos = 0.0
      call d2dColorToRGB(d2dYellow, stops(1)%R, stops(1)%G, stops(1)%B)
      stops(1)%A = 1.0
      stops(2)%Pos = 1.0
      call d2dColorToRGB(d2dForestGreen, stops(2)%R, stops(2)%G, stops(2)%B)
      stops(2)%A = 1.0
      gradient%Stops = c_loc(stops(1))
      gradient%NumStops = 2

      call d2dSolidBrush(black, d2dBlack, 1.0d0)

      path = uiDrawNewPath(uiDrawFillModeWinding)
      call uiDrawPathNewFigure(path, 150.0d0, 75.0d0 + 200.0d0)
      call uiDrawPathArcTo(path, 75.0d0, 75.0d0 + 200.0d0,75.0d0,0.0d0,2.0d0 * uiPi,0)
      call uiDrawPathEnd(path)

      call uiDrawFill(p%Context, path, gradient)
      sp%Thickness = 1.0
      sp%Cap = uiDrawLineCapFlat
      sp%Join = uiDrawLineJoinMiter
      sp%MiterLimit = uiDrawDefaultMiterLimit
      call uiDrawStroke(p%Context, path, black, sp)

      call uiDrawFreePath(path)
  end subroutine drawD2DRadialBrush

  subroutine handlerDraw(a, area, p)
    use iso_c_binding
    use libuif_structs
    use libuif
    implicit none
      type(uiAreaHandler) :: a
      type(c_ptr) :: area
      type(uiAreaDrawParams) :: p
      type(c_ptr) :: path
!  fill the area with white
       call setSolidBrush(uiDrawBrushTypeSolid, colorWhite, 1.0d0)
       path = uiDrawNewPath(uiDrawFillModeWinding)
       call uiDrawPathAddRectangle(path, 0.0_c_double, 0.0_c_double, p%AreaWidth, p%AreaHeight)
       call uiDrawPathEnd(path)
       call uiDrawFill(p%Context, path, brush)
       call uiDrawFreePath(path)

!  figure out dimensions
!       call graphSize(p%AreaWidth, p%AreaHeight)

!   make a stroke for both the axes and the histogram line
!       sp%Cap = uiDrawLineCapFlat
!       sp%Join = uiDrawLineJoinMiter
!       sp%Thickness = 2.0d0
!       sp%MiterLimit = uiDrawDefaultMiterLimit

!  drawD2DLinearBrush
      call drawD2DLinearBrush(p)

!  drawD2DRadialBrush
      call drawD2DRadialBrush(p)

  end subroutine handlerDraw

  subroutine handlerMouseEvent()
    use iso_c_binding
    use libuif
!  do nothing
  end subroutine handlerMouseEvent

  subroutine handlerMouseCrossed()
    use iso_c_binding
    use libuif
!  do nothing
  end subroutine handlerMouseCrossed

  subroutine handlerDragBroken()
    use iso_c_binding
    use libuif
!  do nothing
  end subroutine handlerDragBroken

  function handlerKeyEvent() result(ret)
    use iso_c_binding
    use libuif
      integer :: ret
!  reject all keys
    ret = 0
  end function handlerKeyEvent

end module handlers

program main
    use iso_c_binding
    use libuif_structs
    use libuif
    use handlers

    implicit none
!    type(c_ptr) :: mainwin
    type(c_ptr) :: vbox,ebtn

! initialize
  call uiInit(0)

! start procedure

  mainwin = uiNewWindow("libui Draw Sample"//c_null_char, 640, 480, 0)
!  call uiWindowSetMargined(mainwin, 1)
  call uiWindowOnClosing(mainwin, c_funloc(onClosing), c_null_ptr)

  vbox = uiNewVerticalBox()
  call uiWindowSetChild(mainwin, vbox)

    handler%Draw = c_funloc(handlerDraw)
    handler%MouseEvent = c_funloc(handlerMouseEvent)
    handler%MouseCrossed = c_funloc(handlerMouseCrossed)
    handler%DragBroken = c_funloc(handlerDragBroken)
    handler%KeyEvent = c_funloc(handlerKeyEvent)
  histogram = uiNewArea(handler)
  call uiBoxAppend(vbox, histogram, 1)

!  call uiBoxSetPadded(vbox,1)
  ebtn = uiNewButton("終了"//c_null_char)
  call uiButtonOnClicked(ebtn, c_funloc(onClosing), c_null_ptr)
  call uiBoxAppend(vbox, ebtn, 0)

  call uiControlShow(mainwin)
  call uiMain()

! nomary do not need if call when close window receive sig fault by button clicked
!  call uiUninit()

end program main


text:
namespace TicTacToe.Data
{
    using System.Data.Entity;
    using TicTacToe.Data.Models;

    public interface IDatabaseContext
    {
        IDbSet<Game> Games { get; set; }

        Database Database { get; }

    }
}


text:
static NSString * const kGameResultId = @"id";
static NSString * const kGameUniqueName = @"game_unique_name";
static NSString * const kUserUniqueId = @"user_unique_id";
static NSString * const kRecentGames = @"recent_games";
static NSString * const kHighScore = @"high_score";
static NSString * const kHighestLevel = @"highest_level";
static NSString * const kExtraResultData = @"extra_result_data";
static NSString * const kMaxNumberOfTimesPlayedInOneDay = @"max_count_in_day";
static NSString * const kMaxNumberOfTimesPlayedInOneWeek = @"max_count_in_week";
static NSString * const kNumberOfTimesPlayedToday = @"times_played_today";
static NSString * const kNumberOfTimesPlayedThisWeek = @"times_played_this_week";
static NSString * const kNumberOfTimesPlayedTotal = @"times_played_total";
static NSString * const kLastPlayedAt = @"last_played_at";
static NSString * const kUpdatedAt = @"updated_at";

static NSString * const kGameAggregateFilename = @"game_aggregate";
@interface TPGameAggregateResult ()
@end

@implementation TPGameAggregateResult

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
  return @{
           @"resultId": kGameResultId,
           @"gameUniqueName": kGameUniqueName,
           @"userUniqueId": kUserUniqueId,
           @"recentGames": kRecentGames,
           @"highScore": kHighScore,
           @"highestLevel": kHighestLevel,
           @"extraResultData": kExtraResultData,
           @"maxNumberOfTimesPlayedInOneDay": kMaxNumberOfTimesPlayedInOneDay,
           @"maxNumberOfTimesPlayedInOneWeek": kMaxNumberOfTimesPlayedInOneWeek,
           @"numberOfTimesPlayedToday": kNumberOfTimesPlayedToday,
           @"numberOfTimesPlayedThisWeek": kNumberOfTimesPlayedThisWeek,
           @"numberOfTimesPlayedTotal": kNumberOfTimesPlayedTotal,
           @"lastPlayedAt": kLastPlayedAt,
           @"updatedAt": kUpdatedAt
           };
}

+ (NSValueTransformer *) lastPlayedAtJSONTransformer {
  return [MTLValueTransformer reversibleTransformerWithForwardBlock:^(NSString *str) {
    return [[TPSettings dateFormatter] dateFromString:str];
  } reverseBlock:^(NSDate *date) {
    return [[TPSettings dateFormatter] stringFromDate:date];
  }];
}

+ (NSValueTransformer *) updatedAtJSONTransformer {
  return [MTLValueTransformer reversibleTransformerWithForwardBlock:^(NSString *str) {
    return [[TPSettings dateFormatter] dateFromString:str];
  } reverseBlock:^(NSDate *date) {
    return [[TPSettings dateFormatter] stringFromDate:date];
  }];
}

+ (NSString *) filePathForGameUniqueName:(NSString *) gameUniqueName forUserId:(NSString *) userId {
  NSString *filename = [NSString stringWithFormat:@"%@-%@.plist", kGameAggregateFilename, gameUniqueName];
  NSString *filePath = [TPSettings filePathForFilename:filename folderName:userId];
  return filePath;
}

+ (void) aggregateResultForGameName:(NSString *) gameUniqueName
                            success:(void (^)(TPGameAggregateResult *gameAggregateResult))success
                            failure:(void (^)(NSError *error))failure {
  TPGameAggregateResult *result = [TPGameAggregateResult gameAggregateResultForGameUniqueName:gameUniqueName];
  success(result);
}

+ (instancetype) gameAggregateResultForGameUniqueName:(NSString *) gameUniqueName {
  TPSessionService *session = [TPSessionService sharedInstance];
  if (session.user == nil) {
    // TODO: Need an error description.
    NSLog(@"Session user should not be nil.");
    return nil;
  }

  NSString *filePath = [self filePathForGameUniqueName:gameUniqueName forUserId:session.user.userId];
  TPGameAggregateResult *result = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

  if (result == nil) {
    // Nothing saved yet, initialize
    result = [[TPGameAggregateResult alloc] initWithGameUniqueName:gameUniqueName
                                                      userUniqueId:session.user.userId];
    [result saveWithErrorDescription:nil queueForUpdate:NO];
  }

  return result;
}

+ (NSArray *) gameAggregateResultsFromServerResponse:(NSArray *) serverResponse {
  TPSessionService *session = [TPSessionService sharedInstance];
  if (session.user == nil) {
    // TODO: Need an error description.
    NSLog(@"User is nil, which is unexpected.");
    return nil;
  }

  NSMutableArray *aggregateResults = [NSMutableArray array];

  [serverResponse enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSDictionary *resultDict = (NSDictionary *) obj;
    TPGameAggregateResult *result = [MTLJSONAdapter modelOfClass:TPGameAggregateResult.class fromJSONDictionary:resultDict error:nil];
    NSString *filePath = [self filePathForGameUniqueName:result.gameUniqueName
                                               forUserId:session.user.userId];

    TPGameAggregateResult *latest = (TPGameAggregateResult *) [self latestInSession:session persistedFilePath:filePath afterCompareWith:result];
    [aggregateResults addObject:latest];
  }];
  return aggregateResults;
}

+ (NSArray *) gameAggregateResultsFromLocalCopy {
  TPSessionService *session = [TPSessionService sharedInstance];
  if (session.user == nil) {
    // TODO: Need an error description.
    NSLog(@"User is nil, which is unexpected.");
    return nil;
  }

  NSMutableArray *aggregateResults = [NSMutableArray array];
  NSFileManager *fileManager = [NSFileManager defaultManager];
  [fileManager enumerateFilesInFolder:session.user.userId filterByFilename:kGameAggregateFilename usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSString *filePath = (NSString *) obj;
    TPGameAggregateResult *result = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

    [aggregateResults addObject:result];
  }];

  return aggregateResults;
}

- (instancetype) initWithGameUniqueName:(NSString *) gameUniqueName
                           userUniqueId:(NSString *) userUniqueId {
  self = [super init];
  if (self) {
    _resultId = -1;
    _gameUniqueName = [gameUniqueName copy];
    _highScore = 0.0;
    _highestLevel = 0;
    _userUniqueId = [userUniqueId copy];
  }
  return self;
}

- (void) updateAggregateResultWithGameResult:(TPGameResult *) result {
  [self updateStatsForGameResult:result];
}

#pragma mark - Concrete TPLocalSerializable methods

- (void) willSaveToServerInSession:(TPSessionService *) session {
  if (self.userUniqueId == nil || [self.userUniqueId isEqualToString:@""]) {
    assert(session.user.userId != nil && ![session.user.userId isEqualToString:@""]);
    self.userUniqueId = session.user.userId;
  }
}

- (TPLocalSerializableModel *) didSaveToServerInSession:(TPSessionService *) session withResponse:(id) responseObject {
  NSDictionary *resultsResponse = [responseObject valueForKey:kTPDataResponseKey];
  NSError *error;
  TPGameAggregateResult *result = [MTLJSONAdapter modelOfClass:TPGameAggregateResult.class fromJSONDictionary:resultsResponse error:&error];

  return result;
}

- (BOOL) isFirstTimeSave {
  return (self.resultId == -1);
}

- (NSString *) localSaveFilePath {
  return [TPGameAggregateResult filePathForGameUniqueName:self.gameUniqueName forUserId:self.userUniqueId];
}

- (NSString *) saveToUrlInSession:(TPSessionService *) session {
  NSString *url = [kTPAggregateGameResultsUrlRoot stringByReplacingOccurrencesOfString:@"GAMEUNIQUENAME" withString:self.gameUniqueName];
  return [NSString stringWithFormat:@"%@%@", [session gameServiceBaseURL], url];
}

- (NSString *) updateUrlInSession:(TPSessionService *) session {
  NSString *url = [kTPAggregateGameResultsUrlRoot stringByReplacingOccurrencesOfString:@"GAMEUNIQUENAME" withString:self.gameUniqueName];

  return [NSString stringWithFormat:@"%@%@/%ld", [session gameServiceBaseURL], url, (long)self.resultId];
}

#pragma mark - Stat calculations

- (void) updateStatsForGameResult:(TPGameResult *) gameResult {
  [self updateHighScoreFromScore:gameResult.conanicalScore];
  [self updateHighestLevelFromLevelCompleted:gameResult.levelCompleted];
  [self updateDailyStatsForDate:gameResult.playedAt];
}

- (void) updateHighScoreFromScore:(double) score {
  if (score > self.highScore) {
    self.highScore = score;
  }
}

- (void) updateHighestLevelFromLevelCompleted:(NSInteger) levelCompleted {
  if (levelCompleted > self.highestLevel) {
    self.highestLevel = levelCompleted;
  }
}

@end


text:
// Copyright 2017 The Kubernetes Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import chromeModule from '../chrome/module';
import componentsModule from '../common/components/module';
import csrfTokenModule from '../common/csrftoken/module';
import filtersModule from '../common/filters/module';
import namespaceModule from '../common/namespace/module';
import {ScaleService} from '../common/scaling/service';
import eventsModule from '../events/module';
import podModule from '../pod/module';

import {ReplicationControllerService} from './detail/delete_service';
import {replicationControllerInfoComponent} from './detail/info_component';
import {replicationControllerEventsResource, replicationControllerPodsResource} from './detail/stateconfig';
import {replicationControllerResource, replicationControllerServicesResource} from './detail/stateconfig';
import {replicationControllerCardComponent} from './list/card_component';
import {replicationControllerCardListComponent} from './list/cardlist_component';
import {replicationControllerCardMenuComponent} from './list/cardmenu_component';
import {replicationControllerListResource} from './list/stateconfig';
import stateConfig from './stateconfig';

/**
 * Angular module for the Replication Controller resource.
 */
export default angular
    .module(
        'kubernetesDashboard.replicationController',
        [
          'ngMaterial',
          'ngResource',
          'ui.router',
          chromeModule.name,
          componentsModule.name,
          eventsModule.name,
          filtersModule.name,
          namespaceModule.name,
          csrfTokenModule.name,
          podModule.name,
        ])
    .config(stateConfig)
    .component('kdReplicationControllerCard', replicationControllerCardComponent)
    .component('kdReplicationControllerCardList', replicationControllerCardListComponent)
    .component('kdReplicationControllerCardMenu', replicationControllerCardMenuComponent)
    .component('kdReplicationControllerInfo', replicationControllerInfoComponent)
    .service('kdReplicationControllerService', ReplicationControllerService)
    .service('kdScaleService', ScaleService)
    .factory('kdRCListResource', replicationControllerListResource)
    .factory('kdRCResource', replicationControllerResource)
    .factory('kdRCPodsResource', replicationControllerPodsResource)
    .factory('kdRCEventsResource', replicationControllerEventsResource)
    .factory('kdRCServicesResource', replicationControllerServicesResource);


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

001
018
019package org.apache.hadoop.io;
020
021import java.io.DataInput;
022import java.io.DataOutput;
023import java.io.IOException;
024
025import org.apache.hadoop.classification.InterfaceAudience;
026import org.apache.hadoop.classification.InterfaceStability;
027import org.apache.hadoop.conf.Configurable;
028import org.apache.hadoop.conf.Configuration;
029import org.apache.hadoop.util.ReflectionUtils;
030
031/**
032 * A wrapper for Writable instances.
033 * <p>
034 * When two sequence files, which have same Key type but different Value
035 * types, are mapped out to reduce, multiple Value types is not allowed.
036 * In this case, this class can help you wrap instances with different types.
037 * </p>
038 *
039 * <p>
040 * Compared with <code>ObjectWritable</code>, this class is much more effective,
041 * because <code>ObjectWritable</code> will append the class declaration as a String
042 * into the output file in every Key-Value pair.
043 * </p>
044 *
045 * <p>
046 * Generic Writable implements {@link Configurable} interface, so that it will be
047 * configured by the framework. The configuration is passed to the wrapped objects
048 * implementing {@link Configurable} interface <i>before deserialization</i>.
049 * </p>
050 *
051 * how to use it: <br>
052 * 1. Write your own class, such as GenericObject, which extends GenericWritable.<br>
053 * 2. Implements the abstract method <code>getTypes()</code>, defines
054 *    the classes which will be wrapped in GenericObject in application.
055 *    Attention: this classes defined in <code>getTypes()</code> method, must
056 *    implement <code>Writable</code> interface.
057 * <br><br>
058 *
059 * The code looks like this:
060 * <blockquote><pre>
061 * public class GenericObject extends GenericWritable {
062 *
063 *   private static Class[] CLASSES = {
064 *               ClassType1.class,
065 *               ClassType2.class,
066 *               ClassType3.class,
067 *               };
068 *
069 *   protected Class[] getTypes() {
070 *       return CLASSES;
071 *   }
072 *
073 * }
074 * </pre></blockquote>
075 *
076 * @since Nov 8, 2006
077 */
078@InterfaceAudience.Public
079@InterfaceStability.Stable
080public abstract class GenericWritable implements Writable, Configurable {
081
082  private static final byte NOT_SET = -1;
083
084  private byte type = NOT_SET;
085
086  private Writable instance;
087
088  private Configuration conf = null;
089
090  /**
091   * Set the instance that is wrapped.
092   *
093   * @param obj
094   */
095  public void set(Writable obj) {
096    instance = obj;
097    Class<? extends Writable> instanceClazz = instance.getClass();
098    Class<? extends Writable>[] clazzes = getTypes();
099    for (int i = 0; i < clazzes.length; i++) {
100      Class<? extends Writable> clazz = clazzes[i];
101      if (clazz.equals(instanceClazz)) {
102        type = (byte) i;
103        return;
104      }
105    }
106    throw new RuntimeException("The type of instance is: "
107                               + instance.getClass() + ", which is NOT registered.");
108  }
109
110  /**
111   * Return the wrapped instance.
112   */
113  public Writable get() {
114    return instance;
115  }
116
117  @Override
118  public String toString() {
119    return "GW[" + (instance != null ? ("class=" + instance.getClass().getName() +
120        ",value=" + instance.toString()) : "(null)") + "]";
121  }
122
123  @Override
124  public void readFields(DataInput in) throws IOException {
125    type = in.readByte();
126    Class<? extends Writable> clazz = getTypes()[type & 0xff];
127    try {
128      instance = ReflectionUtils.newInstance(clazz, conf);
129    } catch (Exception e) {
130      e.printStackTrace();
131      throw new IOException("Cannot initialize the class: " + clazz);
132    }
133    instance.readFields(in);
134  }
135
136  @Override
137  public void write(DataOutput out) throws IOException {
138    if (type == NOT_SET || instance == null)
139      throw new IOException("The GenericWritable has NOT been set correctly. type="
140                            + type + ", instance=" + instance);
141    out.writeByte(type);
142    instance.write(out);
143  }
144
145  /**
146   * Return all classes that may be wrapped.  Subclasses should implement this
147   * to return a constant array of classes.
148   */
149  abstract protected Class<? extends Writable>[] getTypes();
150
151  @Override
152  public Configuration getConf() {
153    return conf;
154  }
155
156  @Override
157  public void setConf(Configuration conf) {
158    this.conf = conf;
159  }
160
161}


text:
package graphene.web.components.navigation;

public class Breadcrumb {

}


text:
package io.weba.processor.flink.job;

import io.weba.processor.flink.functions.EventJsonFlapMap;
import io.weba.processor.flink.sink.ElasticsearchEventSinkFactory;
import io.weba.processor.flink.streaming.api.environment.ParametersExecutionEnvironmentFactory;
import io.weba.processor.flink.streaming.connectors.kafka.FlinkKafkaConsumerFactory;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.elasticsearch2.ElasticsearchSink;

public class IngestEventsElasticsearchJob {
    public static void main(String[] args) throws Exception {
        ParameterTool parameters = ParameterTool.fromArgs(args);

        StreamExecutionEnvironment environment = new ParametersExecutionEnvironmentFactory(parameters)
                .createExecutionEnvironment();

        DataStream<String> stream = environment
                .addSource(new FlinkKafkaConsumerFactory(parameters).createConsumer())
                .name("Consume messages from Kafka.")
                .rebalance();

        DataStream<Tuple2<String, String>> events = stream
                .flatMap(new EventJsonFlapMap())
                .name("Run Eventor, serialize event and produce tuple.");

        ElasticsearchSink sink = new ElasticsearchEventSinkFactory(parameters).create();

        events.addSink(sink)
                .name("Push event to Elasticsearch.");

        environment.execute("Ingest events from Kafka and index in Elasticsearch.");
    }
}


text:
/*
 * crypto_sign/try.c version 20140423
 * D. J. Bernstein
 * Public domain.
 * Auto-generated by trygen.py; do not edit.
 */

#include "crypto_sign.h"
#include "try.h"
#include "randombytes.h"

const char *primitiveimplementation = crypto_sign_IMPLEMENTATION;

#define TUNE_BYTES 1536
#ifdef SMALL
#define MAXTEST_BYTES 128
#else
#define MAXTEST_BYTES 4096
#endif
#ifdef SMALL
#define LOOPS 8
#else
#define LOOPS 64
#endif

static unsigned char *p;
static unsigned char *s;
static unsigned char *m;
static unsigned char *c;
static unsigned char *t;
static unsigned char *p2;
static unsigned char *s2;
static unsigned char *m2;
static unsigned char *c2;
static unsigned char *t2;
#define plen crypto_sign_PUBLICKEYBYTES
#define slen crypto_sign_SECRETKEYBYTES
unsigned long long mlen;
unsigned long long clen;
unsigned long long tlen;

void preallocate(void)
{
#ifdef RAND_R_PRNG_NOT_SEEDED
  RAND_status();
#endif
}

void allocate(void)
{
  unsigned long long alloclen = 0;
  if (alloclen < TUNE_BYTES) alloclen = TUNE_BYTES;
  if (alloclen < MAXTEST_BYTES + crypto_sign_BYTES) alloclen = MAXTEST_BYTES + crypto_sign_BYTES;
  if (alloclen < crypto_sign_PUBLICKEYBYTES) alloclen = crypto_sign_PUBLICKEYBYTES;
  if (alloclen < crypto_sign_SECRETKEYBYTES) alloclen = crypto_sign_SECRETKEYBYTES;
  p = alignedcalloc(alloclen);
  s = alignedcalloc(alloclen);
  m = alignedcalloc(alloclen);
  c = alignedcalloc(alloclen);
  t = alignedcalloc(alloclen);
  p2 = alignedcalloc(alloclen);
  s2 = alignedcalloc(alloclen);
  m2 = alignedcalloc(alloclen);
  c2 = alignedcalloc(alloclen);
  t2 = alignedcalloc(alloclen);
}

void predoit(void)
{
  crypto_sign_keypair(p,s);
  mlen = TUNE_BYTES;
  clen = 0;
  randombytes(m,mlen);
}

void doit(void)
{
  crypto_sign(c,&clen,m,mlen,s);
  crypto_sign_open(t,&tlen,c,clen,p);
}

void test(void)
{
  unsigned long long loop;

  for (loop = 0;loop < LOOPS;++loop) {
    mlen = myrandom() % (MAXTEST_BYTES + 1);

    output_prepare(p2,p,plen);
    output_prepare(s2,s,slen);
    if (crypto_sign_keypair(p,s) != 0) fail("crypto_sign_keypair returns nonzero");
    checksum(p,plen);
    checksum(s,slen);
    output_compare(p2,p,plen,"crypto_sign_keypair");
    output_compare(s2,s,slen,"crypto_sign_keypair");

    clen = mlen + crypto_sign_BYTES;
    output_prepare(c2,c,clen);
    input_prepare(m2,m,mlen);
    memcpy(s2,s,slen);
    double_canary(s2,s,slen);
    if (crypto_sign(c,&clen,m,mlen,s) != 0) fail("crypto_sign returns nonzero");
    if (clen < mlen) fail("crypto_sign returns smaller output than input");
    if (clen > mlen + crypto_sign_BYTES) fail("crypto_sign returns more than crypto_sign_BYTES extra bytes");
    checksum(c,clen);
    output_compare(c2,c,clen,"crypto_sign");
    input_compare(m2,m,mlen,"crypto_sign");
    input_compare(s2,s,slen,"crypto_sign");

#if crypto_sign_DETERMINISTIC == 1
    double_canary(c2,c,clen);
    double_canary(m2,m,mlen);
    double_canary(s2,s,slen);
    if (crypto_sign(c2,&clen,m2,mlen,s2) != 0) fail("crypto_sign returns nonzero");
    if (memcmp(c2,c,clen) != 0) fail("crypto_sign is nondeterministic");
#endif

#if crypto_sign_DETERMINISTIC == 1
    double_canary(c2,c,clen);
    double_canary(m2,m,mlen);
    double_canary(s2,s,slen);
    if (crypto_sign(m2,&clen,m2,mlen,s) != 0) fail("crypto_sign with m=c overlap returns nonzero");
    if (memcmp(m2,c,clen) != 0) fail("crypto_sign does not handle m=c overlap");
    memcpy(m2,m,mlen);
    if (crypto_sign(s2,&clen,m,mlen,s2) != 0) fail("crypto_sign with s=c overlap returns nonzero");
    if (memcmp(s2,c,clen) != 0) fail("crypto_sign does not handle s=c overlap");
    memcpy(s2,s,slen);
#endif

    tlen = clen;
    output_prepare(t2,t,tlen);
    memcpy(c2,c,clen);
    double_canary(c2,c,clen);
    memcpy(p2,p,plen);
    double_canary(p2,p,plen);
    if (crypto_sign_open(t,&tlen,c,clen,p) != 0) fail("crypto_sign_open returns nonzero");
    if (tlen != mlen) fail("crypto_sign_open does not match mlen");
    if (memcmp(t,m,mlen) != 0) fail("crypto_sign_open does not match m");
    checksum(t,tlen);
    output_compare(t2,t,clen,"crypto_sign_open");
    input_compare(c2,c,clen,"crypto_sign_open");
    input_compare(p2,p,plen,"crypto_sign_open");

    double_canary(t2,t,tlen);
    double_canary(c2,c,clen);
    double_canary(p2,p,plen);
    if (crypto_sign_open(t2,&tlen,c2,clen,p2) != 0) fail("crypto_sign_open returns nonzero");
    if (memcmp(t2,t,tlen) != 0) fail("crypto_sign_open is nondeterministic");

    double_canary(t2,t,tlen);
    double_canary(c2,c,clen);
    double_canary(p2,p,plen);
    if (crypto_sign_open(c2,&tlen,c2,clen,p) != 0) fail("crypto_sign_open with c=t overlap returns nonzero");
    if (memcmp(c2,t,tlen) != 0) fail("crypto_sign_open does not handle c=t overlap");
    memcpy(c2,c,clen);
    if (crypto_sign_open(p2,&tlen,c,clen,p2) != 0) fail("crypto_sign_open with p=t overlap returns nonzero");
    if (memcmp(p2,t,tlen) != 0) fail("crypto_sign_open does not handle p=t overlap");
    memcpy(p2,p,plen);

    c[myrandom() % clen] += 1 + (myrandom() % 255);
    if (crypto_sign_open(t,&tlen,c,clen,p) == 0)
      if ((tlen != mlen) || (memcmp(t,m,mlen) != 0))
        fail("crypto_sign_open allows trivial forgeries");
    c[myrandom() % clen] += 1 + (myrandom() % 255);
    if (crypto_sign_open(t,&tlen,c,clen,p) == 0)
      if ((tlen != mlen) || (memcmp(t,m,mlen) != 0))
        fail("crypto_sign_open allows trivial forgeries");
    c[myrandom() % clen] += 1 + (myrandom() % 255);
    if (crypto_sign_open(t,&tlen,c,clen,p) == 0)
      if ((tlen != mlen) || (memcmp(t,m,mlen) != 0))
        fail("crypto_sign_open allows trivial forgeries");
  }
}


text:
require('../scss/main.scss');

// Import JavaScript vendor files
require('../../node_modules/waypoints/lib/noframework.waypoints.js');
require('../../node_modules/smoothscroll/smoothscroll.js');

// Import JavaScript custom files
require('./scripts/nav.js');
require('./scripts/splash-scroll-down.js');
require('./scripts/splash-3d-model.js');
require('./scripts/services-3d-models.js');
require('./scripts/randomize-teammates.js');
require('./scripts/reveal-subtitles.js');
require('./scripts/reveal-services.js');
require('./scripts/reveal-article.js');
require('./scripts/reveal-brands.js');
require('./scripts/reveal-bio.js');
require('./scripts/reveal-stack.js');
require('./scripts/reveal-jobs.js');
require('./scripts/reveal-contacts.js');
require('./scripts/navigate-jobs.js');
require('./scripts/fix-job-selector.js');
require('./scripts/hide-post-sharing.js');


text:
package junit.org.rapidpm.ddi.reflections;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.rapidpm.ddi.reflections.ReflectionUtils;

/**
 * ReflectionUtils Tester.
 *
 * @author <Authors name>
 * @version 1.0
 * @since
Jan 25, 2016

 */
public class ReflectionUtilsTest {

  @BeforeEach
  public void before() {
  }

  @AfterEach
  public void after() {
  }

  /**
   * Method: checkInterface(final Type aClass, Class targetInterface)
   */
  @Test
  public void testCheckInterface() {

    final ReflectionUtils utils = new ReflectionUtils();

    Assertions.assertTrue(utils.checkInterface(ServiceImpl_A.class, Service.class));
    Assertions.assertFalse(utils.checkInterface(Service.class, ServiceImpl_A.class));

    Assertions.assertFalse(utils.checkInterface(ServiceImpl_A.class, NoService.class));
    Assertions.assertFalse(utils.checkInterface(NoService.class, ServiceImpl_A.class));

    Assertions.assertFalse(utils.checkInterface(NoService.class, Service.class));
    Assertions.assertFalse(utils.checkInterface(Service.class, NoService.class));

    Assertions.assertFalse(utils.checkInterface(Service.class, ServiceLev2.class));
    Assertions.assertTrue(utils.checkInterface(ServiceLev2.class, Service.class));

    Assertions.assertTrue(utils.checkInterface(ServiceImpl_B.class, Service.class));
    Assertions.assertFalse(utils.checkInterface(Service.class, ServiceImpl_B.class));

    Assertions.assertFalse(utils.checkInterface(ServiceImpl_B.class, NoService.class));
    Assertions.assertFalse(utils.checkInterface(NoService.class, ServiceImpl_B.class));

  }

  public interface Service {
  }

  public interface ServiceLev2 extends Service {
  }

  public interface NoService {
  }

  public static class ServiceImpl_A implements Service {
  }

  public static class ServiceImpl_B implements ServiceLev2 {
  }

}


text:
package org.bitcoins.core.crypto

/**
 * The result type returned by checking a signature
 */
sealed trait TransactionSignatureCheckerResult {
  /**
   * Indicates if the transaction signature checker was successful or failed
   */
  def isValid: Boolean
}

/**
 * Represents the case that the signatures checked inside of the transaction were
 * all validly encoded as per the script verify flag & that the signatures
 * were valid when checked against the public keys
 */
case object SignatureValidationSuccess extends TransactionSignatureCheckerResult {
  def isValid = true
}

/** Indicates that there was an error when evaluating the signature of a transaction */
sealed trait SignatureValidationError extends TransactionSignatureCheckerResult {
  def isValid = false
}

/**
 * Signature validation failed because a signature was not encoded
 * per the BIP66 rules [[https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki#specification]]
 */
case object SignatureValidationErrorNotStrictDerEncoding extends SignatureValidationError

/**
 * Signature validation failed because there were not enough correct signatures for the transaction
 * we were given
 */
case object SignatureValidationErrorIncorrectSignatures extends SignatureValidationError

/**
 * This indicates that the signature validation failed because we have more signatures left to check
 * than public keys remaining to check them against
 * see [[https://github.com/bitcoin/bitcoin/blob/master/src/script/interpreter.cpp#L914-915]]
 */
case object SignatureValidationErrorSignatureCount extends SignatureValidationError

/**
 * This indicates that the public key was not encoded correctly according to this function
 * [[https://github.com/bitcoin/bitcoin/blob/528472111b4965b1a99c4bcf08ac5ec93d87f10f/src/script/interpreter.cpp#L214-L223]]
 */
case object SignatureValidationErrorPubKeyEncoding extends SignatureValidationError
/**
 * This indicates that the digital signature did not have a Low S value as per BIP62
 * [[https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#Low_S_values_in_signatures]]
 */
case object SignatureValidationErrorHighSValue extends SignatureValidationError

/**
 * Fails the script if the hash type is not defined on a digital signature
 */
case object SignatureValidationErrorHashType extends SignatureValidationError

/**
 * Fails the script if the given public key was not compressed and the [[org.bitcoins.core.script.flag.ScriptVerifyWitnessPubKeyType]]
 * flag was set
 */
case object SignatureValidationErrorWitnessPubKeyType extends SignatureValidationError

/**
 * Fails the script if a an invalid signature is not an empty byte vector
 * See BIP146
 * [[https://github.com/bitcoin/bips/blob/master/bip-0146.mediawiki#nullfail]]
 */
case object SignatureValidationErrorNullFail extends SignatureValidationError


text:
- start = 2021-02-14 03:30
- end = 2021-02-14 03:50
- reviewer = Stefan Hanreich <stefanhani@gmail.com>

## Signature

`ssize_t keySetName(Key *key, const char *newname)`

## Checklist

#### Doxygen

(bullet points are in order of appearance)

- [x] First line explains briefly what the function does
- [ ] Simple example or snippet how to use the function
       - [ ] add
- [ ] Longer description of function containing common use cases
- [ ] Description of functions reads nicely
- [ ] `@pre`
       - [ ] @pre newName must be a valid name
       - [ ] @pre must not be a read-only key
       - [ ] @pre must not have been inserted before
- [ ] `@post`
       - [ ] @post Key has (possibly modified) newName as name
- [ ] `@invariant`
       - [ ] add
- [x] `@param` for every parameter
- [ ] `@return` / `@retval`
       - [ ] add `@retval` -1 if key is read-only
- [ ] `@since`
       - [ ] add
- [x] `@ingroup`
- [ ] `@see`
       - [ ] add `keySetNameSpace()`

### Naming

- [x] Abbreviations used in function names must be defined in the
      [Glossary](/doc/help/elektra-glossary.md)
- [x] Function names should neither be too long, nor too short
- [x] Function name should be clear and unambiguous
- [x] Abbreviations used in parameter names must be defined in the
      [Glossary](/doc/help/elektra-glossary.md)
- [x] Parameter names should neither be too long, nor too short
- [x] Parameter names should be clear and unambiguous

### Compatibility

(only in PRs)

- [Symbol versioning](/doc/dev/symbol-versioning.md)
  is correct for breaking changes
- ABI/API changes are forward-compatible (breaking backwards-compatibility
  to add additional symbols is fine)

### Parameter & Return Types

- [x] Function parameters should use enum types instead of boolean types
      wherever sensible
- [x] Wherever possible, function parameters should be `const`
- [ ] Wherever possible, return types should be `const`
       - [ ] might be possible to make it `const`
- [x] Functions should have the least amount of parameters feasible

### Structural Clarity

- [x] Functions should do exactly one thing
- [x] Function name has the appropriate prefix
- [ ] Order of signatures in kdb.h.in is the same as Doxygen
       - [ ] swapped with functions for unescaped
- [x] No functions with similar purpose exist

### Memory Management

- [x] Memory Management should be handled by the function wherever possible

### Extensibility

- [x] Function is easily extensible, e.g., with flags
- [ ] Documentation does not impose limits, that would hinder further extensions
       - [ ] behavior on invalid names

### Tests

- [ ] Function code is fully covered by tests
       - [ ] test_bit "CANNOT" fail, so might not be necessary to cover this
       for now should be made more resistant to future changes
- [ ] All possible error states are covered by tests
       - [ ] test read-only keys
- All possible enum values are covered by tests
- [ ] No inconsistencies between tests and documentation
       - [ ] https://github.com/ElektraInitiative/libelektra/blob/master/tests/abi/testabi_key.c#L357
       checks for -1 if null pointer is provided
       documentation says 0 will be returned
       - [ ] Documentation says name will be `""` after an invalid name
       Tests show that name stays unchanged
       https://github.com/ElektraInitiative/libelektra/blob/master/tests/abi/testabi_key.c#L601
       - [ ] Documentations should include stripping trailing `/`

## Summary

## Other Issues discovered (unrelated to function)


text:
//
//  RXLoadingHUD.h
//  RXExtenstion
//
//  Created by srx on 16/7/6.
//  Copyright © 2016年 https://github.com/srxboys. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

/*
 三点 动画(参考网络 改编而来)

 */

const CGFloat _default_hud_widthHeigth = 8;
const CGFloat _default_hud_space = 20;
const CGFloat _default_hudView_width = _default_hud_space * 2 + _default_hud_widthHeigth;

@interface RXLoadingHUD : UIView

@property (nonatomic, strong) UIColor *hudColor;

/** 每个 圆点的大小 默认为=8*/
@property (nonatomic, assign,readonly) CGFloat hud_widthHeight;
/** 每个 圆点的间距(_hud_widthHeight 大小包括在内) 默认=20 */
@property (nonatomic, assign,readonly) CGFloat hud_space;
/** 该动画的宽度 默认=【_hud_space * 2 + _hud_widthHeight】 */
@property (nonatomic, assign, readonly) CGFloat hudView_width;

/** 默认圆圆的大小*/
- (instancetype)initWithFrame:(CGRect)frame;

/** 自定义圆圆的大小*/
- (instancetype)initCustomWithFrame:(CGRect)frame hud_WH:(CGFloat)hud_wh hud_space:(CGFloat)hub_space;

-(void)showAnimated:(BOOL)animated;
-(void)hide;

@end


text:
<?php
/**
 * This file is part of the Ray.ValidateModule package.
 *
 * @license http://opensource.org/licenses/MIT MIT
 */
namespace Ray\Validation;

interface ValidationInterface extends FailureInterface
{
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>Module dispatcher</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="EDoc">

Overview

Module dispatcher

Function Index

Function Details

Function Index

dispatch_to/2	dispatches the Requested command to the internal node.

table_update/2	send the table operatin to the internal node loop.

Function Details

dispatch_to/2

<tt>dispatch_to(Request, X2) -> any()</tt>

dispatches the Requested command to the internal node

table_update/2

<tt>table_update(Command, Data) -> any()</tt>

send the table operatin to the internal node loop

Overview

Generated by EDoc, Aug 23 2009, 15:33:05.


text:
module.exports = Chat

var debug = require('debug')('snapchat:chat')
var async = require('async')
var extend = require('xtend')
var Promise = require('bluebird')

var constants = require('../lib/constants')
var StringUtils = require('../lib/string-utils')

var Conversation = require('../models/conversation')

/**
 * Snapchat wrapper for chat-related API calls.
 *
 * @class
 * @param {Object} opts
 */
function Chat (client, opts) {
  var self = this
  if (!(self instanceof Chat)) return new Chat(client, opts)
  if (!opts) opts = {}

  self.client = client
}

/**
 * Sends the typing notification to the given users.
 *
 * @param {Array<string>} recipients An array of username strings.
 * @param {function} cb
 */
Chat.prototype.sendTypingToUsers = function (recipients, cb) {
  var self = this
  debug('Chat.sendTypingToUsers')

  return self._sendTyping(recipients, cb)
}

/**
 * Sends the typing notification to a single user.
 *
 * @param {string} username
 * @param {function} cb
 */
Chat.prototype.sendTypingToUser = function (username, cb) {
  var self = this
  debug('Chat.sendTypingToUser (%s)', username)

  return self._sendTyping([ username ], cb)
}

/**
 * Marks all chat messages in a conversation as read.
 *
 * @TODO currently not working
 * @param {Conversation} conversation
 * @param {function} cb
 */
Chat.prototype.markRead = function (conversation, cb) {
  var self = this
  debug('Chat.markRead (%s)', conversation.identifier)

  return self.client.sendEvents([
    {
      'eventName': 'CHAT_TEXT_VIEWED',
      'params': {
        'id': conversation.identifier
      },
      'ts': StringUtils.timestamp() | 0
    }
  ], null, cb)
}

/**
 * Retrieves the conversation auth mac and payload for a conversation with username.
 *
 * @param {string} username
 * @param {function} cb
 */
Chat.prototype.conversationAuth = function (username, cb) {
  var self = this

  return new Promise(function (resolve, reject) {
    debug('Chat.conversationAuth (%s)', username)

    var cid = StringUtils.SCIdentifier(self.client.username, username)

    self.client.post(constants.endpoints.chat.authToken, {
      'username': self.client.username,
      'conversation_id': cid
    }, function (err, result) {
      if (err) {
        return reject(err)
      } else if (result) {
        result = result['messaging_auth']

        if (result && result['mac'] && result['payload']) {
          return resolve(result)
        }

        return reject(new Error('Chat.conversationAuth parse error'))
      }
    })
  }).nodeify(cb)
}

/**
 * Retrieves the conversation with \e username.
 *
 * @param {string} username
 * @param {function} cb
 */
Chat.prototype.conversationWithUser = function (username, cb) {
  var self = this

  return new Promise(function (resolve, reject) {
    debug('Chat.conversationWithUser (%s)', username)

    self.conversationsWithUsers([ username ], function (err, results) {
      if (err) {
        return reject(err)
      } else {
        return resolve(results.conversations[0])
      }
    })
  }).nodeify(cb)
}

/**
 * Fetches the conversations for all users in \e usernames
 *
 * @param {Array<string>} usernames
 * @param {function} cb
 */
Chat.prototype.conversationsWithUsers = function (usernames, cb) {
  var self = this

  return new Promise(function (resolve, reject) {
    debug('Chat.conversationsWithUsers (%j)', usernames)

    var results = {
      conversations: [ ],
      failed: [ ],
      errors: [ ]
    }

    var messages = [ ]

    async.eachLimit(usernames, 4, function (username, cb) {
      self.conversationAuth(username, function (err, auth) {
        if (err) {
          results.failed.push(username)
          results.errors.push(err)
          return cb(err)
        } else {
          var identifier = StringUtils.uniqueIdentifer()
          var header = {
            'auth': auth,
            'to': [ username ],
            'conv_id': StringUtils.SCIdentifier(self.client.username, username),
            'from': self.client.username,
            'conn_sequence_number': 0
          }

          var first = {
            'presences': { },
            'receiving_video': false,
            'supports_here': true,
            'header': header,
            'retried': false,
            'id': identifier,
            'type': 'presence'
          }

          first.presences[self.client.username] = true
          first.presences[username] = false

          var header2 = extend(header, {
            'conv_id': StringUtils.SCIdentifier(username, self.client.username)
          })

          var second = {
            'presences': { },
            'receiving_video': false,
            'supports_here': true,
            'header': header2,
            'retried': false,
            'id': identifier,
            'type': 'presence'
          }

          second.presences[self.client.username] = true
          second.presences[username] = false

          messages.push(first)
          messages.push(second)
          return cb(null)
        }
      })
    }, function () {
      self.client.post(constants.endpoints.chat.sendMessage, {
        'auth_token': self.client.authToken,
        'messages': JSON.stringify(messages),
        'username': self.client.username
      }, function (err, result) {
        if (err) {
          return reject(err)
        } else if (result) {
          if (result.conversations) {
            results.conversations = result.conversations.map(function (convo) {
              return new Conversation(convo)
            })
            return resolve(results)
          } else {
            debug('Chat.conversationsWithUsers parse error %j', result)
          }
        }

        return reject(new Error('Chat.conversationsWithUsers parse error'))
      })
    })
  }).nodeify(cb)
}

/**
 * Clears the conversation with the given identifier.
 *
 * @param {string} identifier The identifier of the conversation to clear.
 * @param {function} cb
 */
Chat.prototype.clearConversationWithIdentifier = function (identifier, cb) {
  var self = this
  debug('Chat.clearConversationWithIdentifier (%s)', identifier)

  return self.client.post(constants.endpoints.chat.clearConvo, {
    'conversation_id': identifier,
    'username': self.client.username
  }, cb)
}

/**
 * Clears the entire feed.
 *
 * @param {function} cb
 */
Chat.prototype.clearFeed = function (cb) {
  var self = this
  debug('Chat.clearFeed')

  return self.client.post(constants.endpoints.chat.clearFeed, {
    'username': self.client.username
  }, cb)
}

/**
 * Sends a message \e message to \e username.
 *
 * @param {string} message The message to send.
 * @param {Array<string>} username The username of the recipient.
 * @param {function} cb
 */
Chat.prototype.sendMessage = function (message, username, cb) {
  var self = this

  return new Promise(function (resolve, reject) {
    debug('Chat.sendMessage ("%s", %s)', message, username)

    self.sendMessageToUsers(message, [ username ], function (err, results) {
      if (err) {
        return reject(err)
      } else if (!results.conversations.length) {
        return reject(new Error('Chat.conversationWithUser error'))
      } else {
        return resolve(results.conversations[0])
      }
    })
  }).nodeify(cb)
}

/**
 * Sends a message \e message to each user in \e usernames.
 *
 * @TODO: what to do if message fails to send
 *
 * @param {string} message The message to send.
 * @param {Array<string>} usernames An array of username strings as recipients.
 * @param {function} cb
 */
Chat.prototype.sendMessageToUsers = function (message, usernames, cb) {
  var self = this

  return new Promise(function (resolve, reject) {
    debug('Chat.sendMessageToUsers ("%s", %j)', message, usernames)

    var results = {
      conversations: [ ],
      failed: [ ],
      errors: [ ]
    }

    self.conversationsWithUsers(usernames, function (err, convoResults) {
      if (err) {
        return reject(err)
      }

      results.failed = convoResults.failed
      results.errors = convoResults.errors

      var messages = convoResults.conversations.map(function (convo) {
        var identifier = StringUtils.uniqueIdentifer()
        var sequenceNum = convo.state['conversation_state']
        sequenceNum = sequenceNum && sequenceNum['user_sequences']
        sequenceNum = sequenceNum && sequenceNum[self.client.username]
        sequenceNum = sequenceNum | 0

        var header = {
          'auth': convo.messagingAuth,
          'to': [ convo.recipient ],
          'from': self.client.username,
          // 'conn_sequence_number': 1,
          'conn_sequ_num': 1,
          'conv_id': convo.identifier
        }

        return {
          'body': { 'type': 'text', 'text': message },
          'chat_message_id': identifier,
          'seq_num': sequenceNum + 1,
          'timestamp': StringUtils.timestamp(),
          'retried': false,
          'id': identifier,
          'type': 'chat_message',
          'header': header
        }
      })

      if (!messages.length) {
        debug('Chat.sendMessageToUsers error retrieving conversations')
        return reject(new Error('Chat.sendMessageToUsers error retrieving conversations'))
      } else {
        self.client.post(constants.endpoints.chat.sendMessage, {
          'auth_token': self.client.authToken,
          'messages': JSON.stringify(messages),
          'username': self.client.username
        }, function (err, result) {
          if (err) {
            return reject(err)
          } else if (result) {
            if (result.conversations && result.conversations) {
              results.conversations = result.conversations.map(function (convo) {
                return new Conversation(convo)
              })
              return resolve(results)
            } else {
              debug('Chat.sendMessageToUsers parse error %j', result)
            }
          }

          return reject(new Error('Chat.sendMessageToUsers parse error'))
        })
      }
    })
  }).nodeify(cb)
}

/**
 * Loads another page of conversations in the feed after the given conversation.
 *
 * This method will update client.session.conversations accordingly.
 *
 * @param {Conversation} conversation The conversation after which to load more conversations.
 * @param {function} cb
 */
Chat.prototype.loadConversationsAfter = function (conversation, cb) {
  var self = this

  return new Promise(function (resolve, reject) {
    debug('Chat.loadConversationsAfter')

    if (!conversation || !conversation.pagination || !conversation.pagination.length) {
      return resolve([ ])
    }

    self.client.post(constants.endpoints.chat.conversations, {
      'username': self.client.username,
      'checksum': StringUtils.md5HashToHex(self.client.username),
      'offset': conversation.pagination
    }, function (err, result) {
      if (err) {
        return reject(err)
      } else if (result) {
        result = result['conversations_response']

        if (result) {
          var conversations = result.map(function (result) {
            var convo = new Conversation(result)

            self.client.session.conversations.push(convo)
            return convo
          })

          return resolve(conversations)
        }

        return reject(new Error('Chat.loadConversationsAfter parse error'))
      }
    })
  }).nodeify(cb)
}

/**
 * Loads all conversations into the current session.
 *
 * This method will update client.session.conversations accordingly.
 * @param {function} cb
 */
Chat.prototype.loadAllConversations = function (cb) {
  var self = this

  return new Promise(function (resolve, reject) {
    debug('Chat.loadAllConversations')

    self.client.updateSession(function (err) {
      if (err) {
        return reject(err)
      }

      var conversations = [ ]
      var last = self.client.session.conversations[self.client.session.conversations.length - 1]

      function loadPage () {
        self.loadConversationsAfter(last, function (err, convos) {
          if (err) {
            return reject(err)
          } else if (convos.length > 0) {
            conversations = conversations.concat(convos)
            last = convos[convos.length - 1]
            return loadPage()
          }

          conversations.forEach(function (convo) {
            self.client.session.conversations.push(convo)
          })
          return resolve(conversations)
        })
      }

      loadPage()
    })
  }).nodeify(cb)
}

/**
 * Loads more messages after the given message or cash transaction.
 *
 * @param {Transaction|Message} messageOrTransaction any object conforming to Pagination \b EXCEPT AN \C Conversation.
 * @warning Do not pass an Conversation object to messageOrTransaction. Doing so will throw an exception.
 * @param {function} cb
 */
Chat.prototype.loadMessagesAfterPagination = function (messageOrTransaction, cb) {
  var self = this

  return new Promise(function (resolve, reject) {
    debug('Chat.loadMessagesAfterPagination')

    if (messageOrTransaction instanceof Conversation ||
       !messageOrTransaction.conversationIdentifier) {
      return reject(new Error('Chat.loadMessagesAfterPagination invalid param'))
    }

    if (!messageOrTransaction ||
        !messageOrTransaction.pagination ||
        !messageOrTransaction.pagination.length) {
      return resolve()
    }

    self.clients.post(constants.endpoints.chat.conversation, {
      'username': self.client.username,
      'conversation_id': messageOrTransaction.conversationIdentifier,
      'offset': messageOrTransaction.pagination
    }, function (err, result) {
      if (err) {
        return reject(err)
      } else if (result && result.conversation) {
        return resolve(new Conversation(result.conversation))
      }

      return reject(new Error('Chat.loadConversationsAfter parse error'))
    })
  }).nodeify(cb)
}

/**
 * Loads all messages in the given thread and adds them to that Conversation object.
 *
 * @param {Conversation} conversation The conversation to load completely.
 * @param {function} cb
 */
Chat.prototype.loadFullConversation = function (conversation, cb) {
  var self = this

  return new Promise(function (resolve, reject) {
    debug('Chat.loadFullConversation')

    var last = conversation.messages[conversation.messages.length - 1]

    function loadPage () {
      self.loadMessagesAfterPagination(last, function (err, convo) {
        if (err) {
          return reject(err)
        } else if (convo) {
          last = convo.messages[convo.messages.length - 1]
          conversation.addMessagesFromConversation(convo)
          return loadPage()
        }

        return resolve()
      })
    }

    loadPage()
  }).nodeify(cb)
}

/**
 * @private
 */
Chat.prototype._sendTyping = function (recipients, cb) {
  var self = this

  return self.client.post(constants.endpoints.chat.typing, {
    'recipient_usernames': JSON.stringify(recipients),
    'username': self.client.username
  }, cb)
}


text:
package com.qSilver.render.gui;

import com.bStone.engine.render.drawable.render.Render;
import com.bStone.util.ColorUtil;
import com.qSilver.render.string.StringRenderer;

public class GuiLabel extends Gui
{
	protected String label;
	private int labelAlignment;

	public GuiLabel(float parPosX, float parPosY, float parDepth, String parLabel, int parAlignment)
	{
		super(parPosX, parPosY, parDepth, StringRenderer.getStringWidth(parLabel), StringRenderer.getStringHeight(parLabel));
		this.label = parLabel;
		this.labelAlignment = parAlignment;
	}

	public GuiLabel setLabel(String parLabel)
	{
		this.label = parLabel;
		return this;
	}

	public GuiLabel setAlignment(int parAlignment)
	{
		this.labelAlignment = parAlignment;
		return this;
	}

	@Override
	public void onUpdate()
	{
		Render.gl().glPushMatrix();
		{
			Render.gl().glTranslatef(this.posX, this.posY, 0F);
			Render.gl().glScalef(this.scale, this.scale, 1F);

			Render.gl().glColor3f(ColorUtil.getRed(this.color) / 255F, ColorUtil.getGreen(this.color) / 255F, ColorUtil.getBlue(this.color) / 255F);
			StringRenderer.renderString(this.label, 0, 0, 1F, this.labelAlignment);
		}
		Render.gl().glPopMatrix();
	}

	@Override
	public void onClick(int parButton) {}

	public String getLabel()
	{
		return this.label;
	}

	public int getAlignment()
	{
		return this.labelAlignment;
	}
}


text: frontend util packs from my experience


text:
[![Build Status](https://api.travis-ci.org/sqlmapproject/sqlmap.svg?branch=master)](https://api.travis-ci.org/sqlmapproject/sqlmap) [![Python 2.6|2.7](https://img.shields.io/badge/python-2.6|2.7-yellow.svg)](https://www.python.org/) [![License](https://img.shields.io/badge/license-GPLv2-red.svg)](https://raw.githubusercontent.com/sqlmapproject/sqlmap/master/doc/COPYING) [![Twitter](https://img.shields.io/badge/twitter-@sqlmap-blue.svg)](https://twitter.com/sqlmap)

sqlmap é uma ferramenta de teste de penetração de código aberto que automatiza o processo de detecção e exploração de falhas de injeção SQL. Com essa ferramenta é possível assumir total controle de servidores de banco de dados em páginas web vulneráveis, inclusive de base de dados fora do sistema invadido. Ele possui um motor de detecção poderoso, empregando as últimas e mais devastadoras técnicas de teste de penetração por SQL Injection, que permite acessar a base de dados, o sistema de arquivos subjacente e executar comandos no sistema operacional.

Imagens
----

![Imagem](https://raw.github.com/wiki/sqlmapproject/sqlmap/images/sqlmap_screenshot.png)

Você pode visitar a [coleção de imagens](https://github.com/sqlmapproject/sqlmap/wiki/Screenshots) que demonstra alguns dos recursos apresentados na wiki.

Instalação
----

Você pode baixar o arquivo tar mais recente clicando [aqui]
(https://github.com/sqlmapproject/sqlmap/tarball/master) ou o arquivo zip mais recente clicando [aqui](https://github.com/sqlmapproject/sqlmap/zipball/master).

De preferência, você pode baixar o sqlmap clonando o repositório [Git](https://github.com/sqlmapproject/sqlmap):

    git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev

sqlmap funciona em [Python](http://www.python.org/download/) nas versões **2.6.x** e **2.7.x** em todas as plataformas.

Como usar
----

Para obter uma lista das opções básicas faça:

    python sqlmap.py -h

Para obter a lista completa de opções faça:

    python sqlmap.py -hh

Você pode encontrar alguns exemplos [aqui](https://asciinema.org/a/46601).
Para ter uma visão geral dos recursos do sqlmap, lista de recursos suportados e a descrição de todas as opções, juntamente com exemplos, aconselhamos que você consulte o [manual do usuário](https://github.com/sqlmapproject/sqlmap/wiki).

Links
----

* Homepage: http://sqlmap.org
* Download: [.tar.gz](https://github.com/sqlmapproject/sqlmap/tarball/master) ou [.zip](https://github.com/sqlmapproject/sqlmap/zipball/master)
* Commits RSS feed: https://github.com/sqlmapproject/sqlmap/commits/master.atom
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
* Manual do Usuário: https://github.com/sqlmapproject/sqlmap/wiki
* Perguntas frequentes (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
* Mailing list subscription: https://lists.sourceforge.net/lists/listinfo/sqlmap-users
* Mailing list RSS feed: http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
* Mailing list archive: http://news.gmane.org/gmane.comp.security.sqlmap
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
* Demonstrações: [#1](http://www.youtube.com/user/inquisb/videos) e [#2](http://www.youtube.com/user/stamparm/videos)
* Imagens: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots


text:
@implementation Adoption

@dynamic polygons;
@dynamic timestamp;
@dynamic userId;
@dynamic wid;
@dynamic zoneName;
@dynamic countryName;
@dynamic year;
@dynamic serverURL;

- (void) awakeFromInsert
{
    [super awakeFromInsert];
    [self setTimestamp:[NSDate date]];
}

+ (int)countAdoptionsForUserId:(NSString *)uid
{

    FRKAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *context = [appDelegate managedObjectContext];

    NSEntityDescription *entityDesc = [NSEntityDescription
                                       entityForName:@"Adoption"
                                       inManagedObjectContext:context];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entityDesc];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"(userId = %@)", uid];
    [fetchRequest setPredicate:pred];

    NSError *err;
    NSUInteger count = [context countForFetchRequest:fetchRequest error:&err];

    return count;
}

@end


text:
Yet another post

[meta:author]: <> (Jonas Colmsjo)
[meta:title]: <> (Apparmor.md)
[meta:date]: <> (2012-01-01)
[meta:nested:key]: <> (Metadata value)

##!!truncate

[[wiki]]

h1. Apparmor

* https://wiki.ubuntu.com/AppArmor
* http://doc.opensuse.org/products/draft/SLES/SLES-security_sd_draft/pre.apparm.html
* http://forums.opensuse.org/english/get-technical-help-here/applications/455941-apparmor-email-alerting.html

<pre>
sudo apt-get install apparmor-profiles apparmor-utils

sudo apparmor_status
service apparmor status

sudo aa-complain /etc/cron*

</pre>

h2. Immunizing executables

* http://doc.opensuse.org/documentation/html/openSUSE/opensuse-security/cha.apparmor.concept.html#sec.apparmor.concept.cron


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.devtools.j2objc.pipeline;

import com.google.common.io.Files;
import com.google.devtools.j2objc.Options;
import com.google.devtools.j2objc.ast.Annotation;
import com.google.devtools.j2objc.ast.CompilationUnit;
import com.google.devtools.j2objc.ast.SingleMemberAnnotation;
import com.google.devtools.j2objc.file.InputFile;
import com.google.devtools.j2objc.file.RegularInputFile;
import com.google.devtools.j2objc.util.ErrorUtil;
import com.google.devtools.j2objc.util.FileUtil;
import com.google.devtools.j2objc.util.Parser;
import com.google.devtools.j2objc.util.TypeUtil;
import com.google.j2objc.annotations.ObjectiveCName;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

/**
 * Preprocesses each Java file in the batch.
 */
public class InputFilePreprocessor {

  private static final Logger logger = Logger.getLogger(InputFilePreprocessor.class.getName());

  private final Parser parser;
  private File strippedSourcesDir;
  private final Options options;

  public InputFilePreprocessor(Parser parser) {
    this.parser = parser;
    this.options = parser.options();
  }

  public void processInputs(Iterable<ProcessingContext> inputs) {
    for (ProcessingContext input : inputs) {
      if (input.getFile().getUnitName().endsWith(".java")) {
        processInput(input);
      }
    }
  }

  private void processInput(ProcessingContext input) {
    try {
      if (input.getFile().getUnitName().endsWith("package-info.java")) {
        processPackageInfoSource(input);
      } else {
        processRegularSource(input);
      }
    } catch (IOException e) {
      ErrorUtil.error(e.getMessage());
    }
  }

  public File getStrippedSourcesDir() {
    return strippedSourcesDir;
  }

  private File getCreatedStrippedSourcesDir() {
    if (strippedSourcesDir == null) {
      strippedSourcesDir = Files.createTempDir();
      logger.finest("Created temp dir for stripped sources: " + strippedSourcesDir.getPath());
    }
    return strippedSourcesDir;
  }

  private void processRegularSource(ProcessingContext input) throws IOException {
    InputFile file = input.getFile();
    String source = options.fileUtil().readFile(file);
    boolean shouldMapHeaders = options.getHeaderMap().useSourceDirectories();
    boolean doIncompatibleStripping = source.contains("J2ObjCIncompatible");
    if (!(shouldMapHeaders || doIncompatibleStripping)) {
      // No need to parse.
      return;
    }
    Parser.ParseResult parseResult = parser.parseWithoutBindings(file, source);
    if (parseResult == null) {
      // The parser found and reported one or more errors.
      return;
    }
    String qualifiedName = parseResult.mainTypeName();
    if (shouldMapHeaders) {
      options.getHeaderMap().put(qualifiedName, input.getGenerationUnit().getOutputPath() + ".h");
    }
    if (doIncompatibleStripping) {
      parseResult.stripIncompatibleSource();
      File strippedDir = getCreatedStrippedSourcesDir();
      String relativePath = qualifiedName.replace('.', File.separatorChar) + ".java";
      File strippedFile = new File(strippedDir, relativePath);
      Files.createParentDirs(strippedFile);
      Files.write(parseResult.getSource(), strippedFile, options.fileUtil().getCharset());
      input.setFile(new RegularInputFile(strippedFile.getPath(), relativePath));
    }
  }

  private void processPackageInfoSource(ProcessingContext input) throws IOException {
    InputFile file = input.getFile();
    String source = options.fileUtil().readFile(file);
    CompilationUnit compilationUnit =
        parser.parse(FileUtil.getMainTypeName(file), file.getUnitName(), source);
    if (compilationUnit != null) {
      extractPackagePrefix(file, compilationUnit);
    }
  }

  private void extractPackagePrefix(InputFile file, CompilationUnit unit) {
    // We should only reach here if it's a package-info.java file.
    assert file.getUnitName().endsWith("package-info.java");
    List<Annotation> annotations = (List<Annotation>) unit.getPackage().getAnnotations();
    for (Annotation annotation : annotations) {
      // getFullyQualifiedName() might not actually return a fully qualified name.
      String name = annotation.getTypeName().getFullyQualifiedName();
      if (name.endsWith("ObjectiveCName")) {
        // Per Eclipse docs, binding resolution can be a resource hog.
        if (TypeUtil.getQualifiedName(annotation.getAnnotationMirror().getAnnotationType()).equals(
            ObjectiveCName.class.getCanonicalName())) {
          String key = unit.getPackage().getName().getFullyQualifiedName();
          String val = (String) ((SingleMemberAnnotation) annotation).getValue().getConstantValue();
          options.getPackagePrefixes().addPrefix(key, val);
        }
      }
    }
  }
}


text:
package ru.eaboimov;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
Сумма четных цифр.
*/
public class CounterTest {
	/**
	Test add.
	*/
	@Test
	public void whenSumEvenNumbersFromOneToTenThenThirty() {
		Counter coun = new Counter();
		assertThat(coun.add(1, 10), is(30));
	}
}


text:
package net.jforum.search;

import java.util.ArrayList;

import net.jforum.entities.Post;
import net.jforum.exceptions.SearchInstantiationException;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.log4j.Logger;

/**
 * @author Rafael Steil
 * @version $Id$
 */
public final class SearchFacade
{
	private static final Logger LOGGER = Logger.getLogger(SearchFacade.class);
	private static LuceneManager searchManager;

	public static void init()
	{
		if (!isSearchEnabled()) {
			LOGGER.info("Search indexing is disabled. Will try to create a LuceneSearch "
				+ "instance for runtime configuration changes");
		}

		final String clazz = SystemGlobals.getValue(ConfigKeys.SEARCH_INDEXER_IMPLEMENTATION);

		if (clazz == null || "".equals(clazz)) {
			LOGGER.info(ConfigKeys.SEARCH_INDEXER_IMPLEMENTATION + " is not defined. Skipping.");
		}
		else {
			try {
				searchManager = (LuceneManager)Class.forName(clazz).newInstance();
			}
			catch (Exception e) {
				LOGGER.warn(e.toString(), e);
				throw new SearchInstantiationException("Error while tring to start the search manager: " + e);
			}

			searchManager.init();
		}
	}

	public static void create(final Post post)
	{
		if (isSearchEnabled()) {
			searchManager.create(post);
		}
	}

	public static void update(final Post post)
	{
		if (isSearchEnabled()) {
			searchManager.update(post);
		}
	}

	public static SearchResult<Post> search(final SearchArgs args, final int userId)
	{
		return isSearchEnabled()
			? searchManager.search(args, userId)
			: new SearchResult<Post>(new ArrayList<Post>(), 0);
	}

	private static boolean isSearchEnabled()
	{
		return SystemGlobals.getBoolValue(ConfigKeys.SEARCH_INDEXING_ENABLED);
	}

	public static void delete(final Post post)
	{
		if (isSearchEnabled()) {
			searchManager.delete(post);
		}
	}

	public static LuceneManager manager()
	{
		return searchManager;
	}

	private SearchFacade() {}
}