text:
"""cleanup_time_grainularity

Revision ID: f9a30386bd74
Revises: b5998378c225
Create Date: 2020-03-25 10:42:11.047328

"""

# revision identifiers, used by Alembic.
revision = "f9a30386bd74"
down_revision = "b5998378c225"

import json

from alembic import op
from sqlalchemy import Column, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base

from superset import db

Base = declarative_base()

class Slice(Base):
    __tablename__ = "slices"

    id = Column(Integer, primary_key=True)
    params = Column(Text)
    viz_type = Column(String(250))

def upgrade():
    """
    Remove any erroneous time grainularity fields from slices foor those visualization
    types which do not support time granularity.

    :see: https://github.com/apache/superset/pull/8674
    :see: https://github.com/apache/superset/pull/8764
    :see: https://github.com/apache/superset/pull/8800
    :see: https://github.com/apache/superset/pull/8825
    """

    bind = op.get_bind()
    session = db.Session(bind=bind)

    # Visualization types which support time grainularity (hence negate).
    viz_types = [
        "area",
        "bar",
        "big_number",
        "compare",
        "dual_line",
        "line",
        "pivot_table",
        "table",
        "time_pivot",
        "time_table",
    ]

    # Erroneous time grainularity fields for either Druid NoSQL or SQL slices which do
    # not support time grainularity.
    erroneous = ["grainularity", "time_grain_sqla"]

    for slc in session.query(Slice).filter(Slice.viz_type.notin_(viz_types)).all():
        try:
            params = json.loads(slc.params)

            if any(field in params for field in erroneous):
                for field in erroneous:
                    if field in params:
                        del params[field]

                slc.params = json.dumps(params, sort_keys=True)
        except Exception:
            pass

    session.commit()
    session.close()

def downgrade():
    pass


text:
<?php
namespace W3TC;

/**
 * Windows Azure Storage CDN engine
 */
class CdnEngine_Azure extends CdnEngine_Base {
	/**
	 * Storage client object
	 *
	 * @var Microsoft_WindowsAzure_Storage_Blob
	 */
	var $_client = null;

	/**
	 * PHP5 Constructor
	 *
	 * @param array   $config
	 */
	function __construct( $config = array() ) {
		$config = array_merge( array(
				'user' => '',
				'key' => '',
				'container' => '',
				'cname' => array(),
			), $config );

		parent::__construct( $config );

		require_once W3TC_LIB_DIR . DIRECTORY_SEPARATOR . 'Azure' .
			DIRECTORY_SEPARATOR . 'loader.php';
	}

	/**
	 * Inits storage client object
	 *
	 * @param string  $error
	 * @return boolean
	 */
	function _init( &$error ) {
		if ( empty( $this->_config['user'] ) ) {
			$error = 'Empty account name.';
			return false;
		}

		if ( empty( $this->_config['key'] ) ) {
			$error = 'Empty account key.';

			return false;
		}

		if ( empty( $this->_config['container'] ) ) {
			$error = 'Empty container name.';

			return false;
		}

		try {
			$connectionString = 'DefaultEndpointsProtocol=https;AccountName=' .
			$this->_config['user'] .
			';AccountKey=' . $this->_config['key'];

			$this->_client = \MicrosoftAzure\Storage\Common\ServicesBuilder::getInstance()->createBlobService(
				$connectionString);
		} catch ( \Exception $ex ) {
			$error = $ex->getMessage();
			return false;
		}

		return true;
	}

	/**
	 * Uploads files to S3
	 *
	 * @param array   $files
	 * @param array   $results
	 * @param boolean $force_rewrite
	 * @return boolean
	 */
	function upload( $files, &$results, $force_rewrite = false,
		$timeout_time = NULL ) {
		$error = null;

		if ( !$this->_init( $error ) ) {
			$results = $this->_get_results( $files, W3TC_CDN_RESULT_HALT, $error );

			return false;
		}

		foreach ( $files as $file ) {
			if ( !is_null( $timeout_time ) && time() > $timeout_time )
				break;

			$remote_path = $file['remote_path'];

			$results[] = $this->_upload( $file, $force_rewrite );
		}

		return !$this->_is_error( $results );
	}

	/**
	 * Uploads file
	 *
	 * @param string  $local_path
	 * @param string  $remote_path
	 * @param bool    $force_rewrite
	 * @return array
	 */
	function _upload( $file, $force_rewrite = false ) {
		$local_path = $file['local_path'];
		$remote_path = $file['remote_path'];

		if ( !file_exists( $local_path ) ) {
			return $this->_get_result( $local_path, $remote_path,
				W3TC_CDN_RESULT_ERROR, 'Source file not found.', $file );
		}

		$contents = @file_get_contents( $local_path );
		$md5 = md5( $contents );   // @md5_file( $local_path );
		$content_md5 = $this->_get_content_md5( $md5 );

		if ( !$force_rewrite ) {
			try {
				$propertiesResult = $this->_client->getBlobProperties( $this->_config['container'], $remote_path );
				$p = $propertiesResult->getProperties();

				$local_size = @filesize( $local_path );

				if ( $local_size == $p->getContentLength() && $content_md5 === $p->getContentMD5() ) {
					return $this->_get_result( $local_path, $remote_path,
						W3TC_CDN_RESULT_OK, 'File up-to-date.', $file );
				}
			} catch ( \Exception $exception ) {
			}
		}

		$headers = $this->_get_headers( $file );
		$headers = array_merge( $headers, array(
				'Content-MD5' => $content_md5
			) );

		try {
			// $headers
			$this->_client->createBlockBlob( $this->_config['container'], $remote_path, $contents );
		} catch ( \Exception $exception ) {
			return $this->_get_result( $local_path, $remote_path,
				W3TC_CDN_RESULT_ERROR,
				sprintf( 'Unable to put blob (%s).', $exception->getMessage() ),
				$file );
		}

		return $this->_get_result( $local_path, $remote_path, W3TC_CDN_RESULT_OK,
			'OK', $file );
	}

	/**
	 * Deletes files from storage
	 *
	 * @param array   $files
	 * @param array   $results
	 * @return boolean
	 */
	function delete( $files, &$results ) {
		$error = null;

		if ( !$this->_init( $error ) ) {
			$results = $this->_get_results( $files, W3TC_CDN_RESULT_HALT, $error );

			return false;
		}

		foreach ( $files as $file ) {
			$local_path = $file['local_path'];
			$remote_path = $file['remote_path'];

			try {
				$this->_client->deleteBlob( $this->_config['container'], $remote_path );
				$results[] = $this->_get_result( $local_path, $remote_path,
					W3TC_CDN_RESULT_OK, 'OK', $file );
			} catch ( \Exception $exception ) {
				$results[] = $this->_get_result( $local_path, $remote_path,
					W3TC_CDN_RESULT_ERROR,
					sprintf( 'Unable to delete blob (%s).', $exception->getMessage() ),
					$file );
			}
		}

		return !$this->_is_error( $results );
	}

	/**
	 * Tests S3
	 *
	 * @param string  $error
	 * @return boolean
	 */
	function test( &$error ) {
		if ( !parent::test( $error ) ) {
			return false;
		}

		$string = 'test_azure_' . md5( time() );

		if ( !$this->_init( $error ) ) {
			return false;
		}

		try {
			$containers = $this->_client->listContainers();
		} catch ( \Exception $exception ) {
			$error = sprintf( 'Unable to list containers (%s).', $exception->getMessage() );

			return false;
		}

		$container = null;

		foreach ( $containers->getContainers() as $_container ) {
			if ( $_container->getName() == $this->_config['container'] ) {
				$container = $_container;
				break;
			}
		}

		if ( !$container ) {
			$error = sprintf( 'Container doesn\'t exist: %s.', $this->_config['container'] );

			return false;
		}

		try {
			$this->_client->createBlockBlob( $this->_config['container'], $string, $string );
		} catch ( \Exception $exception ) {
			$error = sprintf( 'Unable to create blob (%s).', $exception->getMessage() );
			return false;
		}

		try {
			$propertiesResult = $this->_client->getBlobProperties( $this->_config['container'], $string );
			$p = $propertiesResult->getProperties();
			$size = $p->getContentLength();
			$md5 = $p->getContentMD5();
		} catch ( \Exception $exception ) {
			$error = sprintf( 'Unable to get blob properties (%s).', $exception->getMessage() );
			return false;
		}

		if ( $size != strlen( $string ) || $this->_get_content_md5( md5( $string ) ) != $md5 ) {
			try {
				$this->_client->deleteBlob( $this->_config['container'], $string );
			} catch ( \Exception $exception ) {
			}

			$error = 'Blob data properties are not equal.';
			return false;
		}

		try {
			$getBlob = $this->_client->getBlob( $this->_config['container'], $string );
			$dataStream = $getBlob->getContentStream();
			$data = stream_get_contents( $dataStream );
		} catch ( \Exception $exception ) {
			$error = sprintf( 'Unable to get blob data (%s).', $exception->getMessage() );
			return false;
		}

		if ( $data != $string ) {
			try {
				$this->_client->deleteBlob( $this->_config['container'], $string );
			} catch ( \Exception $exception ) {
			}

			$error = 'Blob datas are not equal.';
			return false;
		}

		try {
			$this->_client->deleteBlob( $this->_config['container'], $string );
		} catch ( \Exception $exception ) {
			$error = sprintf( 'Unable to delete blob (%s).', $exception->getMessage() );

			return false;
		}

		return true;
	}

	/**
	 * Returns CDN domain
	 *
	 * @return array
	 */
	function get_domains() {
		if ( !empty( $this->_config['cname'] ) ) {
			return (array) $this->_config['cname'];
		} elseif ( !empty( $this->_config['user'] ) ) {
			$domain = sprintf( '%s.blob.core.windows.net', $this->_config['user'] );

			return array(
				$domain
			);
		}

		return array();
	}

	/**
	 * Returns via string
	 *
	 * @return string
	 */
	function get_via() {
		return sprintf( 'Windows Azure Storage: %s', parent::get_via() );
	}

	/**
	 * Creates bucket
	 *
	 * @param string  $container_id
	 * @param string  $error
	 * @return boolean
	 */
	function create_container( &$container_id, &$error ) {
		if ( !$this->_init( $error ) ) {
			return false;
		}

		try {
			$containers = $this->_client->listContainers();
		} catch ( \Exception $exception ) {
			$error = sprintf( 'Unable to list containers (%s).', $exception->getMessage() );

			return false;
		}

		if ( in_array( $this->_config['container'], (array) $containers ) ) {
			$error = sprintf( 'Container already exists: %s.', $this->_config['container'] );

			return false;
		}

		try {
    		$createContainerOptions = new \MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions();
    		$createContainerOptions->setPublicAccess(
    			\MicrosoftAzure\Storage\Blob\Models\PublicAccessType::CONTAINER_AND_BLOBS );

			$this->_client->createContainer( $this->_config['container'], $createContainerOptions );
		} catch ( \Exception $exception ) {
			$error = sprintf( 'Unable to create container: %s (%s)', $this->_config['container'], $exception->getMessage() );

			return false;
		}

		return true;
	}

	/**
	 * Returns Content-MD5 header value
	 *
	 * @param string  $string
	 * @return string
	 */
	function _get_content_md5( $md5 ) {
		return base64_encode( pack( 'H*', $md5 ) );
	}

