text:
package passhash_test

import (
	"testing"
)

import (
	"github.com/dhui/passhash"
)

// setupAuditLoggerTestData logs test data to the given AuditLogger
func setupAuditLoggerTestData(userID passhash.UserID, al passhash.AuditLogger) int { // nolint: unparam
	numIters := 5
	for i := 0; i < numIters; i++ {
		al.Log(userID, passhash.AuthnSucceeded, passhash.EmptyIP)
		al.Log(userID, passhash.AuthnFailed, passhash.EmptyIP)
		al.Log(userID, passhash.UpgradedKdf, passhash.EmptyIP)
	}
	return numIters * 3
}

func TestDummyAuditLoggerLog(t *testing.T) {
	al := passhash.DummyAuditLogger{}
	userID := passhash.UserID(0)
	al.Log(userID, passhash.AuthnSucceeded, passhash.EmptyIP)
}

func TestDummyAuditLoggerLastN(t *testing.T) {
	al := &passhash.DummyAuditLogger{}
	userID := passhash.UserID(0)
	n := setupAuditLoggerTestData(userID, al)
	if l := len(al.LastN(userID, n)); l != 0 {
		t.Errorf("DummyAuditLogger has data! Has %d elements", l)
	}
}

func TestDummyAuditLoggerLastNWithTypes(t *testing.T) {
	al := &passhash.DummyAuditLogger{}
	userID := passhash.UserID(0)
	n := setupAuditLoggerTestData(userID, al)
	if l := len(al.LastNWithTypes(userID, n, passhash.AuthnSucceeded)); l != 0 {
		t.Errorf("DummyAuditLogger has data! Has %d elements", l)
	}
}

func TestMemoryAuditLoggerLog(t *testing.T) {
	al := passhash.MemoryAuditLogger{}
	userID := passhash.UserID(0)
	al.Log(userID, passhash.AuthnSucceeded, passhash.EmptyIP)
	if l := len(al.LastN(userID, 10)); l != 1 {
		t.Errorf("Unexpected number of logs. Have %d instead of 1", l)
	}
}

func TestMemoryAuditLoggerLastNLess(t *testing.T) {
	al := &passhash.MemoryAuditLogger{}
	userID := passhash.UserID(0)
	n := setupAuditLoggerTestData(userID, al)
	lastN := al.LastN(userID, n/2)
	if l := len(lastN); l != n/2 {
		t.Errorf("Did not retrieve expected number of logs. Have %d logs instead of %d", l, n/2)
	}
}

func TestMemoryAuditLoggerLastNEqual(t *testing.T) {
	al := &passhash.MemoryAuditLogger{}
	userID := passhash.UserID(0)
	n := setupAuditLoggerTestData(userID, al)
	lastN := al.LastN(userID, n)
	if l := len(lastN); l != n {
		t.Errorf("Did not retrieve expected number of logs. Have %d logs instead of %d", l, n)
	}
}

func TestMemoryAuditLoggerLastNMore(t *testing.T) {
	al := &passhash.MemoryAuditLogger{}
	userID := passhash.UserID(0)
	n := setupAuditLoggerTestData(userID, al)
	lastN := al.LastN(userID, n*2)
	if l := len(lastN); l != n {
		t.Errorf("Did not retrieve expected number of logs. Have %d logs instead of %d", l, n)
	}
}

func TestMemoryAuditLoggerLastNWithTypesNone(t *testing.T) {
	al := &passhash.MemoryAuditLogger{}
	userID := passhash.UserID(0)
	n := setupAuditLoggerTestData(userID, al)
	lastN := al.LastNWithTypes(userID, n)
	if len(lastN) != 0 {
		t.Errorf("Got %d log entries when no types were specified", len(lastN))
	}
}

func TestMemoryAuditLoggerLastNWithTypesLess(t *testing.T) {
	al := &passhash.MemoryAuditLogger{}
	userID := passhash.UserID(0)
	n := setupAuditLoggerTestData(userID, al)
	lastN := al.LastNWithTypes(userID, (n/3)-3, passhash.AuthnSucceeded)
	if l := len(lastN); l != (n/3)-3 {
		t.Errorf("Did not retrieve expected number of logs. Have %d logs instead of %d", l, (n/3)-3)
		t.Log(lastN)
	}
}

func TestMemoryAuditLoggerLastNWithTypesEqual(t *testing.T) {
	al := &passhash.MemoryAuditLogger{}
	userID := passhash.UserID(0)
	n := setupAuditLoggerTestData(userID, al)
	lastN := al.LastNWithTypes(userID, (n / 3), passhash.AuthnSucceeded)
	if l := len(lastN); l != n/3 {
		t.Errorf("Did not retrieve expected number of logs. Have %d logs instead of %d", l, n/3)
		t.Log(lastN)
	}
}

func TestMemoryAuditLoggerLastNWithTypesMore(t *testing.T) {
	al := &passhash.MemoryAuditLogger{}
	userID := passhash.UserID(0)
	n := setupAuditLoggerTestData(userID, al)
	lastN := al.LastNWithTypes(userID, n, passhash.AuthnSucceeded)
	if l := len(lastN); l != n/3 {
		t.Errorf("Did not retrieve expected number of logs. Have %d logs instead of %d", l, n/3)
		t.Log(lastN)
	}
}


text:
echo SEP: Testing Symmetric Eigenvalue Problem routines
exec ./test_eigs < $CBLAPACKDIR/test/input/sep.in

redpajama_set_name: RedPajamaGithub


text:
#ifndef BOOST_CONTAINER_DETAIL_NODE_POOL_COMMON_HPP
#define BOOST_CONTAINER_DETAIL_NODE_POOL_COMMON_HPP

#if (defined _MSC_VER) && (_MSC_VER >= 1200)
#  pragma once
#endif

#include "config_begin.hpp"
#include <boost/intrusive/slist.hpp>
#include <new>

namespace boost {
namespace container {
namespace container_detail {

template<class VoidPointer>
struct node_slist
{
   //This hook will be used to chain the individual nodes
    typedef typename bi::make_slist_base_hook
      <bi::void_pointer<VoidPointer>, bi::link_mode<bi::normal_link> >::type slist_hook_t;

   //A node object will hold node_t when it's not allocated
   typedef slist_hook_t node_t;

   typedef typename bi::make_slist
      <node_t, bi::linear<true>, bi::cache_last<true>, bi::base_hook<slist_hook_t> >::type node_slist_t;
};

template<class T>
struct is_stateless_segment_manager
{
   static const bool value = false;
};

}  //namespace container_detail {
}  //namespace container {
}  //namespace boost {

#include <boost/container/detail/config_end.hpp>

#endif   //#ifndef BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP


text:
package com.intellij.codeInsight.template.emmet.nodes;

import com.google.common.base.Joiner;
import com.intellij.codeInsight.template.CustomTemplateCallback;
import com.intellij.codeInsight.template.emmet.ZenCodingUtil;
import com.intellij.codeInsight.template.emmet.generators.ZenCodingGenerator;
import com.intellij.codeInsight.template.emmet.tokens.TemplateToken;
import com.intellij.codeInsight.template.impl.TemplateImpl;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.List;

/**
 * @author Eugene.Kudelevsky
 */
public class TemplateNode extends ZenCodingNode {
  private static final Joiner JOINER = Joiner.on(",");
  private final TemplateToken myTemplateToken;
  @Nullable private final ZenCodingGenerator myGenerator;

  public TemplateNode(TemplateToken templateToken) {
    this(templateToken, null);
  }

  public TemplateNode(TemplateToken token, @Nullable ZenCodingGenerator generator) {
    myTemplateToken = token;
    myGenerator = generator;
  }

  public TemplateToken getTemplateToken() {
    return myTemplateToken;
  }

  @NotNull
  @Override
  public List<GenerationNode> expand(int numberInIteration,
                                     int totalIterations, String surroundedText,
                                     CustomTemplateCallback callback,
                                     boolean insertSurroundedTextAtTheEnd, GenerationNode parent) {
    TemplateToken templateToken = myTemplateToken;
    String templateKey = templateToken.getKey();
    if (myGenerator != null && StringUtil.containsChar(templateKey, '$') && callback.findApplicableTemplate(templateKey) == null) {
      String newTemplateKey = ZenCodingUtil.replaceMarkers(templateKey, numberInIteration, totalIterations, surroundedText);
      TemplateToken newTemplateToken = new TemplateToken(newTemplateKey,
                                        templateToken.getAttribute2Value());

      TemplateImpl template = myGenerator.createTemplateByKey(newTemplateKey);
      if (template != null) {
        template.setDeactivated(true);
        newTemplateToken.setTemplate(template, callback);
        templateToken = newTemplateToken;
      }
  }

  GenerationNode node = new GenerationNode(templateToken, numberInIteration, totalIterations,
                                           surroundedText, insertSurroundedTextAtTheEnd, parent);
  return Arrays.asList(node);
}

  @Override
  public String toString() {
    String result = myTemplateToken.getKey();
    List<Pair<String, String>> attributes = myTemplateToken.getAttribute2Value();
    if (!attributes.isEmpty()) {
      result += "[" + JOINER.join(myTemplateToken.getAttribute2Value()) + "]";
    }
    return "Template(" + result + ")";
  }
}


text:
<?php

/**
 * Class Itabs_LogViewer_Adminhtml_LogviewerController
 */