	/**
	 * Formats object URL
	 *
	 * @param string  $path
	 * @return string
	 */
	function _format_url( $path ) {
		$domain = $this->get_domain( $path );

		if ( $domain && !empty( $this->_config['container'] ) ) {
			$scheme = $this->_get_scheme();
			$url = sprintf( '%s://%s/%s/%s', $scheme, $domain, $this->_config['container'], $path );

			return $url;
		}

		return false;
	}

	/**
	 * Returns array of headers
	 *
	 * @param array   $file CDN file array
	 * @return array
	 */
	function _get_headers( $file, $block_expires = false ) {
		$allowed_headers = array(
			'Content-Length',
			'Content-Type',
			'Content-Encoding',
			'Content-Language',
			'Content-MD5',
			'Cache-Control',
		);

		$headers = parent::_get_headers( $file, true );

		foreach ( $headers as $header => $value ) {
			if ( !in_array( $header, $allowed_headers ) ) {
				unset( $headers[$header] );
			}
		}

		return $headers;
	}

	/**
	 * How and if headers should be set
	 *
	 * @return string W3TC_CDN_HEADER_NONE, W3TC_CDN_HEADER_UPLOADABLE, W3TC_CDN_HEADER_MIRRORING
	 */
	function headers_support() {
		return W3TC_CDN_HEADER_UPLOADABLE;
	}

	function get_prepend_path( $path ) {
		$path = parent::get_prepend_path( $path );
		$path = $this->_config['container'] ? trim( $path, '/' ) . '/' . trim( $this->_config['container'], '/' ): $path;
		return $path;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package at.mduft.rex.util;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Implements a {@link Thread} that watches for file modifications based on the Java7
 * {@link WatchService} infrastructure. Whenever the file changes, all registered listeners are
 * notified.
 */
public class FileChangeWatch extends Thread {

    private static final Logger log = LoggerFactory.getLogger(FileChangeWatch.class);
    private final List<FileChangeListener> listeners = new ArrayList<>();
    private final Path toWatch;
    private final WatchService service;

    /**
     * Creates a new {@link FileChangeWatch} that will observe the given path for changes.
     *
     * @param toWatch
     *            the file to watch
     * @throws IOException
     *             in case setting up the {@link WatchService} fails.
     */
    public FileChangeWatch(Path toWatch) throws IOException {
        this.toWatch = toWatch;
        this.service = toWatch.getFileSystem().newWatchService();
        this.toWatch.getParent().register(service, StandardWatchEventKinds.ENTRY_MODIFY);

        setName("Watch " + toWatch.getFileName());
    }

    @SuppressWarnings("unchecked")
    @Override
    public void run() {
        log.debug("start watching " + toWatch + " for modifications");
        try {
            WatchKey key = service.take();
            while (key != null) {
                for (WatchEvent<?> event : key.pollEvents()) {
                    if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                        WatchEvent<Path> pathEvent = (WatchEvent<Path>) event;
                        if (pathEvent.context().getFileName().equals(toWatch.getFileName())) {
                            notifyChange(toWatch);
                        }
                    }
                }
                if (!key.reset()) {
                    log.warn("directory inaccessible: " + toWatch.getParent());
                    return;
                }

                key = service.take();
            }
        } catch (InterruptedException e) {
            log.info("watch service interupted: ", e);
        }
    }

    /**
     * Notify all listeners about a change.
     *
     * @param changed
     *            the file that changed.
     */
    private void notifyChange(Path changed) {
        for (FileChangeListener l : listeners) {
            try {
                l.fileChanged(changed);
            } catch (RuntimeException e) {
                log.warn("failed to notify " + l, e);
            }
        }
    }

    /**
     * Adds an additional listener that is to be notified when the watched file changes.
     *
     * @param listener
     *            the listener to be notified on modifications.
     */
    public void addListener(FileChangeListener listener) {
        listeners.add(listener);
    }

}


text:
function change(event){
   var currentDisplay = $("#index > div:visible");
      console.log("Toggling writing display!");
      currentDisplay.fadeToggle(function() {
          currentDisplay = $(event.srcElement.getAttribute("data-st-contentid"));
          currentDisplay.fadeToggle();
      });
};
$(function() {
    var currentDisplay = $("#index > div:visible");
    console.log(document.querySelector(".form"));
    document.querySelector(".form").addEventListener("change",change);
})


text:
layout: post
title: Today is GTD Wednesday
joomla_id: 6
joomla_url: today-is-gtd-wednesday
date: 2010-12-29 18:20:25.000000000 +01:00
author: Joachim van de Haterd
excerpt: "Since I have the evening for myself, and I'm home from work early, I'd use my 'free' evening to get some stuff done."
category: GTD
tags: [Cult of productivity]
---
Since I have the evening for myself, and I'm home from work early, I'd use my 'free' evening to get some stuff done.

I finally know what to get for my old car (too little), what to pay for a proper replacement (too much) and that makes things more complicated.

Next job: clean up some mess after the Christmas weekend. Done.

Next: send that email to my ex-colleague, who I helped pick a new motorcycle. Umm... Wrong laptop. Will do it tonight. :)

Close down my old web site and have it point to the new one (you're reading it now). Hmmm. What was the proper procedure again? Oh well, let's just finish this post then.

Ah. The really bad thing: brush up my skills with the gimp and make some proper graphics for my brand new web site.

I have a bad feeling that this evening will prove to be less productive than I initially hoped.

*Edit*: at least I got the logo done. Sending the mail now. :)


text:
@interface SfNavigationController ()

@end

@implementation SfNavigationController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    //对于IPAD,不允许转屏
    if(iPhoneOniPad) {
        return NO;
    }
    return UIInterfaceOrientationIsPortrait(interfaceOrientation);
}

-(BOOL)shouldAutorotate {
    //对于IPAD,不允许转屏
    if(iPhoneOniPad) {
        return NO;
    }
    return YES;
}

-(NSUInteger)supportedInterfaceOrientations{
    //对于IPAD,不允许转屏
    if(iPhoneOniPad) {
        return UIInterfaceOrientationMaskPortrait;
    }
    return UIInterfaceOrientationMaskAll;
}

@end


text:
package pt.davidafsilva.slacker.api;

import java.time.Instant;
import java.util.Objects;
import java.util.Optional;

import io.vertx.core.json.Json;

/**
 * A builder for a fluent creation of {@link SlackerRequest} messages.
 *
 * @author david
 * @since 1.0
 */
public final class SlackerRequestBuilder {

  // properties
  private Instant timestamp;
  private String teamIdentifier;
  private String teamDomain;
  private String channelId;
  private String channelName;
  private String userId;
  private String userName;
  private String command;
  private String args;

  public SlackerRequestBuilder timestamp(final Instant timestamp) {
    this.timestamp = timestamp;
    return this;
  }

  public SlackerRequestBuilder teamIdentifier(final String teamIdentifier) {
    this.teamIdentifier = teamIdentifier;
    return this;
  }

  public SlackerRequestBuilder teamDomain(final String teamDomain) {
    this.teamDomain = teamDomain;
    return this;
  }

  public SlackerRequestBuilder channelId(final String channelId) {
    this.channelId = channelId;
    return this;
  }

  public SlackerRequestBuilder channelName(final String channelName) {
    this.channelName = channelName;
    return this;
  }

  public SlackerRequestBuilder userId(final String userId) {
    this.userId = userId;
    return this;
  }

  public SlackerRequestBuilder userName(final String userName) {
    this.userName = userName;
    return this;
  }

  public SlackerRequestBuilder command(final String command) {
    this.command = command;
    return this;
  }

  public SlackerRequestBuilder args(final String args) {
    this.args = args;
    return this;
  }

  /**
   * Builds a slacker request with the current state of the builder.
   *
   * @return a new instance of {@link SlackerRequest} with the specified parameters
   * @throws NullPointerException if the builder state is incomplete and unable to create the
   *                              proper request message
   */
  public SlackerRequest build() {
    return new SlackerRequestImpl(
        Objects.requireNonNull(timestamp, "timestamp"),
        Objects.requireNonNull(teamIdentifier, "team identifier"),
        Objects.requireNonNull(teamDomain, "team domain"),
        Objects.requireNonNull(channelId, "channel identifier"),
        Objects.requireNonNull(channelName, "channel name"),
        Objects.requireNonNull(userId, "user identifier"),
        Objects.requireNonNull(userName, "user name"),
        Objects.requireNonNull(command, "command"),
        args == null || args.isEmpty() ? null : args);
  }

  // straight-forward implementation of the slacker request
  static final class SlackerRequestImpl implements SlackerRequest {

    // the request timestamp
    private final Instant timestamp;
    // the team identifier
    private final String teamIdentifier;
    // the team domain
    private final String teamDomain;
    // the channel id
    private final String channelId;
    // the channel name
    private final String channelName;
    // the user identifier
    private final String userId;
    // the user name
    private final String userName;
    // the command
    private final String command;
    // the arguments
    private final Optional<String> args;

    /**
     * Default constructor
     *
     * @param timestamp      the request timestamp
     * @param teamIdentifier the team identifier
     * @param teamDomain     the team domain
     * @param channelId      the channel id
     * @param channelName    the channel name
     * @param userId         the user identifier
     * @param userName       the user name
     * @param command        the command
     * @param args           the arguments
     */
    private SlackerRequestImpl(final Instant timestamp, final String teamIdentifier,
        final String teamDomain, final String channelId, final String channelName,
        final String userId, final String userName, final String command, final String args) {
      this.timestamp = timestamp;
      this.teamIdentifier = teamIdentifier;
      this.teamDomain = teamDomain;
      this.channelId = channelId;
      this.channelName = channelName;
      this.userId = userId;
      this.userName = userName;
      this.command = command;
      this.args = Optional.ofNullable(args);
    }

    @Override
    public Instant getTimestamp() {
      return timestamp;
    }

    @Override
    public String getTeamIdentifier() {
      return teamIdentifier;
    }

    @Override
    public String getTeamDomain() {
      return teamDomain;
    }

    @Override
    public String getChannelId() {
      return channelId;
    }

    @Override
    public String getChannelName() {
      return channelName;
    }

    @Override
    public String getUserId() {
      return userId;
    }

    @Override
    public String getUserName() {
      return userName;
    }

    @Override
    public String getCommand() {
      return command;
    }

    @Override
    public Optional<String> getArguments() {
      return args;
    }

    @Override
    public String toString() {
      return Json.encodePrettily(this);
    }
  }
}


text:
import cv
import ml
import os

from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn import cross_validation

from collections import defaultdict
import json

FEATURE_DIR = "data"
IMAGES_DIR = "images"

def is_image_file(src):
    return src.endswith(".jpg") or src.endswith(".png")

def save_data():
    if not os.path.isdir(FEATURE_DIR):
        os.mkdir(FEATURE_DIR)

    color_file = open(os.path.join(FEATURE_DIR, "color.txt"), 'w')
    hu_file = open(os.path.join(FEATURE_DIR, "hu.txt"), 'w')
    curvature_file = open(os.path.join(FEATURE_DIR, "curvature.txt"), 'w')
    glcm_file = open(os.path.join(FEATURE_DIR, "glcm.txt"), 'w')

    for root, dirs, files in os.walk(IMAGES_DIR):
        for file in files:
            _class = root[-4:]
            file_path = os.path.join(root, file)
            if is_image_file(file_path):
                print(file_path)
                color, hu, curvature, glcm = cv.get_features(
                    file_path)

                _class_str = ',{}\n'.format(_class)
                color_file.write(",".join(map(str, color)) + _class_str)
                hu_file.write(",".join(map(str, hu)) + _class_str)
                curvature_file.write(
                    ",".join(map(str, curvature)) + _class_str)
                glcm_file.write(",".join(map(str, glcm)) + _class_str)

    color_file.close()
    hu_file.close()
    curvature_file.close()
    glcm_file.close()

def test_classifler(classifler, X, y):
    return cross_validation.cross_val_score(classifler, X, y, cv=5)

def test_knn(X, y):
    model = KNeighborsClassifier(10)
    return test_classifler(model, X, y).mean()

def test_svm(X, y):
    model = SVC()
    return test_classifler(model, X, y).mean()

def test_knn_and_snm(data_file):
    X, y = ml.load_data(data_file)
    return test_knn(X, y), test_svm(X, y)

def test_data():
    result = defaultdict(defaultdict)
    for root, dirs, files in os.walk(FEATURE_DIR):
        for f in files:
            file_path = os.path.join(root, f)
            print(file_path)
            predict_result = test_knn_and_snm(file_path)
            print(predict_result)
            result[f[:-4]]["knn"] = predict_result[0]
            result[f[:-4]]["svm"] = predict_result[1]

    return result

def cal_weights(result):
    total = 0
    for feature in result:
        total += result[feature]["knn"] + result[feature]["svm"]

    weights = defaultdict(defaultdict)

    for feature in result:
        weights[feature]["knn"] = result[feature]["knn"] / total
        weights[feature]["svm"] = result[feature]["svm"] / total

    print(json.dumps(weights, indent=4))

    return weights

def run():
    # save_data()
    result = test_data()
    cal_weights(result)

if __name__ == '__main__':
    run()


text:
System.register([], function (_export) {
  "use strict";

  var GetterObserver;

  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  return {
    setters: [],
    execute: function () {
      GetterObserver = (function () {
        function GetterObserver(object, propertyName, descriptor, expression, binding) {
          _classCallCheck(this, GetterObserver);

          this.object = object;
          this.propertyName = propertyName;
          this.descriptor = descriptor;
          this.expression = expression;
          this.binding = binding;
        }

        GetterObserver.prototype.getValue = function getValue() {
          return this.object[this.propertyName];
        };

        GetterObserver.prototype.setValue = function setValue(newValue) {
          if (this.descriptor.set) {
            this.object[this.propertyName] = newValue;
          } else {
            throw new Error(this.propertyName + " does not have a setter function.");
          }
        };

        GetterObserver.prototype.subscribe = function subscribe(callback) {
          var _this = this;

          var callbacks = this.callbacks || (this.callbacks = []),
              info;

          if (callbacks.length === 0) {
            info = this.expression.connect(this.binding, { "this": this.object });
            this.oldValue = this.getValue();
            if (info.observer) {
              this.observer = info.observer;
              info.observer.subscribe(function () {
                return _this.notify();
              });
            }
          }

          callbacks.push(callback);

          return this.unsubscribe.bind(this, callback);
        };

        GetterObserver.prototype.notify = function notify() {
          var i,
              ii,
              newValue = this.getValue(),
              oldValue = this.oldValue,
              callbacks = this.callbacks;
          if (newValue === oldValue) {
            return;
          }
          this.oldValue = newValue;
          for (i = 0, ii = callbacks.length; i < ii; i++) {
            callbacks[i](newValue, oldValue);
          }
        };

        GetterObserver.prototype.unsubscribe = function unsubscribe(callback) {
          var callbacks = this.callbacks,
              index = callbacks.indexOf(callback);
          if (index === -1) {
            return;
          }
          callbacks.splice(index, 1);
          if (callbacks.length === 0 && this.observer) {
            if (this.observer.dispose) {
              this.observer.dispose();
            }
            this.observer = null;
          }
        };

        return GetterObserver;
      })();

      _export("GetterObserver", GetterObserver);
    }
  };
});


text:
// Windows/FileIO.cpp

#include "StdAfx.h"

#ifdef SUPPORT_DEVICE_FILE
#include "../../C/Alloc.h"
#endif

#include "FileIO.h"
#include "FileName.h"

#ifndef _UNICODE
extern bool g_IsNT;
#endif

using namespace NWindows;
using namespace NFile;
using namespace NName;