class Itabs_LogViewer_Adminhtml_LogviewerController
    extends Mage_Adminhtml_Controller_Action
{
    /**
     * Show the log file viewer
     */
    public function indexAction()
    {
        $this->loadLayout();
        $this->_setActiveMenu('system/logviewer');
        $this->_title($this->__('Log Viewer'));
        $this->renderLayout();
    }

    /**
     * Download the given log file
     */
    public function downloadAction()
    {
        $file = $this->getLogHelper()->getCurrentFile();
        if ($file) {
            $path = $this->getLogHelper()->getLogDir() . $file;
            $this->_prepareDownloadResponse($file, file_get_contents($path));

            return;
        }

        return $this->_redirect('*/*');
    }

    /**
     * Retrieve the log viewer helper
     *
     * @return Itabs_LogViewer_Helper_Data
     */
    public function getLogHelper()
    {
        return Mage::helper('itabs_logviewer');
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="CompilerConfiguration">
    <option name="DEFAULT_COMPILER" value="Javac" />
    <resourceExtensions />
    <wildcardResourcePatterns>
      <entry name="!?*.java" />
      <entry name="!?*.form" />
      <entry name="!?*.class" />
      <entry name="!?*.groovy" />
      <entry name="!?*.scala" />
      <entry name="!?*.flex" />
      <entry name="!?*.kt" />
      <entry name="!?*.clj" />
      <entry name="!?*.aj" />
    </wildcardResourcePatterns>
    <annotationProcessing>
      <profile default="true" name="Default" enabled="false">
        <processorPath useClasspath="true" />
      </profile>
      <profile default="false" name="Maven default annotation processors profile" enabled="true">
        <sourceOutputDir name="target/generated-sources/annotations" />
        <sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
        <outputRelativeToContentRoot value="true" />
        <processorPath useClasspath="true" />
        <module name="villetype" />
        <module name="villetype-stub" />
      </profile>
    </annotationProcessing>
    <bytecodeTargetLevel>
      <module name="villetype" target="1.6" />
      <module name="villetype-stub" target="1.6" />
    </bytecodeTargetLevel>
  </component>
</project>


text:
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import org.jspecify.annotations.NullnessUnspecified;

@NullMarked
class NullLiteralToTypeVariable<
    Never1T,
    ChildOfNever1T extends Never1T,
    UnspecChildOfNever1T extends @NullnessUnspecified Never1T,
    NullChildOfNever1T extends @Nullable Never1T,
    //
    Never2T extends Object,
    ChildOfNever2T extends Never2T,
    UnspecChildOfNever2T extends @NullnessUnspecified Never2T,
    NullChildOfNever2T extends @Nullable Never2T,
    //
    UnspecT extends @NullnessUnspecified Object,
    ChildOfUnspecT extends UnspecT,
    UnspecChildOfUnspecT extends @NullnessUnspecified UnspecT,
    NullChildOfUnspecT extends @Nullable UnspecT,
    //
    ParametricT extends @Nullable Object,
    ChildOfParametricT extends ParametricT,
    UnspecChildOfParametricT extends @NullnessUnspecified ParametricT,
    NullChildOfParametricT extends @Nullable ParametricT,
    //
    UnusedT> {
  Never1T x0() {
    // jspecify_nullness_mismatch
    return null;
  }

  ChildOfNever1T x1() {
    // jspecify_nullness_mismatch
    return null;
  }

  UnspecChildOfNever1T x2() {
    // jspecify_nullness_mismatch
    return null;
  }

  NullChildOfNever1T x3() {
    // jspecify_nullness_mismatch
    return null;
  }

  Never2T x4() {
    // jspecify_nullness_mismatch
    return null;
  }

  ChildOfNever2T x5() {
    // jspecify_nullness_mismatch
    return null;
  }

  UnspecChildOfNever2T x6() {
    // jspecify_nullness_mismatch
    return null;
  }

  NullChildOfNever2T x7() {
    // jspecify_nullness_mismatch
    return null;
  }

  UnspecT x8() {
    // jspecify_nullness_mismatch
    return null;
  }

  ChildOfUnspecT x9() {
    // jspecify_nullness_mismatch
    return null;
  }

  UnspecChildOfUnspecT x10() {
    // jspecify_nullness_mismatch
    return null;
  }

  NullChildOfUnspecT x11() {
    // jspecify_nullness_mismatch
    return null;
  }

  ParametricT x12() {
    // jspecify_nullness_mismatch
    return null;
  }

  ChildOfParametricT x13() {
    // jspecify_nullness_mismatch
    return null;
  }

  UnspecChildOfParametricT x14() {
    // jspecify_nullness_mismatch
    return null;
  }

  NullChildOfParametricT x15() {
    // jspecify_nullness_mismatch
    return null;
  }
}


text:
using System;
using System.Windows.Input;
using Mapsui.Nts.Extensions;
using Mapsui.Samples.Wpf.Editing.Editing;
using Mapsui.UI.Wpf;

namespace Mapsui.Samples.Wpf.Editing
{
    public enum MouseState
    {
        Down,
        Up,
        Dragging, // moving with mouse down
        Moving, // moving with mouse up
        DoubleClick
    }

    public class EditManipulation
    {
        private MPoint? _mouseDownPosition;
        private bool _inDoubleClick;

        public static int MinPixelsMovedForDrag { get; set; } = 4;

        public bool Manipulate(MouseState mouseState, MPoint screenPosition,
            EditManager editManager, MapControl mapControl)
        {
            switch (mouseState)
            {
                case MouseState.Up:
                    if (_inDoubleClick) // Workaround to prevent that after a double click the 'up' event will immediately add a new geometry.
                    {
                        _inDoubleClick = false;
                        return false;
                    }

                    if (editManager.EditMode == EditMode.Modify)
                        editManager.StopDragging();
                    if (editManager.EditMode == EditMode.Rotate)
                        editManager.StopRotating();
                    if (editManager.EditMode == EditMode.Scale)
                        editManager.StopScaling();

                    if (IsClick(screenPosition, _mouseDownPosition))
                    {
                        if (editManager.EditMode == EditMode.Modify)
                        {
                            if (IsShiftDown())
                            {
                                return editManager.TryDeleteCoordinate(
                                    mapControl.GetMapInfo(screenPosition, editManager.VertexRadius), editManager.VertexRadius);
                            }
                            return editManager.TryInsertCoordinate(
                                mapControl.GetMapInfo(screenPosition, editManager.VertexRadius));
                        }
                        return editManager.AddVertex(mapControl.Viewport.ScreenToWorld(screenPosition).ToCoordinate());
                    }
                    return false;
                case MouseState.Down:
                    {
                        _mouseDownPosition = screenPosition;
                        // Take into account VertexRadius in feature select, because the objective
                        // is to select the vertex.
                        var mapInfo = mapControl.GetMapInfo(screenPosition, editManager.VertexRadius);
                        if (editManager.EditMode == EditMode.Modify && mapInfo?.Feature != null)
                        {
                            return editManager.StartDragging(mapInfo, editManager.VertexRadius);
                        }
                        if (editManager.EditMode == EditMode.Rotate && mapInfo?.Feature != null)
                        {
                            return editManager.StartRotating(mapInfo);
                        }
                        if (editManager.EditMode == EditMode.Scale && mapInfo?.Feature != null)
                        {
                            return editManager.StartScaling(mapInfo);
                        }
                        return false;
                    }
                case MouseState.Dragging:
                    {
                        var args = mapControl.GetMapInfo(screenPosition);
                        if (editManager.EditMode == EditMode.Modify)
                            return editManager.Dragging(args?.WorldPosition?.ToPoint());
                        if (editManager.EditMode == EditMode.Rotate)
                            return editManager.Rotating(args?.WorldPosition?.ToPoint());
                        if (editManager.EditMode == EditMode.Scale)
                            return editManager.Scaling(args?.WorldPosition?.ToPoint());

                        return false;
                    }
                case MouseState.Moving:
                    editManager.HoveringVertex(mapControl.GetMapInfo(screenPosition));
                    return false;
                case MouseState.DoubleClick:
                    _inDoubleClick = true;
                    if (editManager.EditMode != EditMode.Modify)
                        return editManager.EndEdit();
                    return false;
                default:
                    throw new Exception();
            }
        }

        private static bool IsShiftDown()
        {
            return Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);
        }

        private static bool IsClick(MPoint? screenPosition, MPoint? mouseDownScreenPosition)
        {
            if (mouseDownScreenPosition == null || screenPosition == null)
                return false;
            return mouseDownScreenPosition.Distance(screenPosition) < MinPixelsMovedForDrag;
        }
    }
}


text:
package logreceiver.processor

import java.util.concurrent.TimeoutException

import akka.actor._
import akka.pattern.ask
import akka.util.Timeout
import com.github.vonnagy.service.container.health.{HealthInfo, HealthState, RegisteredHealthCheckActor}
import com.github.vonnagy.service.container.log.ActorLoggingAdapter

import scala.collection.JavaConversions._
import scala.concurrent.duration._
import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success}

object ProcessorManager {
  def props(): Props = Props[ProcessorManager]
}

class ProcessorManager extends Actor with RegisteredHealthCheckActor with ActorLoggingAdapter {

  import SupervisorStrategy._
  import context.dispatcher

  // TODO customize
  override val supervisorStrategy =
    OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1.minute) {
      case _: ActorInitializationException => Stop
      case _: IllegalArgumentException => Stop
      case _: IllegalStateException => Restart
      case _: TimeoutException => Escalate
      case _: Exception => Escalate
    }

  override def preStart() {
    log.info("Processor manager started: {}", context.self.path)
    startProcessors
  }

  override def postStop(): Unit = {
    context.children.foreach { c =>
      context.system.eventStream.unsubscribe(c, classOf[LogBatch])
      context.stop(c)
    }

    log.info("Processor manager stopped: {}", context.self.path)
  }

  override def receive = {
    case ProcessorReady =>
      // A processor is ready to go so add it to the stream
      context.system.eventStream.subscribe(sender, classOf[LogBatch])
  }

  /**
   * Load the defined processors
   */
  private def startProcessors: Seq[ActorRef] = {
    val master = context.system.settings.config.getConfig("log.processors")

    master.root().entrySet().flatMap { entry =>
      try {
        if (master.getConfig(entry.getKey).getBoolean("enabled")) {
          var config = master.getConfig(entry.getKey)
          var clazz = config.getString("class");

          val processor = context.actorOf(Props(Class.forName(clazz)), entry.getKey.toLowerCase)
          Some(processor)
        }
        else {
          None
        }

      } catch {
        case ex: Exception =>
          log.error(s"Log processor specified in config can't be loaded [${entry}]", ex);
          None
      }
    }.toSeq

  }

  /**
   * Fetch the health for this registered checker.
   *
   * @return returns a the health information
   */
  override def getHealth: Future[HealthInfo] = {

    if (context.children.isEmpty) {
      Future {
        HealthInfo("processors", HealthState.DEGRADED, s"There are no configured processors running")
      }
    }
    else {
      implicit val timeout = Timeout(2 seconds)
      val future = (Future.traverse(context.children)(x => x ? CheckHealth)).mapTo[Seq[HealthInfo]]

      val p = Promise[HealthInfo]()
      future.onComplete({
        case Failure(f) =>
          log.error("Error fetching health", f)
          p success HealthInfo("processors", HealthState.DEGRADED, s"We were unable to determine the health on the processors")
        case Success(answers) =>
          p.success(HealthInfo("processors", HealthState.OK,
            s"The following processors are currently running: ${context.children.map(_.path.name).mkString(", ")}",
            null, answers.toList))
      })

      p.future
    }

  }
}


text:
from classes import molecule

class Topology():

	molecules = []
	output_type = ""

	def __init__(self):
		self.molecules = []
		self.output_type = ""

	def addMolecule(self, molecule):
		self.molecules.append(molecule)

	def getMolecules(self):
		return self.molecules

	def getAtomTypes(self):
		atomtypes = []
		for molecule in self.molecules:
			for atom in molecule.getAtoms():
				if atom.getAtomType() not in atomtypes:
					atomtypes.append(atom.getAtomType())
		return atomtypes

	def setOutputType(self, output_type):
		self.output_type = output_type


text:
//
//  JSNetworkTool+JSExtension.h
//  Weibo_Object-C
//
//  Created by ShenYj on 2016/11/23.
//  Copyright © 2016年 ___ShenYJ___. All rights reserved.
//

#import "JSNetworkTool.h"

@interface JSNetworkTool (JSExtension)

/**
 获取Access Token

 @param code          调用authorize获得的code值
 @param finishedBlock 完成回调
 */
- (void)loadAccessTokenWithCode:(NSString *)code withFinishedBlock:(void (^)(id obj, NSError *error))finishedBlock;

/**
 获取用户信息

 @param userAccountModel 用户信息对象
 */
- (void)loadUserAccountInfo:(JSUserAccountModel *)userAccountModel withFinishedBlock:(void (^)(id obj, NSError *error))finishedBlock;

/**
 获取当前登录用户及其所关注(授权)用户的最新微博
 @param Since_id      下拉时指定此参数
 @param max_id        上拉时指定此参数
 @param finishedBlock 完成回调
 */
- (void)loadHomePublicDatawithFinishedBlock:(void (^)(id obj, NSError *error))finishedBlock Since_id:(NSInteger)since_id max_id:(NSInteger)max_id;

/**
 发布文字文博
 @param status        文字微博
 @param finishedBlock 完成回调
 */