namespace NWindows {
namespace NFile {

#ifdef SUPPORT_DEVICE_FILE

namespace NSystem
{
bool MyGetDiskFreeSpace(CFSTR rootPath, UInt64 &clusterSize, UInt64 &totalSize, UInt64 &freeSize);
}
#endif

namespace NIO {

/*
WinXP-64 CreateFile():
  ""             -  ERROR_PATH_NOT_FOUND
  :stream        -  OK
  .:stream       -  ERROR_PATH_NOT_FOUND
  .\:stream      -  OK

  folder\:stream -  ERROR_INVALID_NAME
  folder:stream  -  OK

  c:\:stream     -  OK

  c::stream      -  ERROR_INVALID_NAME, if current dir is NOT ROOT ( c:\dir1 )
  c::stream      -  OK,                 if current dir is ROOT     ( c:\ )
*/

bool CFileBase::Create(CFSTR path, DWORD desiredAccess,
    DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes)
{
  if (!Close())
    return false;

  #ifdef SUPPORT_DEVICE_FILE
  IsDeviceFile = false;
  #endif

  #ifndef _UNICODE
  if (!g_IsNT)
  {
    _handle = ::CreateFile(fs2fas(path), desiredAccess, shareMode,
        (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, flagsAndAttributes, (HANDLE)NULL);
  }
  else
  #endif
  {
    IF_USE_MAIN_PATH
      _handle = ::CreateFileW(fs2us(path), desiredAccess, shareMode,
        (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, flagsAndAttributes, (HANDLE)NULL);
    #ifdef WIN_LONG_PATH
    if (_handle == INVALID_HANDLE_VALUE && USE_SUPER_PATH)
    {
      UString superPath;
      if (GetSuperPath(path, superPath, USE_MAIN_PATH))
        _handle = ::CreateFileW(superPath, desiredAccess, shareMode,
            (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, flagsAndAttributes, (HANDLE)NULL);
    }
    #endif
  }
  return (_handle != INVALID_HANDLE_VALUE);
}

bool CFileBase::Close() throw()
{
  if (_handle == INVALID_HANDLE_VALUE)
    return true;
  if (!::CloseHandle(_handle))
    return false;
  _handle = INVALID_HANDLE_VALUE;
  return true;
}

bool CFileBase::GetPosition(UInt64 &position) const throw()
{
  return Seek(0, FILE_CURRENT, position);
}

bool CFileBase::GetLength(UInt64 &length) const throw()
{
  #ifdef SUPPORT_DEVICE_FILE
  if (IsDeviceFile && SizeDefined)
  {
    length = Size;
    return true;
  }
  #endif

  DWORD sizeHigh;
  DWORD sizeLow = ::GetFileSize(_handle, &sizeHigh);
  if (sizeLow == 0xFFFFFFFF)
    if (::GetLastError() != NO_ERROR)
      return false;
  length = (((UInt64)sizeHigh) << 32) + sizeLow;
  return true;
}

bool CFileBase::Seek(Int64 distanceToMove, DWORD moveMethod, UInt64 &newPosition) const throw()
{
  #ifdef SUPPORT_DEVICE_FILE
  if (IsDeviceFile && SizeDefined && moveMethod == FILE_END)
  {
    distanceToMove += Size;
    moveMethod = FILE_BEGIN;
  }
  #endif

  LONG high = (LONG)(distanceToMove >> 32);
  DWORD low = ::SetFilePointer(_handle, (LONG)(distanceToMove & 0xFFFFFFFF), &high, moveMethod);
  if (low == 0xFFFFFFFF)
    if (::GetLastError() != NO_ERROR)
      return false;
  newPosition = (((UInt64)(UInt32)high) << 32) + low;
  return true;
}

bool CFileBase::Seek(UInt64 position, UInt64 &newPosition) const throw()
{
  return Seek(position, FILE_BEGIN, newPosition);
}

bool CFileBase::SeekToBegin() const throw()
{
  UInt64 newPosition;
  return Seek(0, newPosition);
}

bool CFileBase::SeekToEnd(UInt64 &newPosition) const throw()
{
  return Seek(0, FILE_END, newPosition);
}

// ---------- CInFile ---------

#ifdef SUPPORT_DEVICE_FILE

void CInFile::CorrectDeviceSize()
{
  // maybe we must decrease kClusterSize to 1 << 12, if we want correct size at tail
  static const UInt32 kClusterSize = 1 << 14;
  UInt64 pos = Size & ~(UInt64)(kClusterSize - 1);
  UInt64 realNewPosition;
  if (!Seek(pos, realNewPosition))
    return;
  Byte *buf = (Byte *)MidAlloc(kClusterSize);

  bool needbackward = true;

  for (;;)
  {
    UInt32 processed = 0;
    // up test is slow for "PhysicalDrive".
    // processed size for latest block for "PhysicalDrive0" is 0.
    if (!Read1(buf, kClusterSize, processed))
      break;
    if (processed == 0)
      break;
    needbackward = false;
    Size = pos + processed;
    if (processed != kClusterSize)
      break;
    pos += kClusterSize;
  }

  if (needbackward && pos != 0)
  {
    pos -= kClusterSize;
    for (;;)
    {
      // break;
      if (!Seek(pos, realNewPosition))
        break;
      if (!buf)
      {
        buf = (Byte *)MidAlloc(kClusterSize);
        if (!buf)
          break;
      }
      UInt32 processed = 0;
      // that code doesn't work for "PhysicalDrive0"
      if (!Read1(buf, kClusterSize, processed))
        break;
      if (processed != 0)
      {
        Size = pos + processed;
        break;
      }
      if (pos == 0)
        break;
      pos -= kClusterSize;
    }
  }
  MidFree(buf);
}

void CInFile::CalcDeviceSize(CFSTR s)
{
  SizeDefined = false;
  Size = 0;
  if (_handle == INVALID_HANDLE_VALUE || !IsDeviceFile)
    return;
  #ifdef UNDER_CE

  SizeDefined = true;
  Size = 128 << 20;

  #else

  PARTITION_INFORMATION partInfo;
  bool needCorrectSize = true;

  /*
    WinXP 64-bit:

    HDD \\.\PhysicalDrive0 (MBR):
      GetPartitionInfo == GeometryEx :  corrrect size? (includes tail)
      Geometry   :  smaller than GeometryEx (no tail, maybe correct too?)
      MyGetDiskFreeSpace : FAIL
      Size correction is slow and block size (kClusterSize) must be small?

    HDD partition \\.\N: (NTFS):
      MyGetDiskFreeSpace   :  Size of NTFS clusters. Same size can be calculated after correction
      GetPartitionInfo     :  size of partition data: NTFS clusters + TAIL; TAIL contains extra empty sectors and copy of first sector of NTFS
      Geometry / CdRomGeometry / GeometryEx :  size of HDD (not that partition)

    CD-ROM drive (ISO):
      MyGetDiskFreeSpace   :  correct size. Same size can be calculated after correction
      Geometry == CdRomGeometry  :  smaller than corrrect size
      GetPartitionInfo == GeometryEx :  larger than corrrect size

    Floppy \\.\a: (FAT):
      Geometry :  correct size.
      CdRomGeometry / GeometryEx / GetPartitionInfo / MyGetDiskFreeSpace - FAIL
      correction works OK for FAT.
      correction works OK for non-FAT, if kClusterSize = 512.
  */

  if (GetPartitionInfo(&partInfo))
  {
    Size = partInfo.PartitionLength.QuadPart;
    SizeDefined = true;
    needCorrectSize = false;
    if ((s)[0] == '\\' && (s)[1] == '\\' && (s)[2] == '.' && (s)[3] == '\\' && (s)[5] == ':' && (s)[6] == 0)
    {
      FChar path[4] = { s[4], ':', '\\', 0 };
      UInt64 clusterSize, totalSize, freeSize;
      if (NSystem::MyGetDiskFreeSpace(path, clusterSize, totalSize, freeSize))
        Size = totalSize;
      else
        needCorrectSize = true;
    }
  }

  if (!SizeDefined)
  {
    my_DISK_GEOMETRY_EX geomEx;
    SizeDefined = GetGeometryEx(&geomEx);
    if (SizeDefined)
      Size = geomEx.DiskSize.QuadPart;
    else
    {
      DISK_GEOMETRY geom;
      SizeDefined = GetGeometry(&geom);
      if (!SizeDefined)
        SizeDefined = GetCdRomGeometry(&geom);
      if (SizeDefined)
        Size = geom.Cylinders.QuadPart * geom.TracksPerCylinder * geom.SectorsPerTrack * geom.BytesPerSector;
    }
  }

  if (needCorrectSize && SizeDefined && Size != 0)
  {
    CorrectDeviceSize();
    SeekToBegin();
  }

  // SeekToBegin();
  #endif
}

// ((desiredAccess & (FILE_WRITE_DATA | FILE_APPEND_DATA | GENERIC_WRITE)) == 0 &&

#define MY_DEVICE_EXTRA_CODE \
  IsDeviceFile = IsDevicePath(fileName); \
  CalcDeviceSize(fileName);
#else
#define MY_DEVICE_EXTRA_CODE
#endif

bool CInFile::Open(CFSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes)
{
  bool res = Create(fileName, GENERIC_READ, shareMode, creationDisposition, flagsAndAttributes);
  MY_DEVICE_EXTRA_CODE
  return res;
}

bool CInFile::OpenShared(CFSTR fileName, bool shareForWrite)
{ return Open(fileName, FILE_SHARE_READ | (shareForWrite ? FILE_SHARE_WRITE : 0), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL); }

bool CInFile::Open(CFSTR fileName)
  { return OpenShared(fileName, false); }

// ReadFile and WriteFile functions in Windows have BUG:
// If you Read or Write 64MB or more (probably min_failure_size = 64MB - 32KB + 1)
// from/to Network file, it returns ERROR_NO_SYSTEM_RESOURCES
// (Insufficient system resources exist to complete the requested service).

// Probably in some version of Windows there are problems with other sizes:
// for 32 MB (maybe also for 16 MB).
// And message can be "Network connection was lost"

static UInt32 kChunkSizeMax = (1 << 22);

bool CInFile::Read1(void *data, UInt32 size, UInt32 &processedSize) throw()
{
  DWORD processedLoc = 0;
  bool res = BOOLToBool(::ReadFile(_handle, data, size, &processedLoc, NULL));
  processedSize = (UInt32)processedLoc;
  return res;
}

bool CInFile::ReadPart(void *data, UInt32 size, UInt32 &processedSize) throw()
{
  if (size > kChunkSizeMax)
    size = kChunkSizeMax;
  return Read1(data, size, processedSize);
}

bool CInFile::Read(void *data, UInt32 size, UInt32 &processedSize) throw()
{
  processedSize = 0;
  do
  {
    UInt32 processedLoc = 0;
    bool res = ReadPart(data, size, processedLoc);
    processedSize += processedLoc;
    if (!res)
      return false;
    if (processedLoc == 0)
      return true;
    data = (void *)((unsigned char *)data + processedLoc);
    size -= processedLoc;
  }
  while (size > 0);
  return true;
}

// ---------- COutFile ---------

static inline DWORD GetCreationDisposition(bool createAlways)
  { return createAlways? CREATE_ALWAYS: CREATE_NEW; }

bool COutFile::Open(CFSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes)
  { return CFileBase::Create(fileName, GENERIC_WRITE, shareMode, creationDisposition, flagsAndAttributes); }

bool COutFile::Open(CFSTR fileName, DWORD creationDisposition)
  { return Open(fileName, FILE_SHARE_READ, creationDisposition, FILE_ATTRIBUTE_NORMAL); }

bool COutFile::Create(CFSTR fileName, bool createAlways)
  { return Open(fileName, GetCreationDisposition(createAlways)); }

bool COutFile::CreateAlways(CFSTR fileName, DWORD flagsAndAttributes)
  { return Open(fileName, FILE_SHARE_READ, GetCreationDisposition(true), flagsAndAttributes); }

bool COutFile::SetTime(const FILETIME *cTime, const FILETIME *aTime, const FILETIME *mTime) throw()
  { return BOOLToBool(::SetFileTime(_handle, cTime, aTime, mTime)); }

bool COutFile::SetMTime(const FILETIME *mTime) throw() {  return SetTime(NULL, NULL, mTime); }

bool COutFile::WritePart(const void *data, UInt32 size, UInt32 &processedSize) throw()
{
  if (size > kChunkSizeMax)
    size = kChunkSizeMax;
  DWORD processedLoc = 0;
  bool res = BOOLToBool(::WriteFile(_handle, data, size, &processedLoc, NULL));
  processedSize = (UInt32)processedLoc;
  return res;
}

bool COutFile::Write(const void *data, UInt32 size, UInt32 &processedSize) throw()
{
  processedSize = 0;
  do
  {
    UInt32 processedLoc = 0;
    bool res = WritePart(data, size, processedLoc);
    processedSize += processedLoc;
    if (!res)
      return false;
    if (processedLoc == 0)
      return true;
    data = (const void *)((const unsigned char *)data + processedLoc);
    size -= processedLoc;
  }
  while (size > 0);
  return true;
}

bool COutFile::SetEndOfFile() throw() { return BOOLToBool(::SetEndOfFile(_handle)); }

bool COutFile::SetLength(UInt64 length) throw()
{
  UInt64 newPosition;
  if (!Seek(length, newPosition))
    return false;
  if (newPosition != length)
    return false;
  return SetEndOfFile();
}

}}}


text:
package main

import (
	"log"
	"net"
	"net/http"

	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"github.com/sadlil/experiments/grpc-examples/_proto"
	"github.com/sadlil/experiments/grpc-examples/pkg"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

func main() {
	go runGRPCServer()
	runProxy()
}

func runGRPCServer() {
	l, err := net.Listen("tcp", ":9090")
	if err != nil {
		log.Fatal(err)
	}
	s := grpc.NewServer()
	helloworld.RegisterGreeterServer(s, pkg.NewEchoServer())
	s.Serve(l)
}

func runProxy() {
	httpMux := http.NewServeMux()
	mux := runtime.NewServeMux()
	dialOpts := []grpc.DialOption{grpc.WithInsecure()}
	err := helloworld.RegisterGreeterHandlerFromEndpoint(context.Background(), mux, "localhost:9090", dialOpts)
	if err != nil {
		log.Fatal(err)
	}

	httpMux.Handle("/", mux)
	http.ListenAndServe(":9191", mux)
}


text:
class Event::Agents::Tasks::Node::PagesController < ApplicationController
  include Cms::PublicFilter::Node
  include Event::GeneratorFilter::Ical

  def generate
    written = generate_node @node
    if written
      @task.log "#{@node.url}index.html" if @task
    end

    # initialize context before generating rss
    init_context
    if generate_node_ical @node
      @task.log "#{@node.url}index.ics" if @task
    end

    @start_date = Time.zone.today.advance(years: -1)
    @close_date = Time.zone.today.advance(years: 1)

    remove_old_pages
    generate_new_pages

    written
  end

  private

  def event_display_options
    %w(index list table)
  end

  def remove_old_pages
    term = @start_date.advance(years: -1)..@start_date.advance(months: -1)
    term = term.map { |m| sprintf("#{m.year}%02d", m.month) }.uniq
    term.each do |date|
      file = "#{@node.path}/#{date}.html"
      Fs.rm_rf(file) if Fs.exists?(file)

      event_display_options.each do |display|
        base = "#{@node.path}/#{date}/#{display}"
        file = "#{base}.html"
        Fs.rm_rf(file) if Fs.exists?(file)
        file = "#{base}.ics"
        Fs.rm_rf(file) if Fs.exists?(file)
      end
    end
  end

  def generate_new_pages
    term = (@start_date..@close_date).map { |m| sprintf("#{m.year}%02d", m.month) }.uniq
    term.each do |date|
      event_display_options.each do |display|
        url  = "#{@node.url}#{date}/#{display}.html"
        file = "#{@node.path}/#{date}/#{display}.html"

        init_context
        if generate_node(@node, url: url, file: file)
          @task.log url if @task
        end
      end
    end
  end
end


text:
local env=env
local delta={}

return delta


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../../../../../../../">
  <title data-ice="title">git/resourcecreator/src/Components/Widgets/Cores/Widget002/Widget002SampleDatas.js | 위젯 데이터 명세서 API Document</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

  Home
  Manual
  Reference
  Source

    <input class="search-input">

resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager
VAdvencedFilterArgManagerCategoryGroupAddSampleDatas

VAdvencedFilterArgManagerCategoryGroupEditSampleDatas

VAdvencedFilterArgManagerCategoryMoveSampleDatas

VAdvencedFilterArgManagerCategoryRemoveSampleDatas

VAdvencedFilterArgManagerReadSampleDatas

resourcecreator/src/Utils/CommonManagers/AdvencedFilterManager
VAdvencedFilterManagerReadSampleDatas

resourcecreator/src/Utils/CommonManagers/CategoryListManager
VCategoryListManagerReadSampleDatas

resourcecreator/src/Utils/CommonManagers/LoginManager
VLoginManagerLoginSampleDatas

VLoginManagerLogoutSampleDatas

resourcecreator/src/Utils/CommonManagers/ProjectManager
VProjectManagerAddSampleDatas

VProjectManagerCiUploadSampleDatas

VProjectManagerReadSampleDatas

VProjectManagerRemoveSampleDatas

VProjectManagerThumbnailUploadSampleDatas

resourcecreator/src/Utils/CommonManagers/QueryStateManager
VQueryStateManagerClearSampleDatas

VQueryStateManagerReadSampleDatas

VQueryStateManagerUpdateSampleDatas

resourcecreator/src/Utils/CommonManagers/UserManager
VUserManagerDeleteSampleDatas

VUserManagerNewSampleDatas

VUserManagerReadSampleDatas

VUserManagerUpdateSampleDatas

uicontentsmanager/src/Components/NetworkSwitcher
VNetworkSwitcherSampleDatas

userdashboard/src/Components/AdvencedFilterQuickViewer
VAdvencedFilterQuickViewerSampleDatas

userdashboard/src/Components/NetworkSwitcher
VNetworkSwitcherSampleDatas

git/resourcecreator/src/Components/Widgets/Cores/Widget002/Widget002SampleDatas.js

/**
 * 위젯 식별자: WIDGET002
 * 위젯 이름: 키워드 변화량
 */
export default {
  grid: {
    // 그리드의 데이터 배열(등장 빈도수 내림차순)
    datas: [{
      // 키워드
      keyword: '해약 환급금',
      // 키워드의 상담 건수
      keywordTels: 48,
      // 모집단 전체 키워드의 상담 건수
      totalTels: 100,
      // 연관 키워드
      concernKeyWord: '서류',
      // 키워드 등장 빈도수 (통화일 오름차순)
      keywordApparentFrequency: [
        12, 24, 43, 34, 25, 16, 97, 38, 92, 12,
        24, 97, 38, 92, 12, 24, 43, 34, 25, 16,
        97, 38, 92,
      ],
    }, {
      // 키워드
      keyword: '만기',
      // 키워드의 상담 건수
      keywordTels: 45,
      // 모집단 전체 키워드의 상담 건수
      totalTels: 100,
      // 연관 키워드
      concernKeyWord: '이전에',
      // 키워드 등장 빈도수 (통화일 오름차순)
      keywordApparentFrequency: [
        12, 24, 43, 34, 25, 16, 97, 38, 92, 12,
        24, 97, 38, 92, 12, 24, 43, 34, 25, 16,
        97, 38, 92,
      ],
    }, {
      // 키워드
      keyword: '연결 안되서',
      // 키워드의 상담 건수
      keywordTels: 41,
      // 모집단 전체 키워드의 상담 건수
      totalTels: 100,
      // 연관 키워드
      concernKeyWord: '상담원',
      // 키워드 등장 빈도수 (통화일 오름차순)
      keywordApparentFrequency: [
        12, 24, 43, 34, 25, 16, 97, 38, 92, 12,
        24, 97, 38, 92, 12, 24, 43, 34, 25, 16,
        97, 38, 92,
      ],
    }, {
      // 키워드
      keyword: '지점 방문',
      // 키워드의 상담 건수
      keywordTels: 37,
      // 모집단 전체 키워드의 상담 건수
      totalTels: 100,
      // 연관 키워드
      concernKeyWord: '가까운',
      // 키워드 등장 빈도수 (통화일 오름차순)
      keywordApparentFrequency: [
        12, 24, 43, 34, 25, 16, 97, 38, 92, 12,
        24, 97, 38, 92, 12, 24, 43, 34, 25, 16,
        97, 38, 92,
      ],
    }, {
      // 키워드
      keyword: '스마트 번역 유니버셜',
      // 키워드의 상담 건수
      keywordTels: 32,
      // 모집단 전체 키워드의 상담 건수
      totalTels: 100,
      // 연관 키워드
      concernKeyWord: '다른 보험사',
      // 키워드 등장 빈도수 (통화일 오름차순)
      keywordApparentFrequency: [
        12, 24, 43, 34, 25, 16, 97, 38, 92, 12,
        24, 97, 38, 92, 12, 24, 43, 34, 25, 16,
        97, 38, 92,
      ],
    }, {
      // 키워드
      keyword: '종신 보험',
      // 키워드의 상담 건수
      keywordTels: 28,
      // 모집단 전체 키워드의 상담 건수
      totalTels: 100,
      // 연관 키워드
      concernKeyWord: '정기 보험',
      // 키워드 등장 빈도수 (통화일 오름차순)
      keywordApparentFrequency: [
        12, 24, 43, 34, 25, 16, 97, 38, 92, 12,
        24, 97, 38, 92, 12, 24, 43, 34, 25, 16,
        97, 38, 92,
      ],
    }, {
      // 키워드
      keyword: '어제 뉴스',
      // 키워드의 상담 건수
      keywordTels: 20,
      // 모집단 전체 키워드의 상담 건수
      totalTels: 100,
      // 연관 키워드
      concernKeyWord: '예약 환급금',
      // 키워드 등장 빈도수 (통화일 오름차순)
      keywordApparentFrequency: [
        12, 24, 43, 34, 25, 16, 97, 38, 92, 12,
        24, 97, 38, 92, 12, 24, 43, 34, 25, 16,
        97, 38, 92,
      ],
    }],
  },
};

  Generated by ESDoc(0.4.8)


text:
##########################################################################
#Aqueduct - Compliance Remediation Content
#Copyright (C) 2011,2012
#  Vincent C. Passaro (vincent.passaro@gmail.com)
#  Shannon Mitchell (shannon.mitchell@fusiontechnology-llc.com)
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor,
#Boston, MA  02110-1301, USA.
##########################################################################

###################### Fotis Networks LLC ###############################
# By Vincent C. Passaro                                                 #
# Fotis Networks LLC	                                                #
# Vincent[.]Passaro[@]fotisnetworks[.]com                               #
# www.fotisnetworks.com	                                                #
###################### Fotis Networks LLC ###############################
#
#  _____________________________________________________________________
# |  Version |   Change Information  |      Author        |    Date    |
# |__________|_______________________|____________________|____________|
# |    1.0   |   Initial Script      | Vincent C. Passaro | 1-Aug-2012 |
# |          |   Creation            |                    |            |
# |__________|_______________________|____________________|____________|
#

#######################DISA INFORMATION##################################
# Group ID (Vulid): V-4083
# Group Title: GEN000500
# Rule ID: SV-29796r1_rule
# Severity: medium
# Rule Version (STIG-ID): GEN000500
# Rule Title: Graphical desktop environments provided by the system must
# automatically lock after 15 minutes of inactivity and the system must
# require users to re-authenticate to unlock the environment.

# Applications requiring continuous, real-time screen display (i.e.,
# network management products) require the following and need to be
# documented with the IAO.

# -The logon session does not have administrator rights.
# -The display station (i.e., keyboard, monitor, etc.) is located in a
# controlled access area.

#
# Vulnerability Discussion: If graphical desktop sessions do not lock the
# session after 15 minutes of inactivity, requiring re-authentication to
# resume operations, the system or individual data could be compromised by
# an alert intruder who could exploit the oversight.  This requirement
# applies to graphical desktop environments provided by the system to
# locally attached displays and input devices as well as to graphical
# desktop environments provided to remote systems, including thin clients.
#
# Responsibility: System Administrator
# IAControls: PESL-1
#
# Check Content:
#
# For the Gnome screen saver, check the idle_activation_enabled flag.

# Procedure:
# gconftool-2 --direct --config-source
# xml:readwrite:/etc/gconf/gconf.xml.mandatory --get
# /apps/gnome-screensaver/idle_activation_enabled
# If this does not return "true" and a documented exception has not been
# made by the IAO, this is a finding.
#
# Fix Text:
#
# For the Gnome screen saver, set the idle_activation_enabled flag.
# Procedure:
# gconftool-2 --direct --config-source
# xml:readwrite:/etc/gconf/gconf.xml.mandatory --type bool --set
# /apps/gnome-screensaver/idle_activation_enabled true

#######################DISA INFORMATION##################################

# Global Variables
PDI=GEN000500

# Start-Lockdown

IDLEENABLED=`gconftool-2 --direct --config-source xml:read:/etc/gconf/gconf.xml.mandatory --get /apps/gnome-screensaver/idle_activation_enabled 2> /dev/null | awk '!/^Resolved/'`
if [ "$IDLEENABLED" != 'true' ]
then
  gconftool-2 --direct --config-source xml:readwrite:/etc/gconf/gconf.xml.mandatory --type bool --set /apps/gnome-screensaver/idle_activation_enabled true > /dev/null
fi


text:
package com.thoughtbacon.poolbreak;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;

import com.getbase.floatingactionbutton.FloatingActionButton;

public class MainActivity extends ActionBarActivity {

    private final String TAG = MainActivity.class.getSimpleName();
    public static final String DISTANCE_EXTRA = "distance_extra";
    private DistanceCalculator mDistanceCalculator;
    private int mSelectedSpinnerItemIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        populateSpinner();
        setupListeners();
    }

    //region Prepare UI elements

    /**
     * Populates the spinner with values from an array in strings.xml
     */
    private void populateSpinner() {
        Spinner sizeSpinner = (Spinner) findViewById(R.id.size_spinner);
        ArrayAdapter<CharSequence> spinnerAdapter =
                ArrayAdapter.createFromResource(this,
                        R.array.size_values,
                        android.R.layout.simple_spinner_dropdown_item);
        sizeSpinner.setAdapter(spinnerAdapter);
    }
    //endregion

    //region Set UI listeners

    /**
     * Sets all of the listeners
     */
    private void setupListeners() {
        setupSpinnerListener();
        setupDragListener();
        setupButtonListener();
    }

    /**
     * Sets the spinner item selected listener
     */
    private void setupSpinnerListener() {
        Spinner sizeSpinner = (Spinner) findViewById(R.id.size_spinner);
        sizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mSelectedSpinnerItemIndex = position;
                if (mDistanceCalculator != null) {
                    mDistanceCalculator.setTableType(mSelectedSpinnerItemIndex);
                }
                else if (mDistanceCalculator == null) {
                    mDistanceCalculator = new DistanceCalculator(MainActivity.this, mSelectedSpinnerItemIndex);
                    mDistanceCalculator.setTableType(mSelectedSpinnerItemIndex);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * Sets the dragging for cue ball placement
     */
    private void setupDragListener() {
        RelativeLayout setupLayout = (RelativeLayout) findViewById(R.id.setup_layout);
        setupLayout.setOnTouchListener(new View.OnTouchListener() {
            final ImageView ballImage = (ImageView) findViewById(R.id.image_cue_ball);
            ImageView tableImage = (ImageView) findViewById(R.id.image_table);

            int touchStartX, touchStartY;
            int ballStartX, ballStartY;
            int deltaX, deltaY;
            int ballNewX, ballNewY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                final int leftBound = tableImage.getLeft() + ballImage.getWidth();
                final int rightBound = tableImage.getRight() - ballImage.getWidth() * 2;
                final int topBound = (tableImage.getBottom() - ballImage.getHeight()) / 2;
                final int bottomBound = tableImage.getHeight() - ballImage.getHeight() - ballImage.getWidth();

                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (mDistanceCalculator == null)
                        mDistanceCalculator = new DistanceCalculator(MainActivity.this, mSelectedSpinnerItemIndex);

                    touchStartX = (int) event.getX();
                    touchStartY = (int) event.getY();
                }
                else if (event.getAction() == MotionEvent.ACTION_MOVE) {

                    ballStartX = (int) ballImage.getX();
                    ballStartY = (int) ballImage.getY();
                    deltaX = (int) event.getX() - touchStartX;
                    deltaY = (int) event.getY() - touchStartY;
                    ballNewX = ballStartX + deltaX;
                    ballNewY = ballStartY + deltaY;

                    if (ballNewX < leftBound) {
                        ballNewX = leftBound;
                    }
                    if (ballNewX > rightBound) {
                        ballNewX = rightBound;
                    }
                    if (ballNewY < topBound) {
                        ballNewY = topBound;
                    }
                    if (ballNewY > bottomBound) {
                        ballNewY = bottomBound;
                    }
                    ballImage.setX(ballNewX);
                    ballImage.setY(ballNewY);
                    touchStartX = (int) event.getX();
                    touchStartY = (int) event.getY();
                    mDistanceCalculator.setCueBallLocation(ballNewX, ballNewY);
                }
                return true;
            }
        });
    }

    /**
     * Sets the FAB for starting a new break
     */
    private void setupButtonListener() {
        FloatingActionButton breakButton = (FloatingActionButton) findViewById(R.id.button_break);
        breakButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDistanceCalculator == null)
                    mDistanceCalculator = new DistanceCalculator(MainActivity.this, DistanceCalculator.TableType.SEVEN);

                float distance = mDistanceCalculator.getDistanceFromCueToRack();

                Intent breakIntent = new Intent(MainActivity.this, BreakActivity.class);
                breakIntent.putExtra(DISTANCE_EXTRA, distance);
                startActivity(breakIntent);
            }
        });
    }
    //endregion
}