- (void)composeStatus:(NSString *)status withFinishedBlock:(void (^)(id obj, NSError *error))finishedBlock;

/**
 发布文字&图片文博
 @param contents      文字&图片
 @param finishedBlock 完成回调
 */
- (void)composeStatusWithPictures:(NSDictionary *)contents withFinishedBlock:(void (^)(id obj, NSError *error))finishedBlock;

/** token 请求方法 */
- (void)loadHomeStatusCompeletionHandler:(void (^)(NSArray *datas ,BOOL isSuccess))compeletionHandler;

@end


text:
Mobile convolutional neural network for monocular depth estimation from a single RGB image.

<!-- asset-path: legacy -->
<!-- task: image-depth-estimation -->
<!-- network-architecture: midas -->
<!-- dataset: diml-indoor -->
<!-- dataset: megadepth -->
<!-- dataset: redweb -->
<!-- dataset: wsvd -->
<!-- dataset: 3dmovies -->
<!-- dataset: tartanair -->
<!-- dataset: hrwsi -->
<!-- dataset: apolloscape -->
<!-- dataset: blendedmvs -->
<!-- dataset: irs -->
<!-- fine-tunable: false  -->
<!-- format: hub -->
<!-- license: mit -->

## License
MIT License

## Qualitative Information

This MiDaS model is converted from the original version of the [MiDaS model](https://github.com/intel-isl/MiDaS).
MiDaS was first introduced by
Rene Ranftl, Katrin Lasinger, David Hafner, Konrad Schindler, Vladlen Koltun in the paper:
[Towards Robust Monocular Depth Estimation: Mixing Datasets for Zero-shot Cross-dataset Transfer](https://arxiv.org/abs/1907.01341).

#### Requirements

```
pip install tensorflow tensorflow-hub opencv-python matplotlib
```

* required nVidia GPU

#### Model Details
This module is based on a Pytorch version of MiDaS, which performs efficiently and with very high accuracy to compute depth from a single image.

* input: (uint8) RGB image with shape (3, 256, 256)
* output: (float32) inverse depth maps (1, 256, 256)

#### Example Use

```python
import cv2
import numpy as np
import urllib.request
import matplotlib.pyplot as plt

import tensorflow as tf
import tensorflow_hub as hub

url, filename = ("https://github.com/intel-isl/MiDaS/releases/download/v2/dog.jpg", "dog.jpg")
urllib.request.urlretrieve(url, filename)

# the runtime initialization will not allocate all memory on the device to avoid out of GPU memory
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
    #tf.config.experimental.set_memory_growth(gpu, True)
    tf.config.experimental.set_virtual_device_configuration(gpu,
    [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=4000)])

# input
img = cv2.imread('dog.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255.0

img_resized = tf.image.resize(img, [256,256], method='bicubic', preserve_aspect_ratio=False)
img_resized = tf.transpose(img_resized, [2, 0, 1])
img_input = img_resized.numpy()
reshape_img = img_input.reshape(1,3,256,256)
tensor = tf.convert_to_tensor(reshape_img, dtype=tf.float32)

# load model
module = hub.load("https://tfhub.dev/intel/midas/v2_1_small/1", tags=['serve'])
output = module.signatures['serving_default'](tensor)
prediction = output['default'].numpy()
prediction = prediction.reshape(256, 256)

# output file
prediction = cv2.resize(prediction, (img.shape[1], img.shape[0]), interpolation=cv2.INTER_CUBIC)
print(" Write image to: output.png")
depth_min = prediction.min()
depth_max = prediction.max()
img_out = (255 * (prediction - depth_min) / (depth_max - depth_min)).astype("uint8")

cv2.imwrite("output.png", img_out)
plt.imshow(img_out)
# plt.show()

```

**Source:** https://github.com/intel-isl/MiDaS


text:
package com.intellij.android.designer.model;

import com.android.tools.idea.rendering.RenderResult;
import com.android.tools.idea.rendering.RenderedImage;
import com.intellij.android.designer.AndroidDesignerEditor;
import com.intellij.android.designer.designSurface.AndroidDesignerEditorPanel;
import com.intellij.android.designer.designSurface.RootView;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * A test root view for rendering and parsing tests
 */
public class TestRootView extends RootView {

  private RenderedImage myImage;

  public static TestRootView getTestRootView(Project project, Module module, VirtualFile layoutFile, RenderResult result) {
    AndroidDesignerEditor throwawayEditor = new AndroidDesignerEditor(project, layoutFile);
    AndroidDesignerEditorPanel throwawayPanel = new AndroidDesignerEditorPanel(throwawayEditor, project, module, layoutFile);
    return new TestRootView(throwawayPanel, result);
  }

  private TestRootView(@NotNull AndroidDesignerEditorPanel panel, @NotNull RenderResult renderResult) {
    super(panel, 0, 0, renderResult);
  }

  @Nullable
  @Override
  public BufferedImage getImage() {
    return myImage.getOriginalImage();
  }

  @Override
  public void setRenderedImage(@Nullable RenderedImage image) {
    myImage = image;
  }

  @Nullable
  @Override
  public RenderedImage getRenderedImage() {
    return myImage;
  }

  @Override
  public void updateBounds(boolean imageChanged) {
    // TODO: do something here
  }

  @NotNull
  @Override
  public AndroidDesignerEditorPanel getPanel() {
    throw new RuntimeException("getPanel() is not supported by TestRootView");
  }

  @Override
  public boolean getShowDropShadow() {
    throw new RuntimeException("getShowDropShadow() is not supported by TestRootView");
  }

  @Override
  public void paintComponent(Graphics g) {
    throw new RuntimeException("paintComponent() is not supported by TestRootView");
  }

  @Override
  public void updateSize() {
    throw new RuntimeException("updateSize() is not supported by TestRootView");
  }

  @Override
  protected void paintImage(Graphics g) {
    throw new RuntimeException("paintImage() is not supported by TestRootView");
  }

  @Override
  public int getScaledWidth() {
    throw new RuntimeException("getScaledWidth() is not supported by TestRootView");
  }

  @Override
  public int getScaledHeight() {
    throw new RuntimeException("getScaledHeight() is not supported by TestRootView");
  }

  @Override
  public double getScale() {
    throw new RuntimeException("getScale() is not supported by TestRootView");
  }

  @Override
  public int getShiftX() {
    throw new RuntimeException("getShiftX() is not supported by TestRootView");
  }

  @Override
  public int getShiftY() {
    throw new RuntimeException("getShiftY() is not supported by TestRootView");
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/text1"
        android:text="Tìm Theo Ngày"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="30dp"
        ></TextView>
    <EditText
        android:id="@+id/edit1_1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="dd/mm/yyyy"
        ></EditText>
    <Button
        android:id="@+id/buttonok"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="OK"
        ></Button>

</LinearLayout>
<!-- From: file:/C:/Users/nguyencat/Desktop/nguyenassfinal/ParseStarterProject/src/main/res/layout/dialogdate.xml -->


text:
#include <Control.h>
#include <ScrollBar.h>
#include <UTF8.h>
#include <Window.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#include "iup.h"
#include "iupcbs.h"
#include "iupkey.h"

#include "iup_object.h"
#include "iup_childtree.h"
#include "iup_key.h"
#include "iup_str.h"
#include "iup_class.h"
#include "iup_attrib.h"
#include "iup_focus.h"
#include "iup_key.h"
#include "iup_image.h"
#include "iup_drv.h"

#include "iuphaiku_drv.h"

#define UNIMPLEMENTED printf("%s (%s %d) UNIMPLEMENTED\n",__func__,__FILE__,__LINE__);

void iupgtkUpdateMnemonic(Ihandle* ih)
{
	UNIMPLEMENTED
}

void iupdrvActivate(Ihandle* ih)
{
	UNIMPLEMENTED
}

void iupdrvReparent(Ihandle* ih)
{
	UNIMPLEMENTED
}

BView* viewFromHandler(BHandler* handler)
{
	BWindow* window = dynamic_cast<BWindow*>(handler);
	if (window)
	  return window->ChildAt(0); // Get background view
	else
   	  return dynamic_cast<BView*>(handler);
}

void iuphaikuBaseAddToParent(Ihandle* ih)
{
	BHandler* parent = (BHandler*)iupChildTreeGetNativeParentHandle(ih);
	BView* child = (BView*)ih->handle;

	BView* view = viewFromHandler(parent);
	if(view)
	  view->AddChild(child);
	else
	  debugger("Trying to add a control to a parent that has no BView");
}

void iupdrvBaseLayoutUpdateMethod(Ihandle *ih)
{
	BView* view = (BView*)ih->handle;
	view->MoveTo(ih->x, ih->y);
	view->ResizeTo(ih->currentwidth, ih->currentheight);
}

void iupdrvBaseUnMapMethod(Ihandle* ih)
{
  BHandler* handler = (BHandler*)ih->handle;
  BView* view = dynamic_cast<BView*>(handler);
  BWindow* window = dynamic_cast<BWindow*>(handler);
  if(view) {
	view->RemoveSelf();
    delete view;
  } else if(window) {
    window->Quit();
	// The window will delete itself
  } else if(handler != NULL)
    UNIMPLEMENTED
}

void iupdrvPostRedraw(Ihandle *ih)
{
	UNIMPLEMENTED
}

void iupdrvRedrawNow(Ihandle *ih)
{
	UNIMPLEMENTED
}

void iupdrvScreenToClient(Ihandle* ih, int *x, int *y)
{
	UNIMPLEMENTED
}

void iupdrvClientToScreen(Ihandle* ih, int *x, int *y)
{
	UNIMPLEMENTED
}

int iupdrvBaseSetZorderAttrib(Ihandle* ih, const char* value)
{
	UNIMPLEMENTED
	return 0;
}

void iupdrvSetVisible(Ihandle* ih, int visible)
{
  BView* view = (BView*)ih->handle;
  if(visible && view->IsHidden())
    view->Show();
  else if(!visible && !view->IsHidden())
	view->Hide();
}

int iupdrvIsVisible(Ihandle* ih)
{
  BView* view = (BView*)ih->handle;
  return !view->IsHidden();
}

int iupdrvIsActive(Ihandle *ih)
{
	BHandler* handler = (BHandler*)ih->handle;

	BControl* control = dynamic_cast<BControl*>(handler);
	if (control && !control->IsEnabled())
	  return false;
	return true;
}

void iupdrvSetActive(Ihandle* ih, int enable)
{
	BHandler* handler = (BHandler*)ih->handle;

	BView* view = dynamic_cast<BView*>(handler);
	BWindow* window = dynamic_cast<BWindow*>(handler);
	if (view)
	  view->MakeFocus(enable);
	if (window)
	  window->Activate(enable);
}

void iuphaikuBaseSetBgColor(InativeHandle* handle, unsigned char r, unsigned char g, unsigned char b)
{
  BView* view = viewFromHandler((BHandler*)handle);

  view->SetLowColor(r,g,b);
  view->SetViewColor(r,g,b);
}

void iuphaikuBaseSetFgColor(InativeHandle* handle, unsigned char r, unsigned char g, unsigned char b)
{
  BView* view = viewFromHandler((BHandler*)handle);

  view->SetHighColor(r,g,b);
}

int iupdrvBaseSetBgColorAttrib(Ihandle* ih, const char* value)
{
  unsigned char r, g, b;
  if (!iupStrToRGB(value, &r, &g, &b))
    return 0;

  iuphaikuBaseSetBgColor(ih->handle, r, g, b);

  /* DO NOT NEED TO UPDATE GTK IMAGES SINCE THEY DO NOT DEPEND ON BGCOLOR */

  return 1;
}

int iupdrvBaseSetFgColorAttrib(Ihandle* ih, const char* value)
{
  unsigned char r, g, b;
  if (!iupStrToRGB(value, &r, &g, &b))
    return 0;

  iuphaikuBaseSetFgColor(ih->handle, r, g, b);

  return 1;
}

int iupdrvBaseSetCursorAttrib(Ihandle* ih, const char* value)
{
	UNIMPLEMENTED
  return 0;
}

int iupdrvGetScrollbarSize(void)
{
  return (int)B_V_SCROLL_BAR_WIDTH;
}

void iupdrvDrawFocusRect(Ihandle* ih, void* _gc, int x, int y, int w, int h)
{
	UNIMPLEMENTED
}

void iupdrvBaseRegisterCommonAttrib(Iclass* ic)
{
  // Other drivers seems to register some info about fonts and tooltips here.
  // I'm not sure what is needed and there is no documentation...
  iupClassRegisterAttribute(ic, "TIPMARKUP", NULL, NULL, IUPAF_SAMEASSYSTEM, NULL, IUPAF_NOT_MAPPED);
  iupClassRegisterAttribute(ic, "TIPICON", NULL, NULL, IUPAF_SAMEASSYSTEM, NULL, IUPAF_NOT_MAPPED);
}

void iupgtkReleaseConvertUTF8(void)
{
	UNIMPLEMENTED
}

char* iuphaikuStrConvertToUTF8(const char* str)  /* From IUP to GTK */
{
  if (!str || *str == 0)
    return (char*)str;

  if (iupgtk_utf8autoconvert)  /* this means str is in current locale */
  {
    static char* buffer = NULL;
    int32 len = strlen(str);
	int32 len2 = 2 * len;
	int32 cookie;
	free(buffer);
	buffer = (char*)malloc(len * 2); // Should be enough in most cases ?
    convert_to_utf8(B_ISO9_CONVERSION, str, &len, buffer, &len2, &cookie);
    return buffer;
  }

  return (char*)str;
}

char* iuphaikuStrConvertFromUTF8(const char* str)  /* From GTK to IUP */
{
  if (!str || *str == 0)
    return (char*)str;

  if (iupgtk_utf8autoconvert)  /* this means str is in current locale */
  {
    static char* buffer = NULL;
    int32 len = strlen(str);
	int32 len2 = 2 * len;
	int32 cookie;
	free(buffer);
	buffer = (char*)malloc(len * 2); // Should be enough in most cases ?
    convert_from_utf8(B_ISO9_CONVERSION, str, &len, buffer, &len2, &cookie);
    return buffer;
  }

  return (char*)str;
}

char* iupgtkStrConvertFromFilename(const char* str)   /* From Filename to IUP */
{
	UNIMPLEMENTED
  return (char*)str;
}

void iupdrvSendKey(int key, int press)
{
	UNIMPLEMENTED
}

void iupdrvWarpPointer(int x, int y)
{
	UNIMPLEMENTED
}

void iupdrvSendMouse(int x, int y, int bt, int status)
{
	UNIMPLEMENTED
}

void iupdrvSleep(int time)
{
	UNIMPLEMENTED
}


text:
from __future__ import absolute_import, print_function
import confluent_kafka
import functools
import unittest

from mock import patch, PropertyMock, ANY

import os
import sys
import time

log = None

test_path = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
sync_lib_dir = os.path.join(test_path, "..", "xossynchronizer")
xos_dir = os.path.join(test_path, "..", "..", "..", "xos")

print(os.getcwd())

def config_get_mock(orig, overrides, key):
    if key in overrides:
        return overrides[key]
    else:
        return orig(key)

class FakeKafkaConsumer:
    def __init__(self, values=[]):
        self.values = values

    def subscribe(self, topics):
        pass

    def poll(self, timeout=1.0):
        if self.values:
            return FakeKafkaMessage(self.values.pop())
        # block forever
        time.sleep(1000)

class FakeKafkaMessage:
    """ Works like Message in confluent_kafka
        https://docs.confluent.io/current/clients/confluent-kafka-python/#message
    """

    def __init__(
        self,
        timestamp=None,
        topic="faketopic",
        key="fakekey",
        value="fakevalue",
        error=False,
    ):

        if timestamp is None:
            self.fake_ts_type = confluent_kafka.TIMESTAMP_NOT_AVAILABLE
            self.fake_timestamp = None
        else:
            self.fake_ts_type = confluent_kafka.TIMESTAMP_CREATE_TIME
            self.fake_timestamp = timestamp

        self.fake_topic = topic
        self.fake_key = key
        self.fake_value = value
        self.fake_error = error

    def error(self):
        return self.fake_error

    def timestamp(self):
        return (self.fake_ts_type, self.fake_timestamp)

    def topic(self):
        return self.fake_topic

    def key(self):
        return self.fake_key

    def value(self):
        return self.fake_value

class TestEventEngine(unittest.TestCase):
    @classmethod
    def setUpClass(cls):

        global log

        config = os.path.join(test_path, "test_config.yaml")
        from xosconfig import Config

        Config.clear()
        Config.init(config, "synchronizer-config-schema.yaml")

        if not log:
            from multistructlog import create_logger

            log = create_logger(Config().get("logging"))

    def setUp(self):
        global XOSKafkaThread, Config, log

        self.sys_path_save = sys.path
        self.cwd_save = os.getcwd()

        config = os.path.join(test_path, "test_config.yaml")
        from xosconfig import Config

        Config.clear()
        Config.init(config, "synchronizer-config-schema.yaml")

        from xossynchronizer.mock_modelaccessor_build import (
            build_mock_modelaccessor,
        )

        build_mock_modelaccessor(sync_lib_dir, xos_dir, services_dir=None, service_xprotos=[])

        from xossynchronizer.modelaccessor import model_accessor

        # The test config.yaml references files in `xos-synchronizer-tests/` so make sure we're in the parent
        # directory of the test directory.
        os.chdir(os.path.join(test_path, ".."))

        from xossynchronizer.event_engine import XOSKafkaThread, XOSEventEngine

        self.event_steps_dir = Config.get("event_steps_dir")
        self.event_engine = XOSEventEngine(model_accessor=model_accessor, log=log)

    def tearDown(self):
        sys.path = self.sys_path_save
        os.chdir(self.cwd_save)

    def test_load_event_step_modules(self):
        self.event_engine.load_event_step_modules(self.event_steps_dir)
        self.assertEqual(len(self.event_engine.event_steps), 1)

    def test_start(self):
        self.event_engine.load_event_step_modules(self.event_steps_dir)

        with patch.object(
            XOSKafkaThread, "create_kafka_consumer"
        ) as create_kafka_consumer, patch.object(
            FakeKafkaConsumer, "subscribe"
        ) as fake_subscribe, patch.object(
            self.event_engine.event_steps[0], "process_event"
        ) as process_event:

            create_kafka_consumer.return_value = FakeKafkaConsumer(
                values=["sampleevent"]
            )
            self.event_engine.start()

            self.assertEqual(len(self.event_engine.threads), 1)

            # Since event_engine.start() launches threads, give them a hundred milliseconds to do something...
            time.sleep(0.1)

            # We should have subscribed to the fake consumer
            fake_subscribe.assert_called_once()

            # The fake consumer will have returned one event
            process_event.assert_called_once()

    def test_start_with_pattern(self):
        self.event_engine.load_event_step_modules(self.event_steps_dir)

        with patch.object(
            XOSKafkaThread, "create_kafka_consumer"
        ) as create_kafka_consumer, patch.object(
            FakeKafkaConsumer, "subscribe"
        ) as fake_subscribe, patch.object(
            self.event_engine.event_steps[0], "process_event"
        ) as process_event, patch.object(
            self.event_engine.event_steps[0], "pattern", new_callable=PropertyMock
        ) as pattern, patch.object(
            self.event_engine.event_steps[0], "topics", new_callable=PropertyMock
        ) as topics:

            pattern.return_value = "somepattern"
            topics.return_value = []

            create_kafka_consumer.return_value = FakeKafkaConsumer(
                values=["sampleevent"]
            )
            self.event_engine.start()

            self.assertEqual(len(self.event_engine.threads), 1)

            # Since event_engine.start() launches threads, give them a hundred milliseconds to do something...
            time.sleep(0.1)

            # We should have subscribed to the fake consumer
            fake_subscribe.assert_called_with("somepattern")

            # The fake consumer will have returned one event
            process_event.assert_called_once()

    def test_start_bad_tech(self):
        """ Set an unknown Technology in the event_step. XOSEventEngine.start() should print an error message and
            not create any threads.
        """

        self.event_engine.load_event_step_modules(self.event_steps_dir)

        with patch.object(
            XOSKafkaThread, "create_kafka_consumer"
        ) as create_kafka_consumer, patch.object(
            log, "error"
        ) as log_error, patch.object(
            self.event_engine.event_steps[0], "technology"
        ) as technology:
            technology.return_value = "not_kafka"
            create_kafka_consumer.return_value = FakeKafkaConsumer()
            self.event_engine.start()

            self.assertEqual(len(self.event_engine.threads), 0)

            log_error.assert_called_with(
                "Unknown technology. Skipping step",
                step="TestEventStep",
                technology=ANY,
            )

    def test_start_bad_no_topics(self):
        """ Set no topics in the event_step. XOSEventEngine.start() will launch a thread, but the thread will fail
            with an exception before calling subscribe.
        """

        self.event_engine.load_event_step_modules(self.event_steps_dir)

        with patch.object(
            XOSKafkaThread, "create_kafka_consumer"
        ) as create_kafka_consumer, patch.object(
            FakeKafkaConsumer, "subscribe"
        ) as fake_subscribe, patch.object(
            self.event_engine.event_steps[0], "topics", new_callable=PropertyMock
        ) as topics:
            topics.return_value = []
            create_kafka_consumer.return_value = FakeKafkaConsumer()
            self.event_engine.start()

            # the thread does get launched, but it will fail with an exception
            self.assertEqual(len(self.event_engine.threads), 1)

            time.sleep(0.1)

            fake_subscribe.assert_not_called()

    def test_start_bad_topics_and_pattern(self):
        """ Set no topics in the event_step. XOSEventEngine.start() will launch a thread, but the thread will fail
            with an exception before calling subscribe.
        """

        self.event_engine.load_event_step_modules(self.event_steps_dir)

        with patch.object(
            XOSKafkaThread, "create_kafka_consumer"
        ) as create_kafka_consumer, patch.object(
            FakeKafkaConsumer, "subscribe"
        ) as fake_subscribe, patch.object(
            self.event_engine.event_steps[0], "pattern", new_callable=PropertyMock
        ) as pattern:
            pattern.return_value = "foo"
            create_kafka_consumer.return_value = FakeKafkaConsumer()
            self.event_engine.start()

            # the thread does get launched, but it will fail with an exception
            self.assertEqual(len(self.event_engine.threads), 1)

            time.sleep(0.1)

            fake_subscribe.assert_not_called()

    def test_start_config_no_eventbus_kind(self):
        """ Set a blank event_bus.kind in Config. XOSEventEngine.start() should print an error message and
            not create any threads.
        """

        self.event_engine.load_event_step_modules(self.event_steps_dir)

        config_get_orig = Config.get
        with patch.object(
            XOSKafkaThread, "create_kafka_consumer"
        ) as create_kafka_consumer, patch.object(
            log, "error"
        ) as log_error, patch.object(
            Config,
            "get",
            new=functools.partial(
                config_get_mock, config_get_orig, {"event_bus.kind": None}
            ),
        ):

            create_kafka_consumer.return_value = FakeKafkaConsumer()
            self.event_engine.start()

            self.assertEqual(len(self.event_engine.threads), 0)

            log_error.assert_called_with(
                "Eventbus kind is not configured in synchronizer config file."
            )

    def test_start_config_bad_eventbus_kind(self):
        """ Set an unknown event_bus.kind in Config. XOSEventEngine.start() should print an error message and
            not create any threads.
        """

        self.event_engine.load_event_step_modules(self.event_steps_dir)

        config_get_orig = Config.get
        with patch.object(
            XOSKafkaThread, "create_kafka_consumer"
        ) as create_kafka_consumer, patch.object(
            log, "error"
        ) as log_error, patch.object(
            Config,
            "get",
            new=functools.partial(
                config_get_mock, config_get_orig, {"event_bus.kind": "not_kafka"}
            ),
        ):
            create_kafka_consumer.return_value = FakeKafkaConsumer()
            self.event_engine.start()

            self.assertEqual(len(self.event_engine.threads), 0)

            log_error.assert_called_with(
                "Eventbus kind is set to a technology we do not implement.",
                eventbus_kind="not_kafka",
            )

if __name__ == "__main__":
    unittest.main()


text:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

using Khronos;

// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer

namespace OpenGL
{
	public partial class Gl
	{
		/// <summary>
		/// [GL] Value of GL_SLICE_ACCUM_SUN symbol.
		/// </summary>
		[RequiredByFeature("GL_SUN_slice_accum")]
		public const int SLICE_ACCUM_SUN = 0x85CC;

	}

}


text:
import libtorrent as lt
import time
import types
import sys
from subprocess import *
import thread
import shutil
import tempfile
import os.path as pt
from time import sleep
from BeautifulSoup import BeautifulSoup
import requests
class Torrent_Cosmos:
     def __init__(self):
         self.cache={}
         self.completed=False
         self.ses=None
         self.h=None
         self.piecestart=None
         self.pieceend=None
         self.offset1=None
         self.offset2=None
         self.piecesperite=None
         self.outputcmd=None
         self.torrents=[]
         #self.cur_selected=None

     def searchForCosmos(self):
         r= requests.get('https://thepiratebay.se/search/cosmos%20space%20time%20odyssey/0/7/200')
         soup = BeautifulSoup(r.content)
         table = soup.find(lambda tag: tag.name=='table' and tag.has_key('id') and tag['id']=="searchResult")
         rows = table.findAll(lambda tag: tag.name=='tr' and not tag.has_key('class')  )
         self.torrents=[]
         i=0
         for tr in rows:
             ithItem=tr.findChildren('td')
             seeders=ithItem[2].getText()
             leechers=ithItem[3].getText()
             name=ithItem[1].findAll('a')[0].getText()
             magnet=ithItem[1].findAll('a')[1]['href']
             torrent=ithItem[1].findAll('a')[0]['href']
             self.torrents.append({'s':seeders,'l':leechers, 'name':name,'magnet':magnet,'torrent':torrent})
             print "%d seeders:%s, leechers:%s, name:%s "%(i,leechers, seeders,name)
             i+=1

     def selectItemAndPlay(self, ith):
         selected=self.torrents[ith]
         print 'loading magnet', selected['magnet']
         self.start(selected['magnet'],0,'/tmp','mplayer -fs -')
         #self.start(selected['magnet'],0,'/tmp','vlc -f -')

     def magnet2torrent(self,magnet, output_name=None):
        if output_name and \
                not pt.isdir(output_name) and \
                not pt.isdir(pt.dirname(pt.abspath(output_name))):
            print("Invalid output folder: " + pt.dirname(pt.abspath(output_name)))
            print("")
            sys.exit(0)

        tempdir = tempfile.mkdtemp()
        ses = lt.session()
        params = {
            'save_path': tempdir,
            'duplicate_is_error': True,
            'storage_mode': lt.storage_mode_t(2),
            'paused': False,
            'auto_managed': True,
            'duplicate_is_error': True
        }
        handle = lt.add_magnet_uri(ses, magnet, params)

        print("Downloading Metadata (this may take a while)")
        while (not handle.has_metadata()):
            try:
                sleep(1)
            except KeyboardInterrupt:
                print("Aborting...")
                ses.pause()
                print("Cleanup dir " + tempdir)
                shutil.rmtree(tempdir)
                sys.exit(0)
        ses.pause()
        print("Done")

        torinfo = handle.get_torrent_info()
        torfile = lt.create_torrent(torinfo)

        output = pt.abspath(torinfo.name() + ".torrent")

        if output_name:
            if pt.isdir(output_name):
                output = pt.abspath(pt.join(
                    output_name, torinfo.name() + ".torrent"))
            elif pt.isdir(pt.dirname(pt.abspath(output_name))):
                output = pt.abspath(output_name)

        print("Saving torrent file here : " + output + " ...")
        torcontent = lt.bencode(torfile.generate())
        f = open(output, "wb")
        f.write(lt.bencode(torfile.generate()))
        f.close()
        print("Saved! Cleaning up dir: " + tempdir)
        ses.remove_torrent(handle)
        shutil.rmtree(tempdir)

        return output
     def printstatus(self):
            state_str = ['queued', 'checking', 'downloading metadata', 'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume']
            s = self.h.status()
            print >> sys.stderr,'%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s\n' % (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, s.num_peers, state_str[s.state]),
            #if s.state == 4:
            #       break
            sys.stdout.flush()
            l = ''
            i = 0
            for p in s.pieces:
                    if i >= self.piecestart and i <= self.pieceend:
                            if p == True:
                                    l = l + '1'
                            if p == False:
                                    l = l + '0'
                    i = i+1
            print >> sys.stderr,l

     def addnewpieces(self):
            prio = self.h.piece_priorities()
            s = self.h.status()
            downloading = 0
            if len(s.pieces) == 0:
                    return
            for piece in range(self.piecestart,self.pieceend+1):
                    if prio[piece] != 0 and s.pieces[piece]==False:
                            downloading = downloading+1
            for piece in range(self.piecestart,self.pieceend+1):
                    if prio[piece] == 0 and downloading < self.piecesperite:
                            print >> sys.stderr,'downloading piece ',piece
                            self.h.piece_priority(piece,1)
                            downloading = downloading+1
            for piece in range(self.piecestart,self.pieceend+1):
                    if prio[piece] != 0 and s.pieces[piece]==False:
                            print >> sys.stderr,'high prio ',piece
                            self.h.piece_priority(piece,7)
                            break

     def getpiece(self,i):
            #global cache
            if i in self.cache:
                    ret = self.cache[i]
                    self.cache[i] = 0
                    return ret
            while True:
                    s = self.h.status()
                    if len(s.pieces)==0:
                            break
                    if s.pieces[i]==True:
                            break
                    time.sleep(.1)
            self.h.read_piece(i)
            while True:
                    #printstatus()
                    #addnewpieces()
                    piece = self.ses.pop_alert()
                    if isinstance(piece, lt.read_piece_alert):
                            if piece.piece == i:
                                    #sys.stdout.write(piece.buffer)
                                    return piece.buffer
                            else:
                                    print >> sys.stderr,'store somewhere'
                                    self.cache[piece.piece] = piece.buffer
                            break
                    time.sleep(.1)

     def writethread(self):
            stream = 0
            print "state"
            for piece in range(self.piecestart,self.pieceend+1):
                    buf=self.getpiece(piece)
                    if piece==self.piecestart:
                            buf = buf[self.offset1:]
                    if piece==self.pieceend:
                            buf = buf[:self.offset2]
                    print >> sys.stderr, 'output',piece,len(buf)
                    if self.outputcmd=='-':
                            stream = sys.stdout
                    else:
                            if stream == 0:
                                    stream = Popen(self.outputcmd.split(' '), stdin=PIPE).stdin
                    try:
                            stream.write(buf)
                    except Exception, err:
                            print err
                            self.ses.remove_torrent(self.h)
                            self.completed = True
                            exit(0)
                    time.sleep(.1)
            self.ses.remove_torrent(self.h)
            self.completed = True

     def start(self,magnet,fileid,outdir,_outputcmd):
            self.outputcmd=_outputcmd
            torrent=self.magnet2torrent(magnet)
            info = lt.torrent_info(torrent)
            #self.ses = lt.session()
            print torrent, outdir, self.ses,fileid,self.outputcmd

            #cur_t_handle=self.ses.add_torrent({'url':torrent, 'save_path':outdir})
            #print cur_t_handle
            #info=cur_t_handle.get_torrent_info()
            self.piecesperite = 40*1024*1024/info.piece_length() # 40 MB
            print >> sys.stderr, 'piecesperite',self.piecesperite
            print >> sys.stderr, 'info.piece_length()',info.piece_length()
            sizes = []
            i = 0
            for f in info.files():
                    self.piecestart = f.offset/info.piece_length()
                    self.pieceend = (f.offset+f.size)/info.piece_length()
                    sizes.append(f.size)
                    print >> sys.stderr, i,f.path,f.size,f.offset,self.piecestart,self.pieceend
                    i=i+1
            if fileid == 'list':
                    return
            if fileid == 'max':
                    fileid = sizes.index(max(sizes))
            else:
                    fileid = int(fileid)

            f = info.files()[fileid]
            print >> sys.stderr, f.path
            self.piecestart = f.offset/info.piece_length()
            self.pieceend = (f.offset+f.size)/info.piece_length()
            self.offset1 = f.offset%info.piece_length() #how many bytes need to be removed from the 1st piece
            self.offset2 = ((f.offset+f.size)%info.piece_length()) #how many bytes need we keep from the last piece
            print >> sys.stderr,self.piecestart,self.pieceend,self.offset1,self.offset2,info.piece_length()
            print >> sys.stderr,(self.pieceend-self.piecestart+1)*info.piece_length()-(self.offset1+self.offset2),f.size
            self.ses = lt.session()

            state = None
            #state = lt.bdecode(open(state_file, "rb").read())
            self.ses.start_dht(state)
            self.ses.add_dht_router("router.bittorrent.com", 6881)
            self.ses.add_dht_router("router.utorrent.com", 6881)
            self.ses.add_dht_router("router.bitcomet.com", 6881)

            self.ses.listen_on(6881, 6891)
            self.ses.set_alert_mask(lt.alert.category_t.storage_notification)
            self.h = self.ses.add_torrent({'ti': info, 'save_path': outdir})
            for i in range(info.num_pieces()):
                    self.h.piece_priority(i,0)
            print >> sys.stderr,'starting', self.h.name()
            for i in range(self.piecestart,self.piecestart+self.piecesperite):
                if i <= self.pieceend:
                    self.h.piece_priority(i,7)
                    print >> sys.stderr,'downloading piece '+str(i)
            thread.start_new_thread(self.writethread,())
            while not self.completed:
                    self.printstatus()
                    self.addnewpieces()
                    time.sleep(1)


text:
namespace
{
enum State
{
  EParseTypes,
  EParseLanguages
};

}  // unnamed namespace

// static
size_t const CategoriesHolder::kNumLanguages = 30;
size_t const CategoriesHolder::kEnglishCode = 1;

CategoriesHolder::CategoriesHolder(unique_ptr<Reader> && reader)
{
  ReaderStreamBuf buffer(move(reader));
  istream s(&buffer);
  LoadFromStream(s);
}

void CategoriesHolder::AddCategory(Category & cat, vector<uint32_t> & types)
{
  if (!cat.m_synonyms.empty() && !types.empty())
  {
    shared_ptr<Category> p(new Category());
    p->Swap(cat);

    for (size_t i = 0; i < types.size(); ++i)
      m_type2cat.insert(make_pair(types[i], p));

    for (size_t i = 0; i < p->m_synonyms.size(); ++i)
    {
      ASSERT(p->m_synonyms[i].m_locale != kUnsupportedLocaleCode, ());

      StringT const uniName = search::NormalizeAndSimplifyString(p->m_synonyms[i].m_name);

      vector<StringT> tokens;
      SplitUniString(uniName, MakeBackInsertFunctor(tokens), search::Delimiters());

      for (size_t j = 0; j < tokens.size(); ++j)
        for (size_t k = 0; k < types.size(); ++k)
          if (ValidKeyToken(tokens[j]))
            m_name2type.insert(
                make_pair(make_pair(p->m_synonyms[i].m_locale, tokens[j]), types[k]));
    }
  }

  cat.m_synonyms.clear();
  types.clear();
}

bool CategoriesHolder::ValidKeyToken(StringT const & s)
{
  if (s.size() > 2)
    return true;

  /// @todo We need to have global stop words array for the most used languages.
  for (char const * token : {"a", "z", "s", "d", "di", "de", "le", "wi", "fi", "ra", "ao"})
    if (s.IsEqualAscii(token))
      return false;

  return true;
}

void CategoriesHolder::LoadFromStream(istream & s)
{
  m_type2cat.clear();
  m_name2type.clear();

  State state = EParseTypes;
  string line;

  Category cat;
  vector<uint32_t> types;
  vector<string> currentGroups;
  multimap<string, Category::Name> groupTranslations;

  Classificator const & c = classif();

  int lineNumber = 0;
  while (s.good())
  {
    ++lineNumber;
    getline(s, line);
    strings::Trim(line);
    // Allow for comments starting with '#' character.
    if (!line.empty() && line[0] == '#')
      continue;

    strings::SimpleTokenizer iter(line, state == EParseTypes ? "|" : ":|");

    switch (state)
    {
    case EParseTypes:
    {
      AddCategory(cat, types);
      currentGroups.clear();

      while (iter)
      {
        // Check if category is a group reference.
        if ((*iter)[0] == '@')
        {
          CHECK((currentGroups.empty() || !types.empty()),
                ("Two groups in a group definition at line", lineNumber));
          currentGroups.push_back(*iter);
        }
        else
        {
          // Split category to subcategories for classificator.
          vector<string> v;
          strings::Tokenize(*iter, "-", MakeBackInsertFunctor(v));

          // Get classificator type.
          uint32_t const type = c.GetTypeByPathSafe(v);
          if (type != 0)
            types.push_back(type);
          else
            LOG(LWARNING, ("Invalid type:", v, "at line:", lineNumber));
        }

        ++iter;
      }

      if (!types.empty() || currentGroups.size() == 1)
        state = EParseLanguages;
    }
    break;

    case EParseLanguages:
    {
      if (!iter)
      {
        // If the category groups are specified, add translations from them.

        ///@todo According to the current logic, categories.txt should have
        /// the blank string at the end of file.
        if (!types.empty())
        {
          for (string const & group : currentGroups)
          {
            auto trans = groupTranslations.equal_range(group);
            for (auto it = trans.first; it != trans.second; ++it)
              cat.m_synonyms.push_back(it->second);
          }
        }

        state = EParseTypes;
        continue;
      }

      int8_t const langCode = MapLocaleToInteger(*iter);
      CHECK(langCode != kUnsupportedLocaleCode,
            ("Invalid language code:", *iter, "at line:", lineNumber));

      while (++iter)
      {
        Category::Name name;
        name.m_locale = langCode;
        name.m_name = *iter;

        if (name.m_name.empty())
        {
          LOG(LWARNING, ("Empty category name at line:", lineNumber));
          continue;
        }

        if (name.m_name[0] >= '0' && name.m_name[0] <= '9')
        {
          name.m_prefixLengthToSuggest = name.m_name[0] - '0';
          name.m_name = name.m_name.substr(1);
        }
        else
          name.m_prefixLengthToSuggest = Category::kEmptyPrefixLength;

        // Process emoji symbols.
        using namespace strings;
        if (StartsWith(name.m_name, "U+"))
        {
          auto const code = name.m_name;
          int c;
          if (!to_int(name.m_name.c_str() + 2, c, 16))
          {
            LOG(LWARNING, ("Bad emoji code:", code));
            continue;
          }

          name.m_name = ToUtf8(UniString(1, static_cast<UniChar>(c)));

          if (IsASCIIString(ToUtf8(search::NormalizeAndSimplifyString(name.m_name))))
          {
            LOG(LWARNING, ("Bad emoji code:", code));
            continue;
          }
        }

        if (currentGroups.size() == 1 && types.empty())
        {
          // Not a translation, but a category group definition
          groupTranslations.emplace(currentGroups[0], name);
        }
        else
          cat.m_synonyms.push_back(name);
      }
    }
    break;
    }
  }

  // add last category
  AddCategory(cat, types);
}

bool CategoriesHolder::GetNameByType(uint32_t type, int8_t locale, string & name) const
{
  pair<IteratorT, IteratorT> const range = m_type2cat.equal_range(type);

  for (IteratorT i = range.first; i != range.second; ++i)
  {
    Category const & cat = *i->second;
    for (size_t j = 0; j < cat.m_synonyms.size(); ++j)
      if (cat.m_synonyms[j].m_locale == locale)
      {
        name = cat.m_synonyms[j].m_name;
        return true;
      }
  }

  if (range.first != range.second)
  {
    name = range.first->second->m_synonyms[0].m_name;
    return true;
  }

  return false;
}

string CategoriesHolder::GetReadableFeatureType(uint32_t type, int8_t locale) const
{
  ASSERT_NOT_EQUAL(type, 0, ());
  uint8_t level = ftype::GetLevel(type);
  ASSERT_GREATER(level, 0, ());

  uint32_t originalType = type;
  string name;
  while (true)
  {
    if (GetNameByType(type, locale, name))
      return name;

    if (--level == 0)
      break;

    ftype::TruncValue(type, level);
  }

  return classif().GetReadableObjectName(originalType);
}

bool CategoriesHolder::IsTypeExist(uint32_t type) const
{
  pair<IteratorT, IteratorT> const range = m_type2cat.equal_range(type);
  return range.first != range.second;
}

int8_t CategoriesHolder::MapLocaleToInteger(string const & locale)
{
  struct Mapping
  {
    char const * m_name;
    int8_t m_code;
  };
  // TODO(AlexZ): These constants should be updated when adding new
  // translation into categories.txt
  static const Mapping mapping[] = {
      {"en", 1},  {"ru", 2},  {"uk", 3},  {"de", 4},  {"fr", 5},       {"it", 6},
      {"es", 7},  {"ko", 8},  {"ja", 9},  {"cs", 10}, {"nl", 11},      {"zh-Hant", 12},
      {"pl", 13}, {"pt", 14}, {"hu", 15}, {"th", 16}, {"zh-Hans", 17}, {"ar", 18},
      {"da", 19}, {"tr", 20}, {"sk", 21}, {"sv", 22}, {"vi", 23},      {"id", 24},
      {"ro", 25}, {"nb", 26}, {"fi", 27}, {"el", 28}, {"he", 29},      {"sw", 30}};
  static_assert(ARRAY_SIZE(mapping) == kNumLanguages, "");
  static_assert(CategoriesHolder::kEnglishCode == 1, "");
  ASSERT_EQUAL(string(mapping[0].m_name), "en", ());
  ASSERT_EQUAL(mapping[0].m_code, CategoriesHolder::kEnglishCode, ());
  for (size_t i = 0; i < kNumLanguages; ++i)
  {
    if (locale.find(mapping[i].m_name) == 0)
      return mapping[i].m_code;
  }

  // Special cases for different Chinese variations
  if (locale.find("zh") == 0)
  {
    string lower = locale;
    strings::AsciiToLower(lower);

    for (char const * s : {"hant", "tw", "hk", "mo"})
      if (lower.find(s) != string::npos)
        return 12;  // Traditional Chinese

    return 17;  // Simplified Chinese by default for all other cases
  }

  return kUnsupportedLocaleCode;
}


text:
<resources>
    <string name="app_name">
        fermat-dmp-android-wallet-runtime-argentina-multi-account-wallet-bitdubai
    </string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
</resources>


text:
require 'minitest_helper'

class TestSubscriptionRequestProcessor < MiniTest::Test
  include Zulu

  def teardown
    Zulu.redis.flushall
  end

  def test_it_processes_request
    processor = SubscriptionRequestProcessor.new

    request_mock = MiniTest::Mock.new
    request_mock.expect(:process, true)

    SubscriptionRequest.stub(:pop, request_mock) do
      processor.stub(:reprocess, true) do
        processor.process
      end
    end

    request_mock.verify
  end
end


text:
/**
 *
 */
/**
 * @author dennis
 *
 */
module mmlib4j {
	exports mmlib4j.gui;
	exports mmlib4j.representation.tree.componentTree;
	exports mmlib4j.filtering.binary;
	exports mmlib4j.representation.tree;
	exports mmlib4j.descriptors;
	exports mmlib4j.representation.graph;
	exports mmlib4j.representation.tree.tos;
	exports mmlib4j.filtering;
	exports mmlib4j.images.impl;
	exports mmlib4j.representation.graph.rag;
	exports mmlib4j.representation.graph.pixels;
	exports mmlib4j.utils;
	exports mmlib4j.datastruct;
	exports mmlib4j.representation.tree.attribute;
	exports mmlib4j.representation.tree.pruningStrategy;
	exports mmlib4j.filtering.residual.ultimateLevelings;
	exports mmlib4j.images;
	exports mmlib4j.segmentation;
	exports mmlib4j.filtering.color;
	exports mmlib4j.descriptors.shapeContext;
	exports mmlib4j.math;

	requires java.desktop;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.hurence.logisland</groupId>
        <artifactId>logisland-components</artifactId>
        <version>1.3.0</version>
    </parent>

    <packaging>pom</packaging>

    <artifactId>logisland-services</artifactId>

    <modules>
        <module>logisland-service-influxdb</module>
        <module>logisland-service-cassandra</module>
        <module>logisland-service-mongodb</module>
        <module>logisland-service-inmemory-cache</module>
        <module>logisland-service-ip-to-geo</module>
        <module>logisland-service-redis</module>
        <module>logisland-service-hbase</module>
        <module>logisland-service-solr</module>
        <module>logisland-service-elasticsearch</module>
        <module>logisland-service-rest</module>
        <module>logisland-service-proxy</module>
    </modules>

</project>


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

<TITLE>
InputAdapter (Slick - The 2D Library)
</TITLE>

<META NAME="keywords" CONTENT="org.newdawn.slick.util.InputAdapter class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.newdawn.slick.util

Class InputAdapter

java.lang.Object
  org.newdawn.slick.util.InputAdapter

All Implemented Interfaces:
ControlledInputReciever, ControllerListener, InputListener, KeyListener, MouseListener

Direct Known Subclasses:
AbstractComponent

public class InputAdapter
extends java.lang.Object
implements InputListener

An implement implementation of the InputListener interface

Author:

kevin

Constructor Summary

InputAdapter()

Method Summary

 void
controllerButtonPressed(int controller,
                        int button)

          Notification that a button control has been pressed on
 the controller.

 void
controllerButtonReleased(int controller,
                         int button)

          Notification that a button control has been released on
 the controller.

 void
controllerDownPressed(int controller)

          Notification that the down control has been pressed on
 the controller.

 void
controllerDownReleased(int controller)

          Notification that the down control has been released on
 the controller.

 void
controllerLeftPressed(int controller)

          Notification that the left control has been pressed on
 the controller.

 void
controllerLeftReleased(int controller)

          Notification that the left control has been released on
 the controller.

 void
controllerRightPressed(int controller)

          Notification that the right control has been pressed on
 the controller.

 void
controllerRightReleased(int controller)

          Notification that the right control has been released on
 the controller.

 void
controllerUpPressed(int controller)

          Notification that the up control has been pressed on
 the controller.

 void
controllerUpReleased(int controller)

          Notification that the up control has been released on
 the controller.

 void
inputEnded()

          Notification that all input events have been sent for this frame

 void
inputStarted()

          Notification that input is about to be processed

 boolean
isAcceptingInput()

          Check if this input listener is accepting input

 void
keyPressed(int key,
           char c)

          Notification that a key was pressed

 void
keyReleased(int key,
            char c)

          Notification that a key was released

 void
mouseClicked(int button,
             int x,
             int y,
             int clickCount)

          Notification that a mouse button was clicked.

 void
mouseDragged(int oldx,
             int oldy,
             int newx,
             int newy)

          Notification that mouse cursor was dragged

 void
mouseMoved(int oldx,
           int oldy,
           int newx,
           int newy)

          Notification that mouse cursor was moved

 void
mousePressed(int button,
             int x,
             int y)

          Notification that a mouse button was pressed

 void
mouseReleased(int button,
              int x,
              int y)

          Notification that a mouse button was released

 void
mouseWheelMoved(int change)

          Notification that the mouse wheel position was updated

 void
setAcceptingInput(boolean acceptingInput)

          Indicate if we should be accepting input of any sort

 void
setInput(Input input)

          Set the input that events are being sent from

Methods inherited from class java.lang.Object

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

Constructor Detail

InputAdapter

public InputAdapter()

Method Detail

controllerButtonPressed

public void controllerButtonPressed(int controller,
                                    int button)

Description copied from interface: ControllerListener

Notification that a button control has been pressed on
 the controller.

Specified by:
controllerButtonPressed in interface ControllerListener

Parameters:
controller - The index of the controller on which the control
 was pressed.
button - The index of the button pressed (starting at 1)
See Also:
ControllerListener.controllerButtonPressed(int, int)

controllerButtonReleased

public void controllerButtonReleased(int controller,
                                     int button)

Description copied from interface: ControllerListener

Notification that a button control has been released on
 the controller.

Specified by:
controllerButtonReleased in interface ControllerListener

Parameters:
controller - The index of the controller on which the control
 was released.
button - The index of the button released (starting at 1)
See Also:
ControllerListener.controllerButtonReleased(int, int)

controllerDownPressed

public void controllerDownPressed(int controller)

Description copied from interface: ControllerListener

Notification that the down control has been pressed on
 the controller.

Specified by:
controllerDownPressed in interface ControllerListener

Parameters:
controller - The index of the controller on which the control
 was pressed.
See Also:
ControllerListener.controllerDownPressed(int)

controllerDownReleased

public void controllerDownReleased(int controller)

Description copied from interface: ControllerListener

Notification that the down control has been released on
 the controller.

Specified by:
controllerDownReleased in interface ControllerListener

Parameters:
controller - The index of the controller on which the control
 was released.
See Also:
ControllerListener.controllerDownReleased(int)

controllerLeftPressed

public void controllerLeftPressed(int controller)

Description copied from interface: ControllerListener

Notification that the left control has been pressed on
 the controller.

Specified by:
controllerLeftPressed in interface ControllerListener

Parameters:
controller - The index of the controller on which the control
 was pressed.
See Also:
ControllerListener.controllerLeftPressed(int)

controllerLeftReleased

public void controllerLeftReleased(int controller)

Description copied from interface: ControllerListener

Notification that the left control has been released on
 the controller.

Specified by:
controllerLeftReleased in interface ControllerListener

Parameters:
controller - The index of the controller on which the control
 was released.
See Also:
ControllerListener.controllerLeftReleased(int)

controllerRightPressed

public void controllerRightPressed(int controller)

Description copied from interface: ControllerListener

Notification that the right control has been pressed on
 the controller.

Specified by:
controllerRightPressed in interface ControllerListener

Parameters:
controller - The index of the controller on which the control
 was pressed.
See Also:
ControllerListener.controllerRightPressed(int)

controllerRightReleased

public void controllerRightReleased(int controller)

Description copied from interface: ControllerListener

Notification that the right control has been released on
 the controller.

Specified by:
controllerRightReleased in interface ControllerListener

Parameters:
controller - The index of the controller on which the control
 was released.
See Also:
ControllerListener.controllerRightReleased(int)

controllerUpPressed

public void controllerUpPressed(int controller)

Description copied from interface: ControllerListener

Notification that the up control has been pressed on
 the controller.

Specified by:
controllerUpPressed in interface ControllerListener

Parameters:
controller - The index of the controller on which the control
 was pressed.
See Also:
ControllerListener.controllerUpPressed(int)

controllerUpReleased

public void controllerUpReleased(int controller)

Description copied from interface: ControllerListener

Notification that the up control has been released on
 the controller.

Specified by:
controllerUpReleased in interface ControllerListener

Parameters:
controller - The index of the controller on which the control
 was released.
See Also:
ControllerListener.controllerUpReleased(int)

inputEnded

public void inputEnded()

Description copied from interface: ControlledInputReciever

Notification that all input events have been sent for this frame

Specified by:
inputEnded in interface ControlledInputReciever

See Also:
ControlledInputReciever.inputEnded()

isAcceptingInput

public boolean isAcceptingInput()

Description copied from interface: ControlledInputReciever

Check if this input listener is accepting input

Specified by:
isAcceptingInput in interface ControlledInputReciever

Returns:
True if the input listener should recieve events
See Also:
ControlledInputReciever.isAcceptingInput()

setAcceptingInput

public void setAcceptingInput(boolean acceptingInput)

Indicate if we should be accepting input of any sort

Parameters:
acceptingInput - True if we should accept input

keyPressed

public void keyPressed(int key,
                       char c)

Description copied from interface: KeyListener

Notification that a key was pressed

Specified by:
keyPressed in interface KeyListener

Parameters:
key - The key code that was pressed (@see org.newdawn.slick.Input)
c - The character of the key that was pressed
See Also:
KeyListener.keyPressed(int, char)

keyReleased

public void keyReleased(int key,
                        char c)

Description copied from interface: KeyListener

Notification that a key was released

Specified by:
keyReleased in interface KeyListener

Parameters:
key - The key code that was released (@see org.newdawn.slick.Input)
c - The character of the key that was released
See Also:
KeyListener.keyReleased(int, char)

mouseMoved

public void mouseMoved(int oldx,
                       int oldy,
                       int newx,
                       int newy)

Description copied from interface: MouseListener

Notification that mouse cursor was moved

Specified by:
mouseMoved in interface MouseListener

Parameters:
oldx - The old x position of the mouse
oldy - The old y position of the mouse
newx - The new x position of the mouse
newy - The new y position of the mouse
See Also:
MouseListener.mouseMoved(int, int, int, int)

mousePressed

public void mousePressed(int button,
                         int x,
                         int y)

Description copied from interface: MouseListener

Notification that a mouse button was pressed

Specified by:
mousePressed in interface MouseListener

Parameters:
button - The index of the button (starting at 0)
x - The x position of the mouse when the button was pressed
y - The y position of the mouse when the button was pressed
See Also:
MouseListener.mousePressed(int, int, int)

mouseReleased

public void mouseReleased(int button,
                          int x,
                          int y)

Description copied from interface: MouseListener

Notification that a mouse button was released

Specified by:
mouseReleased in interface MouseListener

Parameters:
button - The index of the button (starting at 0)
x - The x position of the mouse when the button was released
y - The y position of the mouse when the button was released
See Also:
MouseListener.mouseReleased(int, int, int)

mouseWheelMoved

public void mouseWheelMoved(int change)

Description copied from interface: MouseListener

Notification that the mouse wheel position was updated

Specified by:
mouseWheelMoved in interface MouseListener

Parameters:
change - The amount of the wheel has moved
See Also:
MouseListener.mouseWheelMoved(int)

setInput

public void setInput(Input input)

Description copied from interface: ControlledInputReciever

Set the input that events are being sent from

Specified by:
setInput in interface ControlledInputReciever

Parameters:
input - The input instance sending events
See Also:
ControlledInputReciever.setInput(org.newdawn.slick.Input)

mouseClicked

public void mouseClicked(int button,
                         int x,
                         int y,
                         int clickCount)

Description copied from interface: MouseListener

Notification that a mouse button was clicked. Due to double click
 handling the single click may be delayed slightly. For absolute notification
 of single clicks use mousePressed().

 To be absolute this method should only be used when considering double clicks

Specified by:
mouseClicked in interface MouseListener

Parameters:
button - The index of the button (starting at 0)
x - The x position of the mouse when the button was pressed
y - The y position of the mouse when the button was pressed
clickCount - The number of times the button was clicked
See Also:
MouseListener.mouseClicked(int, int, int, int)

mouseDragged

public void mouseDragged(int oldx,
                         int oldy,
                         int newx,
                         int newy)

Description copied from interface: MouseListener

Notification that mouse cursor was dragged

Specified by:
mouseDragged in interface MouseListener

Parameters:
oldx - The old x position of the mouse
oldy - The old y position of the mouse
newx - The new x position of the mouse
newy - The new y position of the mouse

inputStarted

public void inputStarted()

Description copied from interface: ControlledInputReciever

Notification that input is about to be processed

Specified by:
inputStarted in interface ControlledInputReciever

See Also:
ControlledInputReciever.inputStarted()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2006 New Dawn Software. All Rights Reserved.


text:
#include <Python.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

#define LENGTH 0
#define INDEX 1
#define OUT_LINE_LEN 8

int* validLocs;

/**
 *
 * FUNCTION: seeds2string
 * converts a list of seeds to a human readable string
 *
 */
char* seeds2string(int** seedsList, int seedsListLen){

  char* output;
  output = malloc((seedsListLen + 1) * OUT_LINE_LEN * sizeof(char));

  // add the header
  strcpy(output, "STR\tLEN\n");

  for(int i = 0; i < seedsListLen; i++){
    char helper1[4], helper2[4];
    sprintf(helper1, "%d\t", seedsList[i][INDEX]);
    sprintf(helper2, "%d\n", seedsList[i][LENGTH]);

    strcat(output, helper1);
    strcat(output, helper2);
  }

  return output;
}

void copy_seeds_list(int** currSeedsList, int** optimalSeedsList, int seedsListLen){

  for(int i = 0; i < seedsListLen; i++){
    optimalSeedsList[i][LENGTH] = currSeedsList[i][LENGTH];
    optimalSeedsList[i][INDEX] = currSeedsList[i][INDEX];
  }

}

/**
 *
 * FUNCTION: num_loc_generated
 * returns the number of locations that a list of seeds generates
 *
 */
int num_loc_generated(int** seedFreqMatrix, int seedMinLen, int** seedsList, int seedsListLen){
  int locations = 0;

  for(int i = 0; i < seedsListLen; i ++){
    locations += seedFreqMatrix[seedsList[i][LENGTH] - seedMinLen][seedsList[i][INDEX]];
  }

  return locations;
}

/**
 *
 * FUNCTION: is_valid
 * takes in a list of seeds and returns (true or false) if it
 * is a valid seed location. (e.g. no overlapping)
 *
 */
int is_valid(int readLen, int** seedsList, int seedsListLen){
  memset(validLocs, 1, readLen * sizeof(validLocs[0]));

  int currIndex;
  for(int i = 0; i < seedsListLen; i++){
    for(int j = 0; j < seedsList[i][LENGTH]; j++){
      currIndex = j + seedsList[i][INDEX];
      /*
       * return with 0 (i.e. false) if the index is already occupied
       */
      if(currIndex >= readLen || !validLocs[currIndex])
	return 0;
      /*
       * set the space as occupied if not already
       */
      else
	validLocs[currIndex] = 0;
    }
  }

  return 1; //if none of the seed overlap or are otherwise invalid, return 1 (i.e. true)
}

/**
 *
 * FUNCTION: find_optimal_seeds
 * returns a string of the optimal seed locations
 *
 */
char* find_optimal_seeds(PyObject* seed_freq_marix, int readLen, int seedMinLen, int seedMaxLen, int errorsAllowed, int printFreq){

  const int seedsListLen = errorsAllowed + 1;
  /*
   * Read in the seed_freq_matrix and convert to 2d int array for c computations
   */
  if(!PyList_Check(seed_freq_marix))
    return NULL;

  int numLines = PyList_Size(seed_freq_marix);
  int* seedFreqMatrix[numLines];

  for(int i = 0; i < numLines; i++){
    seedFreqMatrix[i] = malloc( numLines * sizeof(int));
    for(int j = 0; j < numLines; j++){
      seedFreqMatrix[i][j] = (int) PyFloat_AsDouble(PyList_GET_ITEM(PyList_GET_ITEM(seed_freq_marix, i), j));
    }
  }

  /*
   * Allocate memory for the helper array validLocs
   * and the seedsList holder (global var)
   */
  validLocs = malloc(readLen * sizeof(int*));

  int* currSeedsList[seedsListLen];
  // set all seeds in the starting position
  for(int i = 0; i < seedsListLen; i++){
    currSeedsList[i] = malloc(2 * sizeof(int*));
    currSeedsList[i][LENGTH] = seedMinLen;
    currSeedsList[i][INDEX] = 0;
  }

  int* optimalSeedsList[seedsListLen];
  for(int i = 0; i < seedsListLen; i++){
    optimalSeedsList[i] = malloc(2 * sizeof(int*));
    optimalSeedsList[i][LENGTH] = seedMinLen;
    optimalSeedsList[i][INDEX] = 0;
  }

  /*
   * begin iterating over all possible locations
   */
  const unsigned long combinations = pow((seedMaxLen - seedMinLen + 1) * readLen, seedsListLen);
  int optimalLocGen = 2147483647; // initialize to max value for signed int
  int innerLoopIterations;

  for(unsigned long i = 0; i < combinations + printFreq; i += printFreq){

    innerLoopIterations = (combinations < printFreq * i) ? printFreq * i - combinations : printFreq;

    if(printFreq != 0){
      printf("On iteration %lu of %lu\n", i, combinations);
    }

    for(int j = 0; j < innerLoopIterations; j++){

      /*
       * a new better configuration is stored when found
       */
      if(is_valid(readLen, currSeedsList, seedsListLen)){
	int currLocGen = num_loc_generated(seedFreqMatrix, seedMinLen, currSeedsList, seedsListLen);
	if(optimalLocGen > currLocGen){

	  optimalLocGen  = currLocGen;
	  copy_seeds_list(currSeedsList, optimalSeedsList, seedsListLen);

	}
      }

      /*
       * increment the seed to the next possible location
       * think of a clock when trying to understand this code
       */
      for(int i = 0; i < seedsListLen; i++){
	if(currSeedsList[i][INDEX] < readLen - 1){
	  currSeedsList[i][INDEX]++;
	  break;
	}
	else{
	  currSeedsList[i][INDEX] = 0;
	  if(currSeedsList[i][LENGTH] < seedMaxLen){
	    currSeedsList[i][LENGTH]++;
	    break;
	  }
	  else{
	    currSeedsList[i][LENGTH] = seedMinLen;
	  }
	}
      }

    }
  }

  free(validLocs);
  return seeds2string(optimalSeedsList, seedsListLen);

}


text:
module Navfund
  class RobinsonsBank < Provider
    # List of funds
    MAIN_URL = "http://www.uitf.com.ph/daily_navpu.php?bank_id=34"
    Funds = [
      {:name => "RBank Peso Money Market Fund", :currency => "PHP", :ticker => ""},
      {:name => "RBank Balanced Fund", :currency => "PHP", :ticker => ""}
      ]

    def initialize(main_url=nil)
      @url = main_url ||= MAIN_URL
      @funds = Funds
      scrape
    end

    # Fetch the current value
    def value(fund, fund_type=nil)
      uitf_com_ph_parser(fund)
    end

    def value_at
      uitf_com_ph_date_parser
    end

  end
end


text:
using System.Xml.Serialization;

namespace EConnectApi.Definitions
{
    [XmlType(AnonymousType = true)]
    [XmlRoot(Namespace = "", IsNullable = false)]
    public class GetIntegrationRequests : PageAble
    {
        public class GetIntegrationRequestsFilters
        {
            public bool ShouldSerializeStatus() { return Status.HasValue; }
            public IntegrationRequestStatus? Status { get; set; }

            public string SentBy { get; set; }

            public string SentFor { get; set; }

            public string PayByRequester { get; set; }

            public string AppId { get; set; }

            public string TrackingId { get; set; }

        }

        [XmlElement(ElementName = "filters")]
        public GetIntegrationRequestsFilters Filters { get; set; }
    }

    public enum IntegrationRequestStatus
    {
        Accepted,
        Pending,
        Rejected,
        Withdrawn,
        Cancelled
    }
}


text:
require 'spec_helper'

describe 'homebrew::repo' do
  let(:facts) do
    {
      :boxen_home => '/opt/boxen',
      :luser      => 'testuser',
    }
  end

  it { should include_class('homebrew') }

  it do
    should contain_exec('brew update').with({
      :creates => '/opt/boxen/homebrew/.git',
    })
  end
end


text:
package com.eusecom.attendance;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.eusecom.attendance.models.User;
import com.eusecom.attendance.models.Post;

import java.util.HashMap;
import java.util.Map;

public class NewPostActivity extends BaseDatabaseActivity {

    private static final String TAG = "NewPostActivity";
    private static final String REQUIRED = "Required";

    // [START declare_database_ref]
    private DatabaseReference mDatabase;
    // [END declare_database_ref]

    private EditText mTitleField;
    private EditText mBodyField;

    String editx, keyx;

    private DatabaseReference mPostReference;
    private ValueEventListener mPostListener;

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

        Intent i = getIntent();
        Bundle extras = i.getExtras();
        editx = extras.getString("editx");
        keyx = extras.getString("keyx");

        // [START initialize_database_ref]
        mDatabase = FirebaseDatabase.getInstance().getReference();
        // [END initialize_database_ref]

        mTitleField = (EditText) findViewById(R.id.field_title);
        mBodyField = (EditText) findViewById(R.id.field_body);

        if( editx.equals("1")) {

            mPostReference = FirebaseDatabase.getInstance().getReference()
                    .child("posts").child(keyx);

        }

        findViewById(R.id.fab_submit_post).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitPost();
            }
        });
    }//end of oncreate

    @Override
    public void onStart() {
        super.onStart();

        if( editx.equals("1")) {
            // Add value event listener to the post
            // [START post_value_event_listener]
            ValueEventListener postListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    // Get Post object and use the values to update the UI
                    Post post = dataSnapshot.getValue(Post.class);
                    // [START_EXCLUDE]

                    mTitleField.setText(post.title);
                    mBodyField.setText(post.body);

                    // [END_EXCLUDE]
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    // Getting Post failed, log a message
                    Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
                    // [START_EXCLUDE]
                    Toast.makeText(NewPostActivity.this, "Failed to load post.",
                            Toast.LENGTH_SHORT).show();
                    // [END_EXCLUDE]
                }
            };
            mPostReference.addValueEventListener(postListener);
            // [END post_value_event_listener]

            // Keep copy of post listener so we can remove it when app stops
            mPostListener = postListener;

        }

    }

    @Override
    public void onStop() {
        super.onStop();

        if( editx.equals("1")) {
            // Remove post value event listener
            if (mPostListener != null) {
                mPostReference.removeEventListener(mPostListener);
            }

        }

    }//end of onstop

    private void submitPost() {

        showProgressDialog();

        final String title = mTitleField.getText().toString();
        final String body = mBodyField.getText().toString();

        // Title is required
        if (TextUtils.isEmpty(title)) {
            mTitleField.setError(REQUIRED);
            return;
        }

        // Body is required
        if (TextUtils.isEmpty(body)) {
            mBodyField.setError(REQUIRED);
            return;
        }

        // [START single_value_read]
        final String userId = getUid();
        mDatabase.child("users").child(userId).addListenerForSingleValueEvent(
                new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        // Get user value
                        User user = dataSnapshot.getValue(User.class);

                        // [START_EXCLUDE]
                        if (user == null) {
                            // User is null, error out
                            Log.e(TAG, "User " + userId + " is unexpectedly null");
                            Toast.makeText(NewPostActivity.this,
                                    "Error: could not fetch user.",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            // Write new post
                            writeNewPost(userId, user.username, title, body);

                        }

                        hideProgressDialog();
                        // Finish this Activity, back to the stream
                        finish();
                        // [END_EXCLUDE]
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Log.w(TAG, "getUser:onCancelled", databaseError.toException());
                        hideProgressDialog();
                    }
                });
        // [END single_value_read]
    }

    // [START write_fan_out]
    private void writeNewPost(String userId, String username, String title, String body) {
        // Create new post at /user-posts/$userid/$postid and at
        // /posts/$postid simultaneously

        String key = mDatabase.child("posts").push().getKey();

        if( editx.equals("1")) {
            key=keyx;
        }

        Post post = new Post(userId, username, title, body);
        Map<String, Object> postValues = post.toMap();

        Map<String, Object> childUpdates = new HashMap<>();

        childUpdates.put("/posts/" + key, postValues);
        childUpdates.put("/user-posts/" + userId + "/" + key, postValues);

        mDatabase.updateChildren(childUpdates);
        //hideProgressDialog();
    }
    // [END write_fan_out]
}


text:
unshiftme-backbone
==================

unshift.me with Backbone


text:
#ifndef MAIN_H_
#define MAIN_H_

#include "camera.h"
#include "orthographic_camera.h"
#include "scene.h"
#include "buffer.h"
#include "raytracer.h"

#endif /* MAIN_H_ */