text:
using Newtonsoft.Json;

namespace Discord.API.Rpc
{
    internal class GuildSummary
    {
        [JsonProperty("id")]
        public ulong Id { get; set; }
        [JsonProperty("name")]
        public string Name { get; set; }
    }
}


text:
TEST(PStringUnitTest, Init)
{
  PString str;
  EXPECT_EQ(str.size_, 0U);
  EXPECT_EQ(nullptr, str.data_);
}

TEST(PStringUnitTest, InitWithParam1)
{
  PString str("ABCDEF");
  EXPECT_EQ(str.size_, 7U);
  EXPECT_STREQ(str.data_, "ABCDEF");
}

TEST(PStringUnitTest, InitWithParam2)
{
  PString str("ABCDEFG");
  EXPECT_EQ(str.size_, 8U);
  EXPECT_STREQ(str.data_, "ABCDEFG");
}

TEST(PStringUnitTest, InitWithParam3)
{
  PString str("ABCDEFGH");
  EXPECT_EQ(str.size_, 9U);
  EXPECT_STREQ(str.data_, "ABCDEFGH");
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace ASPPatterns.Chap4.TransactionScript.BLL
{
    public class HolidayService
    {
        private static string connectionString = ConfigurationManager.ConnectionStrings["HR"].ConnectionString;

        public static bool BookHolidayFor(int employeeId, DateTime From, DateTime To)
        {
            bool booked = false;
            TimeSpan numberOfDaysRequestedForHoliday = To - From;

            if (numberOfDaysRequestedForHoliday.Days > 0)
            {
                if (RequestHolidayDoesNotClashWithExistingHoliday(employeeId, From, To))
                {
                    int holidayAvailable = GetHolidayRemainingFor(employeeId);

                    if (holidayAvailable >= numberOfDaysRequestedForHoliday.Days)
                    {
                        SumitHolidayBookingFor(employeeId, From, To);
                        booked = true;
                    }
                }
            }

            return booked;
        }

        private static int GetHolidayRemainingFor(int employeeId)
        {
            List<BookedLeaveDTO> bookedLeave = GetBookedLeaveFor(employeeId);

            int daysTaken = bookedLeave.Sum(hol => hol.DaysTaken);
            int holidayEntitlement = GetHolidayEntitlementFor(employeeId);

            int daysRemaining = holidayEntitlement - daysTaken;

            return daysRemaining;
        }

        public static List<EmployeeDTO> GetAllEmployeesOnLeaveBetween(DateTime From, DateTime To)
        {
            // ... Example of Transaction Script Method ...
            throw new NotImplementedException();
        }

        public static List<EmployeeDTO> GetAllEmployeesWithHolidayRemaing()
        {
            // ... Example of Transaction Script Method ...
            throw new NotImplementedException();
        }

        private static bool RequestHolidayDoesNotClashWithExistingHoliday(int employeeId, DateTime From, DateTime To)
        {
            return true;
        }

        // Data Access methods

        private static void SumitHolidayBookingFor(int employeeId, DateTime From, DateTime To)
        {
            string insertSql = "INSERT INTO Holidays (EmployeeId, LeaveFrom, LeaveTo) VALUES " +
                               "(@EmployeeId, @LeaveFrom, @LeaveTo);";

            using (SqlConnection connection =
                 new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = insertSql;

                command.Parameters.Add(new SqlParameter("@EmployeeId", employeeId));
                command.Parameters.Add(new SqlParameter("@LeaveFrom", From));
                command.Parameters.Add(new SqlParameter("@LeaveTo", To));

                connection.Open();

                command.ExecuteNonQuery();
            }
        }

        public static List<BookedLeaveDTO> GetBookedLeaveFor(int employeeId)
        {
            List<BookedLeaveDTO> bookedLeave = new List<BookedLeaveDTO>();

            string selectSql = "SELECT * FROM Holidays WHERE EmployeeId = @EmployeeId;";

            using (SqlConnection connection =
                  new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = selectSql;
                command.Parameters.Add(new SqlParameter("@EmployeeId", employeeId));

                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        bookedLeave.Add(new BookedLeaveDTO
                        {
                            From = DateTime.Parse(reader["LeaveFrom"].ToString()),
                            To = DateTime.Parse(reader["LeaveTo"].ToString()),
                            DaysTaken = ((TimeSpan)(DateTime.Parse(reader["LeaveTo"].ToString()) - DateTime.Parse(reader["LeaveFrom"].ToString()))).Days
                        });
                    }
                }
            }

            return bookedLeave;
        }

        private static int GetHolidayEntitlementFor(int employeeId)
        {
            string selectSql = "SELECT HolidayEntitlement FROM Employees WHERE Id = @EmployeeId;";

            int holidayEntitlement = 0;

            using (SqlConnection connection =
                 new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = selectSql;

                command.Parameters.Add(new SqlParameter("@EmployeeId", employeeId));

                connection.Open();

                holidayEntitlement = int.Parse(command.ExecuteScalar().ToString());
            }

            return holidayEntitlement;
        }
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure;
using Azure.Core;
using Azure.ResourceManager.Network.Models;

namespace Azure.ResourceManager.Network
{
    public partial class RouteFilterRuleData : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Location))
            {
                writer.WritePropertyName("location");
                writer.WriteStringValue(Location.Value);
            }
            if (Optional.IsDefined(Id))
            {
                writer.WritePropertyName("id");
                writer.WriteStringValue(Id);
            }
            if (Optional.IsDefined(Name))
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsDefined(Access))
            {
                writer.WritePropertyName("access");
                writer.WriteStringValue(Access.Value.ToString());
            }
            if (Optional.IsDefined(RouteFilterRuleType))
            {
                writer.WritePropertyName("routeFilterRuleType");
                writer.WriteStringValue(RouteFilterRuleType.Value.ToString());
            }
            if (Optional.IsCollectionDefined(Communities))
            {
                writer.WritePropertyName("communities");
                writer.WriteStartArray();
                foreach (var item in Communities)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static RouteFilterRuleData DeserializeRouteFilterRuleData(JsonElement element)
        {
            Optional<AzureLocation> location = default;
            Optional<ETag> etag = default;
            Optional<ResourceIdentifier> id = default;
            Optional<string> name = default;
            Optional<ResourceType> type = default;
            Optional<NetworkAccess> access = default;
            Optional<RouteFilterRuleType> routeFilterRuleType = default;
            Optional<IList<string>> communities = default;
            Optional<NetworkProvisioningState> provisioningState = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("location"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    location = new AzureLocation(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("etag"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    etag = new ETag(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("access"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            access = new NetworkAccess(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("routeFilterRuleType"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            routeFilterRuleType = new RouteFilterRuleType(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("communities"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<string> array = new List<string>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(item.GetString());
                            }
                            communities = array;
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = new NetworkProvisioningState(property0.Value.GetString());
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new RouteFilterRuleData(id.Value, name.Value, Optional.ToNullable(type), Optional.ToNullable(location), Optional.ToNullable(etag), Optional.ToNullable(access), Optional.ToNullable(routeFilterRuleType), Optional.ToList(communities), Optional.ToNullable(provisioningState));
        }
    }
}


text:
<?php

namespace CLI;

class Erase {

	/**
	 * Pointer to the stream where the data is sent
	 *
	 * @var resource
	 */
	public static $stream = STDERR;

	/**
	 * Erase to the end of line
	 */
	public static function eol() {
		fwrite(self::$stream, "\033[K");
	}

	/**
	 * Erase to the start of line
	 */
	public static function sol() {
		fwrite(self::$stream, "\033[1K");
	}

	/**
	 * Erase entire line
	 *
	 * @param int|null $row from a specific row
	 */
	public static function line( $row = null ) {
		self::saveWriteRestore(self::$stream, "\033[2K", $row);
	}

	/**
	 * Erases everything below the cursor
	 *
	 * @param int|null $row from a specific row
	 */
	public static function down( $row = null ) {
		self::saveWriteRestore(self::$stream, "\033[J", $row);
	}

	/**
	 * Erases everything above the cursor
	 *
	 * @param int|null $row from a specific row
	 */
	public static function up( $row = null ) {
		self::saveWriteRestore(self::$stream, "\033[1J", $row);
	}

	/**
	 * Erases the entire screen
	 */
	public static function screen() {
		fwrite(self::$stream, "\033[2J");
	}

	/**
	 * @param resource $stream
	 * @param string $str
	 * @param integer|null $row
	 */
	protected static function saveWriteRestore($stream, $str, $row) {
		if( $row ) {
			Cursor::savepos();
			Cursor::rowcol($row, Misc::cols());
		}
		fwrite($stream, $str);
		if( $row ) {
			Cursor::restore();
		}
	}

}


text:
from __future__ import print_function
import sys
import os
import re
import sqlite3
import subprocess
from optparse import OptionParser
from indexing import cansmirk, heavy_atom_count
from rfrag import fragment_mol

def cmpd_not_in_db_mmp_query(in_smi, cmpd_id):

  query_contexts = set()
  cmpd_frags = fragment_mol(in_smi, cmpd_id)
  for row in cmpd_frags:
    row = row.rstrip()
    row_fields = re.split(',', row)
    if (row_fields[3].count(".") == 1):
      a, b = row_fields[3].split(".")
      query_contexts.add(a)
      query_contexts.add(b)
    else:
      query_contexts.add(row_fields[3])

  q_string = "','".join(query_contexts)
  q_string = "'%s'" % (q_string)

  query_sql = """
    select  c.cmpd_id,
            c.core_smi,
            con.context_smi,
            con.context_size
    from    core_table c, context_table con
    where   c.context_id in (select context_id from context_table where context_smi in (%s))
            and c.context_id = con.context_id""" % (q_string)
  cursor.execute(query_sql)
  results = cursor.fetchall()

  cmpd_size = heavy_atom_count(in_smi)
  print_smallest_change_mmp(results, cmpd_id, cmpd_size)

def run_mmp_query(cmpd_id, cmpd_size):
  query_sql = """
    select  c.cmpd_id,
            c.core_smi,
            con.context_smi,
            con.context_size
    from    core_table c, context_table con
    where   c.context_id in (select context_id from core_table where cmpd_id = '%s')
            and c.context_id = con.context_id""" % (cmpd_id)
  cursor.execute(query_sql)
  results = cursor.fetchall()

  print_smallest_change_mmp(results, cmpd_id, cmpd_size)

def print_smallest_change_mmp(db_results, cmpd_id, query_size):

  uniq_list = {}
  for r in db_results:
    if (r[0] != cmpd_id):
      #print r
      #for each unique compound keep the largest one in common
      if (r[0] not in uniq_list):
        uniq_list[r[0]] = r
      elif (r[3] > uniq_list[r[0]][3]):
        uniq_list[r[0]] = r

  for key, value in uniq_list.items():
    size_of_change = query_size - value[3]
    #print "q_size: %s, Size od change: %s, Ratio: %s" % (query_size,size_of_change,float(size_of_change)/query_size)
    if (use_ratio):
      if (float(size_of_change) / query_size <= ratio):
        cursor.execute("SELECT smiles FROM cmpd_smisp WHERE cmpd_id = ?", (key, ))
        rsmi = cursor.fetchone()[0]
        print("%s,%s,%s,%s,%s,%s" % (smi, rsmi, id, value[0], value[1], value[2]))
    elif (size_of_change <= max_size):
      cursor.execute("SELECT smiles FROM cmpd_smisp WHERE cmpd_id = ?", (key, ))
      rsmi = cursor.fetchone()[0]
      print("%s,%s,%s,%s,%s,%s" % (search_string, rsmi, id, value[0], value[1], value[2]))

def run_subs_query(subs):

  query_sql = """
    select  lhs_smi.smiles,
            lhs.cmpd_id,
            lhs.core_smi,
            rhs_smi.smiles,
            rhs.cmpd_id,
            rhs.core_smi,
            context_table.context_smi,
            rhs_smi.cmpd_size-context_table.context_size
    from    (select cmpd_id,core_smi,context_id from core_table where core_smi_ni = '%s') lhs,
            core_table rhs,
            cmpd_smisp lhs_smi,
            cmpd_smisp rhs_smi,
            context_table
    where   lhs.context_id = rhs.context_id
            and context_table.context_id = rhs.context_id
            and lhs_smi.cmpd_id = lhs.cmpd_id
            and rhs_smi.cmpd_id = rhs.cmpd_id
            and lhs.cmpd_id != rhs.cmpd_id
            and rhs_smi.cmpd_size-context_table.context_size <= %s""" % (subs, max_size)
  cursor.execute(query_sql)
  results = cursor.fetchall()

  for r in results:
    #make sure it is not the same core on both sides
    if (r[2] != r[5]):
      #cansmirk
      smirks, context = cansmirk(str(r[2]), str(r[5]), str(r[6]))
      if (have_id):
        print("%s,%s,%s,%s,%s,%s,%s,%s" % (subs, id, r[0], r[3], r[1], r[4], smirks, context))
      else:
        print("%s,%s,%s,%s,%s,%s,%s" % (subs, r[0], r[3], r[1], r[4], smirks, context))

def run_subs_smarts_query(subs_smarts):

  #set os enviroment for rdkit to use sqllite
  os.environ['RD_USESQLLITE'] = '1'
  temp_core_ni_file = 'temp_core_ni_file_%s' % (os.getpid())
  cmd = "python $RDBASE/Projects/DbCLI/SearchDb.py --dbDir=%s_smarts --smarts='%s' --silent >%s" % (
    pre, subs_smarts, temp_core_ni_file)
  subprocess.Popen(cmd, shell=True).wait()

  infile = open(temp_core_ni_file, 'r')
  for row in infile:
    row = row.rstrip()

    query_sql = """
        select  lhs_smi.smiles,
                lhs.cmpd_id,
                lhs.core_smi,
                rhs_smi.smiles,
                rhs.cmpd_id,
                rhs.core_smi,
                context_table.context_smi,
                rhs_smi.cmpd_size-context_table.context_size
        from    (select cmpd_id,core_smi,context_id from core_table where core_smi_ni = '%s') lhs,
                core_table rhs,
                cmpd_smisp lhs_smi,
                cmpd_smisp rhs_smi,
                context_table
        where   lhs.context_id = rhs.context_id
                and context_table.context_id = rhs.context_id
                and lhs_smi.cmpd_id = lhs.cmpd_id
                and rhs_smi.cmpd_id = rhs.cmpd_id
                and lhs.cmpd_id != rhs.cmpd_id
                and rhs_smi.cmpd_size-context_table.context_size <= %s
                and lhs_smi.cmpd_size-context_table.context_size <= %s""" % (row, max_size,
                                                                             max_size)
    cursor.execute(query_sql)
    results = cursor.fetchall()

    for r in results:
      #cansmirk
      smirks, context = cansmirk(str(r[2]), str(r[5]), str(r[6]))
      if (have_id):
        print("%s,%s,%s,%s,%s,%s,%s" % (id, r[0], r[3], r[1], r[4], smirks, context))
      else:
        print("%s,%s,%s,%s,%s,%s" % (r[0], r[3], r[1], r[4], smirks, context))
  infile.close()
  #remove temporary files
  os.unlink(temp_core_ni_file)

def run_trans_smarts_query(transform):

  lhs, rhs = transform.split(">>")
  matching_lhs = []
  matching_rhs = []

  #set os enviroment for rdkit to use sqllite
  os.environ['RD_USESQLLITE'] = '1'

  cmd = "python $RDBASE/Projects/DbCLI/SearchDb.py --dbDir=%s_smarts --smarts='%s' --silent" % (pre,
                                                                                lhs)
  p1 = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
  output = p1.communicate()[0].decode().rstrip()
  matching_lhs = output.split("\n")
  #sys.stderr.write("rhs: %s\n" % (len(matching_lhs)) )

  cmd = "python $RDBASE/Projects/DbCLI/SearchDb.py --dbDir=%s_smarts --smarts='%s' --silent" % (pre,
                                                                                rhs)
  p1 = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
  output = p1.communicate()[0].decode().rstrip()
  matching_rhs = output.split("\n")
  #sys.stderr.write("rhs: %s\n" % (len(matching_rhs)) )

  #sys.stderr.write('SQLlite method\n')
  lhs_q_string = "','".join(matching_lhs)
  lhs_q_string = "'%s'" % (lhs_q_string)

  rhs_q_string = "','".join(matching_rhs)
  rhs_q_string = "'%s'" % (rhs_q_string)

  query_sql = """
    select  lhs_smi.smiles,
            lhs.cmpd_id,
            lhs.core_smi,
            rhs_smi.smiles,
            rhs.cmpd_id,
            rhs.core_smi,
            context_table.context_smi
    from    (select cmpd_id,core_smi,context_id from core_table where core_smi_ni in (%s) ) lhs,
            (select cmpd_id,core_smi,context_id from core_table where core_smi_ni in (%s) ) rhs,
            cmpd_smisp lhs_smi,
            cmpd_smisp rhs_smi,
            context_table
    where   lhs.context_id = rhs.context_id
            and context_table.context_id = rhs.context_id
            and lhs_smi.cmpd_id = lhs.cmpd_id
            and rhs_smi.cmpd_id = rhs.cmpd_id
            and lhs.cmpd_id != rhs.cmpd_id
            and rhs_smi.cmpd_size-context_table.context_size <= %s
            and lhs_smi.cmpd_size-context_table.context_size <= %s """ % (
    lhs_q_string, rhs_q_string, max_size, max_size)

  cursor.execute(query_sql)
  results = cursor.fetchall()

  for r in results:
    smirks, context = cansmirk(str(r[2]), str(r[5]), str(r[6]))
    if (have_id):
      print("%s,%s,%s,%s,%s,%s,%s,%s" % (transform, id, r[0], r[3], r[1], r[4], smirks, context))
    else:
      print("%s,%s,%s,%s,%s,%s,%s" % (transform, r[0], r[3], r[1], r[4], smirks, context))

def run_trans_query(transform):

  lhs, rhs = transform.split(">>")

  #remove connectivity info
  lhs_ni = remove_numbers(lhs)
  rhs_ni = remove_numbers(rhs)

  query_sql = """
    select  lhs_smi.smiles,
            lhs.cmpd_id,
            lhs.core_smi,
            rhs_smi.smiles,
            rhs.cmpd_id,
            rhs.core_smi,
            context_table.context_smi
    from    (select cmpd_id,core_smi,context_id from core_table where core_smi_ni = '%s') lhs,
            (select cmpd_id,core_smi,context_id from core_table where core_smi_ni = '%s') rhs,
            cmpd_smisp lhs_smi,
            cmpd_smisp rhs_smi,
            context_table
    where   lhs.context_id = rhs.context_id
            and context_table.context_id = rhs.context_id
            and lhs_smi.cmpd_id = lhs.cmpd_id
            and rhs_smi.cmpd_id = rhs.cmpd_id""" % (lhs_ni, rhs_ni)

  cursor.execute(query_sql)
  results = cursor.fetchall()

  for r in results:
    smirks, context = cansmirk(str(r[2]), str(r[5]), str(r[6]))
    #make sure connectivity is correct
    if (smirks == transform):
      if (have_id):
        print("%s,%s,%s,%s,%s,%s,%s" % (id, r[0], r[3], r[1], r[4], smirks, context))
      else:
        print("%s,%s,%s,%s,%s,%s" % (r[0], r[3], r[1], r[4], smirks, context))

def remove_numbers(in_string):

  out_string = re.sub(r'\[\*\:1\]', '[*]', in_string)
  out_string = re.sub(r'\[\*\:2\]', '[*]', out_string)
  out_string = re.sub(r'\[\*\:3\]', '[*]', out_string)

  return out_string

#quick class to help with the formatting of optparse
class MyParser(OptionParser):

  def format_description(self, formatter):
    return self.description

parser = MyParser(
  description="""Program to search MMP db. The types of searching that can be performed are as
follows:

mmp: Find all MMPs of a input/query compound to the compounds in the db

subs: Find all MMPs in the db where the LHS of the transform matches an input
substructure. Make sure the attached points are donated by an asterisk and the
input substructure has been canonicalised (eg. [*]c1ccccc1).

trans: Find all MMPs that match the input transform/SMIRKS. Make sure the input
SMIRKS has been canonicalised using the cansmirk.py program.

subs_smarts: Find all MMPs in the db where the LHS of the transform matches an
input SMARTS. The attachment points in the SMARTS can be donated by [#0] (eg.
[#0]c1ccccc1).

trans_smarts: Find all MMPs that match the LHS and RHS SMARTS of the input
transform. The transform SMARTS are input as LHS_SMARTS>>RHS_SMARTS (eg.
[#0]c1ccccc1>>[#0]c1ccncc1). Note: This search can take a long time to run if a
very general SMARTS expression is used.
""")
parser.add_option(
  '-t', '--type', action='store', dest='type', type='string',
  help='Type of search required. Options are: mmp, subs, trans, subs_smarts, trans_smarts')
parser.add_option(
  '-m', '--maxsize', action='store', dest='maxsize', type='int',
  help='Maximum size of change (in heavy atoms) allowed in matched molecular pairs identified. DEFAULT=10. \
                  Note: This option overrides the ratio option if both are specified.')
parser.add_option(
  '-r', '--ratio', action='store', dest='ratio', type='float',
  help='Only applicable with the mmp search type. Maximum ratio of change allowed in matched molecular pairs identified. The ratio is: size of change / \
                  size of cmpd (in terms of heavy atoms) for the QUERY MOLECULE. DEFAULT=0.3. Note: If this option is used with the maxsize option, the maxsize option will be used.')
parser.add_option('-p', '--prefix', action='store', dest='prefix', type='string',
                  help='Prefix for the db file. DEFAULT=mmp')

#parse the command line options
(options, args) = parser.parse_args()

#note max heavy atom count does not
#include the attachement points (*)
max_size = 10
ratio = 0.3
use_ratio = False
have_id = True

search_type = "mmp"
db_name = "mmp.db"
pre = "mmp"

if (options.maxsize != None):
  max_size = options.maxsize
elif (options.ratio != None):
  ratio = options.ratio
  if (ratio >= 1):
    print("Ratio specified: %s. Ratio needs to be less than 1.")
    sys.exit(1)
  use_ratio = True

if (options.type != None):
  if ((options.type == "mmp") or (options.type == "subs") or (options.type == "trans") or
      (options.type == "subs_smarts") or (options.type == "trans_smarts")):
    search_type = options.type
  else:
    print(
      "Unrecognised search type. Please choose from: mmp, subs, trans, subs_smarts, trans_smarts")
    sys.exit(1)
else:
  print(
    "Please specify search type. Please choose from: mmp, subs, trans, subs_smarts, trans_smarts")
  sys.exit(1)

if (options.prefix != None):
  pre = options.prefix
  db_name = "%s.db" % (pre)

#connect to db
con = sqlite3.connect(db_name)
cursor = con.cursor()

#these setting increase performance
cursor.execute('PRAGMA main.page_size = 4096;')
cursor.execute('PRAGMA main.cache_size=10000;')
cursor.execute('PRAGMA main.locking_mode=EXCLUSIVE;')
cursor.execute('PRAGMA main.synchronous=NORMAL;')
cursor.execute('PRAGMA main.journal_mode=WAL;')
cursor.execute('PRAGMA main.cache_size=5000;')
cursor.execute('PRAGMA main.temp_store = MEMORY;')

#read the STDIN
for line in sys.stdin:

  line = line.rstrip()
  line_fields = re.split('\s|,', line)

  if (len(line_fields) == 1):
    id = line_fields[0]
    have_id = False
  else:
    id = line_fields[1]

  search_string = line_fields[0]

  if (search_type == "mmp"):
    #check smiles is in the database
    cursor.execute("SELECT cmpd_id,cmpd_size FROM cmpd_smisp WHERE smiles = ?", (search_string, ))
    d_res = cursor.fetchone()

    #cmpd in the db
    if (d_res):
      id_in_db, query_size = d_res
      run_mmp_query(id_in_db, query_size)
    else:
      #print "Not in db"
      cmpd_not_in_db_mmp_query(search_string, id)

  #if doing a subs query
  elif (search_type == "subs"):
    run_subs_query(search_string)

  elif (search_type == "trans"):
    run_trans_query(search_string)

  #smarts queries
  elif (search_type == "subs_smarts"):
    run_subs_smarts_query(search_string)

  elif (search_type == "trans_smarts"):
    run_trans_smarts_query(search_string)


text:
rm -rf nginx-1.2.5
if [ ! -f nginx-1.2.5.tar.gz ];then
  wget http://oss.aliyuncs.com/aliyunecs/onekey/nginx/nginx-1.2.5.tar.gz
fi
tar zxvf nginx-1.2.5.tar.gz
cd nginx-1.2.5
./configure --user=www \
--group=www \
--prefix=/alidata/server/nginx \
--with-http_stub_status_module \
--without-http-cache \
--with-http_ssl_module \
--with-http_gzip_static_module
CPU_NUM=$(cat /proc/cpuinfo | grep processor | wc -l)
if [ $CPU_NUM -gt 1 ];then
    make -j$CPU_NUM
else
    make
fi
make install
chmod 775 /alidata/server/nginx/logs
chown -R www:www /alidata/server/nginx/logs
chmod -R 775 /alidata/www
chown -R www:www /alidata/www
cd ..
cp -fR ./nginx/config-nginx/* /alidata/server/nginx/conf/
sed -i 's/worker_processes  2/worker_processes  '"$CPU_NUM"'/' /alidata/server/nginx/conf/nginx.conf
chmod 755 /alidata/server/nginx/sbin/nginx
#/alidata/server/nginx/sbin/nginx
mv /alidata/server/nginx/conf/nginx /etc/init.d/
chmod +x /etc/init.d/nginx
/etc/init.d/nginx start


text:
<?php

defined('BASEPATH') or exit('No direct script access allowed');

// ------------------------------------------------------------------------

class Wiki extends MX_Controller
{
    public $partials = array();
    public $permissions = array();
    public $sitePermissions = array();

    public function __construct()
    {
        parent::__construct();

        // get site permissions and redirect if it don't have access to this module
        if (!$this->permission->sitePermissions) {
            show_error('You do not have permission to view this page');
        }
        if (!in_array($this->uri->segment(1), $this->permission->sitePermissions)) {
            show_error('You do not have permission to view this page');
        }

        // get permissions for the logged in admin
        if ($this->session->userdata('session_admin')) {
            $this->permission->permissions = $this->permission->get_group_permissions($this->session->userdata('groupID'));
        }

        // get siteID, if available
        if (defined('SITEID')) {
            $this->siteID = SITEID;
        }

        // load libs etc
        $this->load->model('wiki_model', 'wiki');
        $this->load->module('pages');
        $this->load->library('parser');
        $this->load->library('mkdn');

        // load partials - categories
        $data['pages'] = $this->wiki->get_pages();
        $data['categories'] = $this->wiki->get_categories();
        $this->partials['wiki:categories'] = $this->parser->parse('partials/categories', $data, true);
    }

    public function index()
    {
        if ($this->uri->segment(2)) {
            // deprecated uri code (now its always just the uri string)
            $num = 2;
            $uri = '';
            while ($segment = $this->uri->segment($num)) {
                $uri .= $segment.'/';
                $num ++;
            }
            $new_length = strlen($uri) - 1;
            $uri = substr($uri, 0, $new_length);
        } else {
            $uri = 'home';
        }

        $this->view($uri);
    }

    public function view($page)
    {
        // get partials
        $output = $this->partials;

        // load wiki page
        $wikipage = $this->wiki->get_page(false, $page);

        // get versions
        if (isset($versions)) {
            $versions = $this->wiki->get_versions($page['pageID']);
        }
        // get page
        $output['wikipage'] = $wikipage;
        $output['wikipage:link'] = site_url('/wiki/edit/'.$this->core->encode($page));
        $output['wikipage:body'] = mkdn($wikipage['body']);

        // set title
        $output['page:title'] = $this->site->config['siteName'].' | Wiki - '.$wikipage['pageName'];
        $output['page:heading'] = $wikipage['pageName'];

        // display with cms layer
        $this->pages->view('wiki_page', $output, true);
    }

    public function edit($page)
    {
        // check user is logged in, if not send them away from this controller
        if (!$this->session->userdata('session_user')) {
            redirect('/users/login/'.$this->core->encode($this->uri->uri_string()));
        }

        // get page
        $uri = $this->core->decode($page);

        // deal with post
        if (count($_POST)) {
            if ($this->wiki->update_page($uri)) {
                redirect('/wiki/'.$uri);
            }
        }

        // load wiki page
        $wikipage = $this->wiki->get_page(false, $uri);

        // get versions
        if ($versions = $this->wiki->get_versions($wikipage['pageID'])) {
            foreach ($versions as $version) {
                $output['versions'][] = array(
                    'version' => ($wikipage['versionID'] == $version['versionID']) ?
                        ''.dateFmt($version['dateCreated']).
                            (($user = $this->wiki->lookup_user($version['userID'], true)) ? ', by '.$user : '').
                            (($notes = $version['notes']) ? ' ('.$notes.')' : '').
                        '' :
                        dateFmt($version['dateCreated']).
                            (($user = $this->wiki->lookup_user($version['userID'], true)) ? ', by '.$user : '').
                            (($notes = $version['notes']) ? ' ('.$notes.')' : '').
                        ' | '.anchor('/wiki/revert/'.$this->core->encode($uri).'/'.$version['versionID'], 'Revert', 'onclick="return confirm(\'You will lose unsaved changes. Continue?\');"')
                );
            }
        }

        // get categories
        if ($categories = $this->wiki->get_categories()) {
            foreach ($categories as $category) {
                $options[$category['catID']] = $category['catName'];
            }
        }
        $options[0] = 'No Category';

        // populate template
        $output['wikipage:link'] = site_url('/wiki/'.$wikipage['uri']);
        $output['form:title'] = $wikipage['pageName'];
        $output['select:categories'] = @form_dropdown('catID', $options, set_value('catID', $wikipage['catID']), 'id="category" class="formelement"');
        $output['form:body'] = $wikipage['body'];
        $output['form:notes'] = $this->input->post('notes');

        // set title
        $output['page:title'] = $this->site->config['siteName'].' | Edit Wiki';
        $output['page:heading'] = 'Edit Page - "'.$uri.'"';

        // display with cms layer
        $this->pages->view('wiki_form', $output, true);
    }

    public function revert($page = '', $versionID = '')
    {
        // check stuff
        if (!$page || !$versionID) {
            show_error('Something went wrong!');
        }

        // get page
        $uri = $this->core->decode($page);

        if (!$page = $this->wiki->get_page(false, $uri)) {
            show_error('No page found!');
        }

        // revert and redirect
        if ($this->wiki->revert_page($page['pageID'], $versionID)) {
            redirect('/wiki/'.$uri);
        } else {
            show_error('Something went wrong!');
        }
    }

    public function pages($catID = '')
    {
        $row = null;
        // get category or fail
        $category = ($catID && $row = $this->wiki->get_categories($catID)) ? $row['catName'] : 'Uncategorised';

        // get partials
        $output = $this->partials;

        // get pages
        $catID = ($catID) ? $catID : false;
        if ($pages = $this->wiki->get_pages($catID)) {
            foreach ($pages as $page) {
                $output['wikipages'][] = array(
                    'wikipage:title' => $page['pageName'],
                    'wikipage:link' => site_url('/wiki/'.$page['uri'])
                );
            }
        }

        // set title
        $output['page:title'] = $this->site->config['siteName'].' | Wiki - '.$category;
        $output['page:heading'] = $category;
        $output['page:description'] = mkdn($row['description']);

        // display with cms layer
        $this->pages->view('wiki', $output, true);
    }

    public function search($tag = '')
    {
        // get partials
        $output = $this->partials;

        // set tags
        $query = ($tag) ? $tag : strip_tags($this->input->post('query', true));

        if ($pageIDs = $this->wiki->search_wiki($query)) {
            if ($pages = $this->wiki->get_pages(null, $pageIDs)) {
                foreach ($pages as $page) {
                    $output['wikipages'][] = array(
                        'wikipage:title' => $page['pageName'],
                        'wikipage:link' => site_url('/wiki/'.$page['uri'])
                    );
                }
            }
        }

        // set pagination
        $output['pagination'] = ($pagination = $this->pagination->create_links()) ? $pagination : '';

        // set title
        $output['page:title'] = $this->site->config['siteName'].' | Searching wiki for "'.$query.'"';
        $output['page:heading'] = 'Search wiki for: "'.$query.'"';

        // display with cms layer
        $this->pages->view('wiki_search', $output, true);
    }
}


text:
<?php

namespace PHPExiftool\Driver\Tag\DICOM;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class DigitalSignatureDateTime extends AbstractTag
{

    protected $Id = '0400,0105';

    protected $Name = 'DigitalSignatureDateTime';

    protected $FullName = 'DICOM::Main';

    protected $GroupName = 'DICOM';

    protected $g0 = 'DICOM';

    protected $g1 = 'DICOM';

    protected $g2 = 'Image';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Digital Signature Date Time';

}


text:
module ElectionCarousel {

    "use strict";

    export class Advertising {

        constructor() { }

        public static createInstance = () => {
            return new Advertising();
        }

        public restrict: string = "E";

        public replace: boolean = true;

        public templateUrl: string = "src/app/election/directives/advertising/advertising.html";

        public link = () => {

        }
    }

    angular.module("election").directive("advertising", [Advertising.createInstance]);

}


text:
package com.unicorn.co226.model;

/**
 * Project - HealthCenterProj
 * Created by Dinuka Nadeeshan on 8/30/16.
 * dinuka.nadeeshan1993@gmail.com
 */
public class Patient {
    private String id;
    private String name;
    private String address;
    private int age;
    private String dob;

    public Patient(){}

    public Patient(String id, String name, String address, String dob) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.dob = dob;
    }

    public Patient(String id, String name, String address, int age, String dob) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.age = age;
        this.dob = dob;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }
}