text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'chrome://internet-detail-dialog/internet_detail_dialog_container.js';

import {InternetDetailDialogBrowserProxyImpl} from 'chrome://internet-detail-dialog/internet_detail_dialog_container.js';
import {MojoInterfaceProviderImpl} from 'chrome://resources/cr_components/chromeos/network/mojo_interface_provider.js';
import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.js';
import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {FakeNetworkConfig} from 'chrome://test/chromeos/fake_network_config_mojom.js';
import {TestBrowserProxy} from 'chrome://test/test_browser_proxy.js';

/** @implements {InternetDetailDialogBrowserProxy} */
export class TestInternetDetailDialogBrowserProxy extends TestBrowserProxy {
  constructor() {
    super([
      'getDialogArguments',
      'dialogClose',
    ]);
  }

  /** @override */
  getDialogArguments() {
    return JSON.stringify({guid: 'guid'});
  }

  /** @override */
  dialogClose() {}
}

suite('internet-detail-dialog', () => {
  const guid = 'guid';
  const test_iccid = '11111111111111111';
  let internetDetailDialog = null;

  /** @type {?chromeos.networkConfig.mojom.CrosNetworkConfigRemote} */
  let mojoApi_;

  suiteSetup(function() {
    mojoApi_ = new FakeNetworkConfig();
    MojoInterfaceProviderImpl.getInstance().remote_ = mojoApi_;
  });

  function flushAsync() {
    flush();
    // Use setTimeout to wait for the next macrotask.
    return new Promise(resolve => setTimeout(resolve));
  }

  function getManagedProperties(type, opt_source) {
    const result = OncMojo.getDefaultManagedProperties(type, guid, name);
    if (opt_source) {
      result.source = opt_source;
    }
    return result;
  }

  setup(async () => {
    PolymerTest.clearBody();
    InternetDetailDialogBrowserProxyImpl.instance_ =
        new TestInternetDetailDialogBrowserProxy();
    mojoApi_.resetForTest();
  });

  async function init() {
    internetDetailDialog = document.createElement('internet-detail-dialog');
    document.body.appendChild(internetDetailDialog);
    await flushAsync();
  }

  async function setupCellularNetwork(isPrimary, isInhibited) {
    const mojom = chromeos.networkConfig.mojom;
    await mojoApi_.setNetworkTypeEnabledState(
        mojom.NetworkType.kCellular, true);

    const cellularNetwork = getManagedProperties(
        mojom.NetworkType.kCellular, mojom.OncSource.kDevice);
    cellularNetwork.typeProperties.cellular.iccid = test_iccid;
    // Required for connectDisconnectButton to be rendered.
    cellularNetwork.connectionState = isPrimary ?
        mojom.ConnectionStateType.kConnected :
        mojom.ConnectionStateType.kNotConnected;
    // Required for networkChooseMobile to be rendered.
    cellularNetwork.typeProperties.cellular.supportNetworkScan = true;

    mojoApi_.setManagedPropertiesForTest(cellularNetwork);
    mojoApi_.setDeviceStateForTest({
      type: mojom.NetworkType.kCellular,
      deviceState: mojom.DeviceStateType.kEnabled,
      inhibitReason:
          (isInhibited ? mojom.InhibitReason.kInstallingProfile :
                         mojom.InhibitReason.kNotInhibited),
      simInfos: [{
        iccid: test_iccid,
        isPrimary: isPrimary,
      }],
    });
  }

  function getElement(selector) {
    const element = internetDetailDialog.$$(selector);
    assertTrue(!!element);
    return element;
  }

  test('Network not on active sim, hide configurations', async () => {
    await setupCellularNetwork(/*isPrimary=*/ false, /*isInhibited=*/ false);

    await init();
    assertFalse(internetDetailDialog.showConfigurableSections_);

    const managedProperties = internetDetailDialog.managedProperties_;
    assertTrue(internetDetailDialog.showCellularSim_(managedProperties));
    assertFalse(!!internetDetailDialog.$$('network-siminfo'));

    // The 'Forget' and 'ConnectDisconnect' buttons should still be showing.
    assertTrue(!!internetDetailDialog.$$('cr-button'));
  });

  test('Network on active sim, show configurations', async () => {
    await setupCellularNetwork(/*isPrimary=*/ true, /*isInhibited=*/ false);

    await init();
    assertTrue(internetDetailDialog.showConfigurableSections_);

    const managedProperties = internetDetailDialog.managedProperties_;
    assertTrue(internetDetailDialog.showCellularSim_(managedProperties));
    assertTrue(!!internetDetailDialog.$$('network-siminfo'));
  });

  test('Dialog disabled when inhibited', async () => {
    // Start uninhibited.
    await setupCellularNetwork(/*isPrimary=*/ true, /*isInhibited=*/ false);
    await init();

    const connectDisconnectButton = getElement('#connectDisconnect');
    const networkSimInfo = getElement('network-siminfo');
    const networkChooseMobile = getElement('network-choose-mobile');
    const networkApnlist = getElement('network-apnlist');
    const networkProxy = getElement('network-proxy');
    const networkIpConfig = getElement('network-ip-config');
    const networkNameservers = getElement('network-nameservers');
    const infoFields = getElement('network-property-list-mojo');

    assertFalse(connectDisconnectButton.disabled);
    assertFalse(networkSimInfo.disabled);
    assertFalse(networkChooseMobile.disabled);
    assertFalse(networkApnlist.disabled);
    assertTrue(networkProxy.editable);
    assertFalse(networkIpConfig.disabled);
    assertFalse(networkNameservers.disabled);
    assertFalse(infoFields.disabled);

    // Mock device being inhibited.
    const mojom = chromeos.networkConfig.mojom;
    mojoApi_.setDeviceStateForTest({
      type: mojom.NetworkType.kCellular,
      deviceState: mojom.DeviceStateType.kEnabled,
      inhibitReason: mojom.InhibitReason.kInstallingProfile,
      simInfos: [{
        iccid: test_iccid,
        isPrimary: true,
      }],
    });
    await flushAsync();

    assertTrue(connectDisconnectButton.disabled);
    assertTrue(networkSimInfo.disabled);
    assertTrue(networkChooseMobile.disabled);
    assertTrue(networkApnlist.disabled);
    assertFalse(networkProxy.editable);
    assertTrue(networkIpConfig.disabled);
    assertTrue(networkNameservers.disabled);
    assertTrue(infoFields.disabled);

    // Uninhibit.
    mojoApi_.setDeviceStateForTest({
      type: mojom.NetworkType.kCellular,
      deviceState: mojom.DeviceStateType.kEnabled,
      inhibitReason: mojom.InhibitReason.kNotInhibited,
      simInfos: [{
        iccid: test_iccid,
        isPrimary: true,
      }],
    });
    await flushAsync();

    assertFalse(connectDisconnectButton.disabled);
    assertFalse(networkSimInfo.disabled);
    assertFalse(networkChooseMobile.disabled);
    assertFalse(networkApnlist.disabled);
    assertTrue(networkProxy.editable);
    assertFalse(networkIpConfig.disabled);
    assertFalse(networkNameservers.disabled);
    assertFalse(infoFields.disabled);
  });
});


text:
Welcome to the ruby-saml project example for Rails4
===================================================

Rails is a web-application framework that includes everything needed to create
database-backed web applications according to the Model-View-Control pattern.

This pattern splits the view (also called the presentation) into "dumb" templates
that are primarily responsible for inserting pre-built data in between HTML tags.
The model contains the "smart" domain objects (such as Account, Product, Person,
Post) that holds all the business logic and knows how to persist themselves to
a database. The controller handles the incoming requests (such as Save New Account,
Update Product, Show Post) by manipulating the model and directing data to the view.

In Rails, the model is handled by what's called an object-relational mapping
layer entitled Active Record. This layer allows you to present the data from
database rows as objects and embellish these data objects with business logic
methods. You can read more about Active Record in
link:files/vendor/rails/activerecord/README.html.

The controller and view are handled by the Action Pack, which handles both
layers by its two parts: Action View and Action Controller. These two layers
are bundled in a single package due to their heavy interdependence. This is
unlike the relationship between the Active Record and Action Pack that is much
more separate. Each of these packages can be used independently outside of
Rails.  You can read more about Action Pack in
link:files/vendor/rails/actionpack/README.html.

Supported Version
-----------------

This ruby-saml-example project works with rails4 and uses is compatible with the ruby-saml toolkit >= 1.0.0.

Getting Started
---------------

1. Download the ruby-saml-example code
2. Install the required gems
3. Execute the command rails server      [It'ss supposed that you installed previously Rails4]
4. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!"
5. Follow the guidelines to start developing your application

Web Servers
-----------

By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails
with a variety of other web servers.

Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>.
More info at: http://mongrel.rubyforge.org

Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or
Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use
FCGI or proxy to a pack of Mongrels/Thin/Ebb servers.

Apache .htaccess example for FCGI/CGI
-------------------------------------

**General Apache options**
```
  AddHandler fastcgi-script .fcgi
  AddHandler cgi-script .cgi
  Options +FollowSymLinks +ExecCGI
```

If you don't want Rails to look in certain directories,
use the following rewrite rules so that Apache won't rewrite certain requests

Example:
```
  RewriteCond %{REQUEST_URI} ^/notrails.*
  RewriteRule .* - [L]
```

Redirect all requests not available on the filesystem to Rails
By default the cgi dispatcher is used which is very slow

For better performance replace the dispatcher with the fastcgi one

Example:
```
  RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
  RewriteEngine On

If your Rails application is accessed via an Alias directive,
then you MUST also set the RewriteBase in this htaccess file.

Example:
```
  Alias /myrailsapp /path/to/myrailsapp/public
  RewriteBase /myrailsapp

  RewriteRule ^$ index.html [QSA]
  RewriteRule ^([^.]+)$ $1.html [QSA]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
``
In case Rails experiences terminal errors, Instead of displaying this message you can supply a file here which will be rendered instead.

Example:
```
   ErrorDocument 500 /500.html

   ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly"
```

Debugging Rails
---------------

Sometimes your application goes wrong.  Fortunately there are a lot of tools that
will help you debug it and get it back on the rails.

First area to check is the application log files.  Have "tail -f" commands running
on the server.log and development.log. Rails will automatically display debugging
and runtime information to these files. Debugging info will also be shown in the
browser on requests from 127.0.0.1.

You can also log your own messages directly into the log file from your code using
the Ruby logger class from inside your controllers. Example:
```
  class WeblogController < ActionController::Base
    def destroy
      @weblog = Weblog.find(params[:id])
      @weblog.destroy
      logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
    end
  end
```
The result will be a message in your log file along the lines of:
```
  Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1
```
More information on how to use the logger is at http://www.ruby-doc.org/core/

Also, Ruby documentation can be found at http://www.ruby-lang.org/ including:

* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/
* Learn to Program: http://pine.fm/LearnToProgram/  (a beginners guide)

These two online (and free) books will bring you up to speed on the Ruby language
and also on programming in general.

Documentation related to configuring logging on ruby-saml can be found at:
https://github.com/onelogin/ruby-saml#configuring-logging

Debugger
--------

You need to install byebug to run the server in debugging mode. With gems, use 'gem install byebug'
Later set
```
debugger
```
where you want to set the breackpoint.

Example:

```
  class WeblogController < ActionController::Base
    def index
      @posts = Post.find(:all)
      debugger
    end
  end
```

So the controller will accept the action, run the first line, then present you
with a IRB prompt in the server window. Here you can do things like:

```
  >> @posts.inspect
  => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
       #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
  >> @posts.first.title = "hello from a debugger"
  => "hello from a debugger"
```

and even better is that you can examine how your runtime objects actually work:

```
  >> f = @posts.first
  => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
  >> f.
  Display all 152 possibilities? (y or n)
```

Finally, when you're ready to resume execution, you enter "cont"

Console
-------

You can interact with the domain model by starting the console through <tt>script/console</tt>.
Here you'll have all parts of the application configured, just like it is when the
application is running. You can inspect domain models, change values, and save to the
database. Starting the script without arguments will launch it in the development environment.
Passing an argument will specify a different environment, like <tt>script/console production</tt>.

To reload your controllers and models after launching the console run <tt>reload!</tt>

**dbconsole**

You can go to the command line of your database directly through <tt>script/dbconsole</tt>.
You would be connected to the database with the credentials defined in database.yml.
Starting the script without arguments will connect you to the development database. Passing an argument will connect you to a different database, like <tt>script/dbconsole production</tt>.

Currently works for mysql, postgresql and sqlite.

Description of Contents
-----------------------

**app**
  Holds all the code that's specific to this particular application.

**app/controllers**
  Holds controllers that should be named like weblogs_controller.rb for
  automated URL mapping. All controllers should descend from ApplicationController
  which itself descends from ActionController::Base.

**app/models**
  Holds models that should be named like post.rb.
  Most models will descend from ActiveRecord::Base.

**app/views**
  Holds the template files for the view that should be named like
  weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby
  syntax.

**app/views/layouts**
  Holds the template files for layouts to be used with views. This models the common
  header/footer method of wrapping views. In your views, define a layout using the
  <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html

**app/views/saml**
  Contains templates used in the saml views:
  complete.html.erb displays the attribute list of the user
  fail.html.erb displays an error

**.erb,**
  call <% yield %> to render the view using this layout.

**app/helpers**
  Holds view helpers that should be named like weblogs_helper.rb. These are generated
  for you automatically when using script/generate for controllers. Helpers can be used to
  wrap functionality for your views into methods.

**config**
  Configuration files for the Rails environment, the routing map, the database, and other dependencies.

**db**
  Contains the database schema in schema.rb.  db/migrate contains all
  the sequence of Migrations for your schema.

**doc**
  This directory is where your application documentation will be stored when generated
  using <tt>rake doc:app</tt>

**lib**
  Application specific libraries. Basically, any kind of custom code that doesn't
  belong under controllers, models, or helpers. This directory is in the load path.

**public**
  The directory available for the web server. Contains subdirectories for images, stylesheets, and javascripts. Also contains the dispatchers and the default HTML files. This should be set as the DOCUMENT_ROOT of your web server.

**script**
  Helper scripts for automation and generation.

**test**
  Unit and functional tests along with fixtures. When using the script/generate scripts, template test files will be generated for you and placed in this directory.

**vendor**
  External libraries that the application depends on. Also includes the plugins subdirectory. If the app has frozen rails, those gems also go here, under vendor/rails/. This directory is in the load path.

redpajama_set_name: RedPajamaGithub


text: __author__ = ['markshao']


text:
namespace google {
namespace cloud {
namespace vision {
namespace v1 {

static const char* ImageAnnotator_method_names[] = {
  "/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateImages",
};

std::unique_ptr< ImageAnnotator::Stub> ImageAnnotator::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) {
  std::unique_ptr< ImageAnnotator::Stub> stub(new ImageAnnotator::Stub(channel));
  return stub;
}

ImageAnnotator::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel)
  : channel_(channel), rpcmethod_BatchAnnotateImages_(ImageAnnotator_method_names[0], ::grpc::RpcMethod::NORMAL_RPC, channel)
  {}

::grpc::Status ImageAnnotator::Stub::BatchAnnotateImages(::grpc::ClientContext* context, const ::google::cloud::vision::v1::BatchAnnotateImagesRequest& request, ::google::cloud::vision::v1::BatchAnnotateImagesResponse* response) {
  return ::grpc::BlockingUnaryCall(channel_.get(), rpcmethod_BatchAnnotateImages_, context, request, response);
}

::grpc::ClientAsyncResponseReader< ::google::cloud::vision::v1::BatchAnnotateImagesResponse>* ImageAnnotator::Stub::AsyncBatchAnnotateImagesRaw(::grpc::ClientContext* context, const ::google::cloud::vision::v1::BatchAnnotateImagesRequest& request, ::grpc::CompletionQueue* cq) {
  return new ::grpc::ClientAsyncResponseReader< ::google::cloud::vision::v1::BatchAnnotateImagesResponse>(channel_.get(), cq, rpcmethod_BatchAnnotateImages_, context, request);
}

ImageAnnotator::Service::Service() {
  (void)ImageAnnotator_method_names;
  AddMethod(new ::grpc::RpcServiceMethod(
      ImageAnnotator_method_names[0],
      ::grpc::RpcMethod::NORMAL_RPC,
      new ::grpc::RpcMethodHandler< ImageAnnotator::Service, ::google::cloud::vision::v1::BatchAnnotateImagesRequest, ::google::cloud::vision::v1::BatchAnnotateImagesResponse>(
          std::mem_fn(&ImageAnnotator::Service::BatchAnnotateImages), this)));
}

ImageAnnotator::Service::~Service() {
}

::grpc::Status ImageAnnotator::Service::BatchAnnotateImages(::grpc::ServerContext* context, const ::google::cloud::vision::v1::BatchAnnotateImagesRequest* request, ::google::cloud::vision::v1::BatchAnnotateImagesResponse* response) {
  (void) context;
  (void) request;
  (void) response;
  return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}

}  // namespace google
}  // namespace cloud
}  // namespace vision
}  // namespace v1


text:
package net.sourceforge.pebble.web.action;

import net.sourceforge.pebble.Constants;
import net.sourceforge.pebble.domain.BlogManager;
import net.sourceforge.pebble.domain.Blog;
import net.sourceforge.pebble.web.security.RequireSecurityToken;
import net.sourceforge.pebble.web.view.RedirectView;
import net.sourceforge.pebble.web.view.View;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Reloads a blog from disk.
 *
 * @author    Simon Brown
 */
@RequireSecurityToken
public class ReloadBlogAction extends SecureAction {

  /**
   * Peforms the processing associated with this action.
   *
   * @param request  the HttpServletRequest instance
   * @param response the HttpServletResponse instance
   * @return the name of the next view
   */
  public View process(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    Blog blog = (Blog)getModel().get(Constants.BLOG_KEY);
    BlogManager.getInstance().reloadBlog(blog);

    String redirectUrl = request.getParameter("redirectUrl");
    if (redirectUrl != null && redirectUrl.length() > 0) {
      return new RedirectView(blog.getUrl() + redirectUrl.substring(1));
    } else {
      return new RedirectView(blog.getUrl());
    }
  }

  /**
   * Gets a list of all roles that are allowed to access this action.
   *
   * @return  an array of Strings representing role names
   * @param request
   */
  public String[] getRoles(HttpServletRequest request) {
    return new String[]{Constants.BLOG_OWNER_ROLE, Constants.BLOG_ADMIN_ROLE};
  }

}


text:
MenuOption::MenuOption(SDL_Texture *texture, int x, int y)
{
    this->texture = texture;
    this->x = x;
    this->y = y;
    SDL_QueryTexture(this->texture, NULL, NULL, &w, &h);
}

void MenuOption::Draw(SDL_Renderer *renderer)
{
    renderTexture(texture, renderer, x + 128 - w /2, y);
}


text:
Events

		<?php $this->load->view('agent/files/event_left'); ?>

		<?php $this->load->view('agent/files/event_right'); ?>


text:
package com.halfmind.alarm.manager;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;

public class MainActivity extends AppCompatActivity {

    private AdView mAdView;

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

        // Initializing AdMob
        MobileAds.initialize(getApplicationContext(), "ca-app-pub-9753397971027272~5599296347");

        mAdView = (AdView) findViewById(R.id.ad_view);

        // For testing purposes only. Remove for Production.
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .build();

        // Uncomment for Production.
        // AdRquest adRequest = new AdRequest.Builder()
            // .addNetworkExtrasBundle(AdMobAdapter.class, extras)
            // .build();

        // Set AdListener
        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Code to be executed when an ad finishes loading.
                System.out.println("DEBUG:: Ad received!");
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                System.err.println("DEBUG:: Ad failed: " + errorCode);
            }

            @Override
            public void onAdOpened() {
                // Code to be executed when an ad opens an overlay that
                // covers the screen.
            }

            @Override
            public void onAdLeftApplication() {
                // Code to be executed when the user has left the app.
            }

            @Override
            public void onAdClosed() {
                // Code to be executed when when the user is about to return
                // to the app after tapping on an ad.
            }
        });

        mAdView.loadAd(adRequest);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
	anchor_edit的渲染文件
]]
local template = require "resty.template"
local reqArgs = require "common.request_args"
local responeData = require"common.api_data_help"
local cjson = require "cjson"
local session =require "resty.session".open()
local userDb = require "db.base_db"
local userDbOp = userDb.new()

-- 通用函数  从数据库查询的数据中截取第一条,根据key获取value
function GetNodeWithKey(table, key)
	-- 这里之所以有个临时的temp,是因为从数据库中查询出来的不是一个table,而是一个array table,切记,即使是只查询出来一条,也是array table. 雷区拍照留念
	local temp={}
	temp=table[1]
	return temp[key]
end

local currentRequestArgs = reqArgs.new()
local args = currentRequestArgs.getArgs()

local temp_anchor={}
local temp_user={}
local temp_user_info={}
local temp_room={}
if args.id_pk and args.id_pk~="" then
temp_anchor.id_pk=args.id_pk
else return
end

-- 根据获取的主播id,在几个表中查询对应的信息

	local dbress1,err1 =userDbOp.getBaseFromSql("select * from t_anchor",temp_anchor)
	if not dbress1 then
		return err1
	end
	local user_code=GetNodeWithKey(dbress1,"user_code_fk")

	temp_user.user_code=user_code
	local dbress2,err2 =userDbOp.getBaseFromSql("select * from t_user",temp_user)
	if not dbress2 then
		return err2
	end

	temp_user_info.user_code_fk=user_code
	local dbress3,err3 =userDbOp.getBaseFromSql("select * from t_user_ext_info",temp_user_info)
	if not dbress3 then
		return err3
	end

	temp_room.anchor_id_fk=temp_anchor.id_pk
	local dbress4,err4 =userDbOp.getBaseFromSql("select * from t_anchor_room",temp_room)
	if not dbress4 then
		return err4
	end

-- session必须开启缓存才能够使用,为了便捷开发,先不判断,而是直接跳转到index页面

-- if args.token == session.data.token then
-- 	-- 从登陆跳过来,带了token才能跳转到html/index.html界面
-- 	local address="/html/index.html"
-- 	local model={}
-- 	template.render(address,model)
-- else
-- 	result = responeData.new_failed({},err)
-- end
local address="/html/client_management/anchor/anchor_edit.html"

	local model={anchor_edit_anchor=dbress1,anchor_edit_user=dbress2,anchor_edit_user_info=dbress3,anchor_edit_room=dbress4}

	template.render(address,model)


text:
class AddIndexToReviewer < ActiveRecord::Migration
  def change
    add_index :commits, :reviewer_id
  end
end


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

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.lucene.search.Sort (Lucene 4.6.1 API)</title>
<meta name="date" content="2014-01-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Uses of Class
org.apache.lucene.search.Sort

Packages that use Sort

Package
Description

org.apache.lucene.search

Code to search indices.

Uses of Sort in org.apache.lucene.search

Fields in org.apache.lucene.search declared as Sort

Modifier and Type
Field and Description

static Sort
Sort.INDEXORDER

Represents sorting by index order.

static Sort
Sort.RELEVANCE

Represents sorting by computed relevance.

Methods in org.apache.lucene.search that return Sort

Modifier and Type
Method and Description

Sort
Sort.rewrite(IndexSearcher searcher)

Rewrites the SortFields in this Sort, returning a new Sort if any of the fields
 changes during their rewriting.

Methods in org.apache.lucene.search with parameters of type Sort

Modifier and Type
Method and Description

static TopFieldCollector
TopFieldCollector.create(Sort sort,
      int numHits,
      boolean fillFields,
      boolean trackDocScores,
      boolean trackMaxScore,
      boolean docsScoredInOrder)

Creates a new TopFieldCollector from the given
 arguments.

static TopFieldCollector
TopFieldCollector.create(Sort sort,
      int numHits,
      FieldDoc after,
      boolean fillFields,
      boolean trackDocScores,
      boolean trackMaxScore,
      boolean docsScoredInOrder)

Creates a new TopFieldCollector from the given
 arguments.

static TopDocs
TopDocs.merge(Sort sort,
     int topN,
     TopDocs[] shardHits)

Returns a new TopDocs, containing topN results across
  the provided TopDocs, sorting by the specified Sort.

protected TopFieldDocs
IndexSearcher.search(List<AtomicReaderContext> leaves,
      Weight weight,
      FieldDoc after,
      int nDocs,
      Sort sort,
      boolean fillFields,
      boolean doDocScores,
      boolean doMaxScore)

Just like IndexSearcher.search(Weight, int, Sort, boolean, boolean), but you choose
 whether or not the fields in the returned FieldDoc instances should
 be set by specifying fillFields.

TopFieldDocs
IndexSearcher.search(Query query,
      Filter filter,
      int n,
      Sort sort)

Search implementation with arbitrary sorting.

TopFieldDocs
IndexSearcher.search(Query query,
      Filter filter,
      int n,
      Sort sort,
      boolean doDocScores,
      boolean doMaxScore)

Search implementation with arbitrary sorting, plus
 control over whether hit scores and max score
 should be computed.

TopFieldDocs
IndexSearcher.search(Query query,
      int n,
      Sort sort)

Search implementation with arbitrary sorting and no filter.

protected TopFieldDocs
IndexSearcher.search(Weight weight,
      FieldDoc after,
      int nDocs,
      Sort sort,
      boolean fillFields,
      boolean doDocScores,
      boolean doMaxScore)

Just like IndexSearcher.search(Weight, int, Sort, boolean, boolean), but you choose
 whether or not the fields in the returned FieldDoc instances should
 be set by specifying fillFields.

protected TopFieldDocs
IndexSearcher.search(Weight weight,
      int nDocs,
      Sort sort,
      boolean doDocScores,
      boolean doMaxScore)

Expert: Low-level search implementation with arbitrary
 sorting and control over whether hit scores and max
 score should be computed.

TopDocs
IndexSearcher.searchAfter(ScoreDoc after,
           Query query,
           Filter filter,
           int n,
           Sort sort)

Finds the top n
 hits for query, applying filter if non-null,
 where all results are after a previous result (after).

TopDocs
IndexSearcher.searchAfter(ScoreDoc after,
           Query query,
           Filter filter,
           int n,
           Sort sort,
           boolean doDocScores,
           boolean doMaxScore)

Finds the top n
 hits for query where all results are after a previous
 result (after), allowing control over
 whether hit scores and max score should be computed.

TopDocs
IndexSearcher.searchAfter(ScoreDoc after,
           Query query,
           int n,
           Sort sort)

Finds the top n
 hits for query where all results are after a previous
 result (after).

Overview

Package

Class

Use

Tree

Deprecated

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

          Copyright © 2000-2014 Apache Software Foundation.  All Rights Reserved.


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>hpack::Decoder - Rust</title>

    <link href='http://fonts.googleapis.com/css?family=Oswald:700|Inconsolata:400,700'
          rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="../main.css">

hpack

Structs
Decoder
Encoder
HeaderField

        <form class="search-form js-only">
            <button class="do-search">Search</button>

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Search documentation..."
                       type="search" />

        </form>

[src]
Struct hpack::Decoder

pub struct Decoder {
    // some fields omitted
}

An implementation of an HPACK decoding context for HTTP/2.

Methods

impl Decoder

fn new() -> Decoder

Create an empty decoding context.

fn decode(&mut self, header_block: ~[u8]) -> Option<~HashSet<HeaderField>>

Decode a headerblock into a set of header fields. Return None if a decoding error has occurred.

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

↑

Move up in search results

↓

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct (or str), enum,
                trait, typedef (or
                tdef).


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <stroke android:width="@dimen/auto_dimen2_1" android:color="#ffdde5f0" />
            <solid android:color="@color/auto_color_e5e8eb_90" />
            <corners android:radius="@dimen/auto_dimen2_6" />
        </shape>
    </item>
</layer-list>


text:
@interface WorkFlowTableViewController ()<AddWorkflowTableViewDelegate>
@end

@implementation WorkFlowTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];

    [self getData];
}

-(void)initView{
    self.navigationItem.title = @"工作流";
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.view.backgroundColor = [UIColor blackColor];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(add) image:@"add_workflow"];
    UIView *footerView = [[UIView alloc]init];
    footerView.backgroundColor = self.view.backgroundColor;
    self.tableView.tableFooterView = footerView;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}

//添加工作流程
-(void)add{

    AddWorkflowTableViewController *addWorkflowTableViewController = [[AddWorkflowTableViewController alloc]init];
    addWorkflowTableViewController.delegate = self;
    addWorkflowTableViewController.workFlowDetailArr = self.workFlowDetailArr;
    addWorkflowTableViewController.workFlowDetailArrIndex = self.workFlowDetailArrIndex;
    [self.navigationController pushViewController:addWorkflowTableViewController animated:YES];

}

-(void)addWorkFlowFinish{

    if ([self.workFlowDetailArr count]>0) {
        [self.workFlowDetailArr removeAllObjects];
    }

    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *fileName = [path stringByAppendingPathComponent:@"workFlow.plist"];
    NSArray *array = [NSArray arrayWithContentsOfFile:fileName];
    NSMutableDictionary *dic = [array objectAtIndex:self.workFlowDetailArrIndex];
    NSArray *detailArr = dic[@"array"];

    self.workFlowDetailArr = detailArr;

    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [self.workFlowDetailArr count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *ID = @"workflow";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = [self.workFlowDetailArr objectAtIndex:indexPath.row];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor blackColor];
    [cell setFont:[UIFont fontWithName:@"Helvetica Neue" size:FontSize]];
    return cell;
}

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
//进入编辑模式,按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete){
        [self.workFlowDetailArr removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
            NSString *fileName = [path stringByAppendingPathComponent:@"workFlow.plist"];
            NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:fileName];

            NSMutableDictionary *dic = [array objectAtIndex:self.workFlowDetailArrIndex];
            NSMutableArray *detailArr = dic[@"array"];

            [detailArr removeObjectAtIndex:indexPath.row];
            [dic setObject:detailArr forKey:@"array"];

            [array removeObjectAtIndex:self.workFlowDetailArrIndex];

            [array insertObject:dic atIndex:self.workFlowDetailArrIndex];

            [array writeToFile:fileName atomically:YES];
        });
    }
}

-(NSMutableArray *)workFlowDetailArr{
    if (!_workFlowDetailArr) {
        _workFlowDetailArr = [[NSMutableArray alloc]init];
    }
    return _workFlowDetailArr;
}

//获取数据
-(void)getData{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *fileName = [path stringByAppendingPathComponent:@"workFlow.plist"];

    NSArray *array = [NSArray arrayWithContentsOfFile:fileName];
    NSMutableDictionary *dic = [array objectAtIndex:self.workFlowDetailArrIndex];
    self.workFlowDetailArr = dic[@"array"];
}

-(void)viewDidLayoutSubviews {
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];

    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
@end


text:
package org.homestead.robotics.util;

import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.camera.AxisCamera;
import edu.wpi.first.wpilibj.camera.AxisCameraException;
import edu.wpi.first.wpilibj.image.BinaryImage;
import edu.wpi.first.wpilibj.image.ColorImage;
import edu.wpi.first.wpilibj.image.CriteriaCollection;
import edu.wpi.first.wpilibj.image.NIVision;
import edu.wpi.first.wpilibj.image.NIVisionException;
import edu.wpi.first.wpilibj.image.ParticleAnalysisReport;
import edu.wpi.first.wpilibj.image.RGBImage;

public class Targeter {

    //Camera constants used for distance calculation
    final int Y_IMAGE_RES = 240;		//Y Image resolution in pixels, should be 120, 240 or 480
    //final double VIEW_ANGLE = 49;		//Axis M1013
    final double VIEW_ANGLE = 41.7;		//Axis 206 camera
    //final double VIEW_ANGLE = 37.4;  //Axis M1011 camera
    final double PI = 3.141592653;

    //Score limits used for target identification
    final int  RECTANGULARITY_LIMIT = 40;
    final int ASPECT_RATIO_LIMIT = 40;

    //Score limits used for hot target determination
    final int TAPE_WIDTH_LIMIT = 50;
    final int  VERTICAL_SCORE_LIMIT = 50;
    final int LR_SCORE_LIMIT = 50;

    //Minimum area of particles to be considered
    final int AREA_MINIMUM = 75;

    //Maximum number of particles to process
    final int MAX_PARTICLES = 8;

    AxisCamera camera;          // the axis camera object (connected to the switch)
    CriteriaCollection cc;      // the criteria for doing the particle filter operation

    public class Scores {
        double rectangularity;
        double aspectRatioVertical;
        double aspectRatioHorizontal;
    }

    public class TargetReport {
        int verticalIndex;
        int horizontalIndex;
        boolean Hot;
        double totalScore;
        double leftScore;
        double rightScore;
        double tapeWidthScore;
        double verticalScore;
    }

    public Targeter() {
        camera = AxisCamera.getInstance();  // get an instance of the camera
        cc = new CriteriaCollection();      // create the criteria for the particle filter
        cc.addCriteria(NIVision.MeasurementType.IMAQ_MT_AREA, AREA_MINIMUM, 65535, false);
    }

    // @return distance to hot goal in inches, -1 if goal not hot
    public double act() {
	TargetReport target = new TargetReport();
	int verticalTargets[] = new int[MAX_PARTICLES];
	int horizontalTargets[] = new int[MAX_PARTICLES];
	int verticalTargetCount, horizontalTargetCount;

        try {
            /**
             * Do the image capture with the camera and apply the algorithm described above. This
             * sample will either get images from the camera or from an image file stored in the top
             * level directory in the flash memory on the cRIO. The file name in this case is "testImage.jpg"
             *
             */
            camera.writeResolution(AxisCamera.ResolutionT.k320x240);
            //System.out.println("resolution " +camera.getResolution().width + " " + camera.getResolution().height);
            ColorImage fake = camera.getImage();     // comment if using stored images
            ColorImage image = new RGBImage("/red.png");
            //currently working autonomous code

            //custom reader
            fake.write("/abc.bmp");
            image.write("/test.bmp");
//            ColorImage image;                           // next 2 lines read image from flash on cRIO
//            image = new RGBImage("/redTarg2.PNG");		// get the sample image from the cRIO flash
            //image = new RGBImage("/redTarg2.PNG");
            //image = new RGBImage("/blueTarg.png");

            //(int hueLow, int hueHigh, int saturationLow, int saturationHigh, int valueLow, int valueHigh)
            BinaryImage thresholdImage = fake.thresholdHSV(200, 260, 130, 255, 70, 220);   // keep only red objects
            thresholdImage.write("/threshold.bmp");
            BinaryImage filteredImage = thresholdImage.particleFilter(cc);           // filter out small particles
            //filteredImage.write("/filteredImage.bmp");

            //iterate through each particle and score to see if it is a target
            Scores scores[] = new Scores[filteredImage.getNumberParticles()];
            horizontalTargetCount = verticalTargetCount = 0;

            if(filteredImage.getNumberParticles() > 0)
            {
                for (int i = 0; i < MAX_PARTICLES && i < filteredImage.getNumberParticles(); i++) {
                    ParticleAnalysisReport report = filteredImage.getParticleAnalysisReport(i);
                    scores[i] = new Scores();

                    //Score each particle on rectangularity and aspect ratio
                    scores[i].rectangularity = scoreRectangularity(report);
                    scores[i].aspectRatioVertical = scoreAspectRatio(filteredImage, report, i, true);
                    scores[i].aspectRatioHorizontal = scoreAspectRatio(filteredImage, report, i, false);

                    System.out.println("[r]" + scores[i].rectangularity);
                    System.out.println("[h]" + scores[i].aspectRatioHorizontal);
                    System.out.println("[v]" + scores[i].aspectRatioVertical);

                    //Check if the particle is a horizontal target, if not, check if it's a vertical target
                    if(scoreCompare(scores[i], false))
                    {
                        horizontalTargets[horizontalTargetCount++] = i; //Add particle to target array and increment count
                    } else if (scoreCompare(scores[i], true)) {
                        verticalTargets[verticalTargetCount++] = i;  //Add particle to target array and increment count
                    }
                }

                //Zero out scores and set verticalIndex to first target in case there are no horizontal targets
                target.totalScore = target.leftScore = target.rightScore = target.tapeWidthScore = target.verticalScore = 0;
                target.verticalIndex = verticalTargets[0];
                for (int i = 0; i < verticalTargetCount; i++)
                {
                    ParticleAnalysisReport verticalReport = filteredImage.getParticleAnalysisReport(verticalTargets[i]);
                    System.out.println("horizontalTargetCount = " + horizontalTargetCount);
                    for (int j = 0; j < horizontalTargetCount; j++)
                    {
                        ParticleAnalysisReport horizontalReport = filteredImage.getParticleAnalysisReport(horizontalTargets[j]);
                        double horizWidth, horizHeight, vertWidth, leftScore, rightScore, tapeWidthScore, verticalScore, total;

                        //Measure equivalent rectangle sides for use in score calculation
                        horizWidth = NIVision.MeasureParticle(filteredImage.image, horizontalTargets[j], false, NIVision.MeasurementType.IMAQ_MT_EQUIVALENT_RECT_LONG_SIDE);
                        vertWidth = NIVision.MeasureParticle(filteredImage.image, verticalTargets[i], false, NIVision.MeasurementType.IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE);
                        horizHeight = NIVision.MeasureParticle(filteredImage.image, horizontalTargets[j], false, NIVision.MeasurementType.IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE);

                        //Determine if the horizontal target is in the expected location to the left of the vertical target
                        leftScore = ratioToScore(1.2*(verticalReport.boundingRectLeft - horizontalReport.center_mass_x)/horizWidth);
                        //Determine if the horizontal target is in the expected location to the right of the vertical target
                        rightScore = ratioToScore(1.2*(horizontalReport.center_mass_x - verticalReport.boundingRectLeft - verticalReport.boundingRectWidth)/horizWidth);
                        //Determine if the width of the tape on the two targets appears to be the same
                        tapeWidthScore = ratioToScore(vertWidth/horizHeight);
                        //Determine if the vertical location of the horizontal target appears to be correct
                        System.out.println("verticalReport.boundingRectTop = " + verticalReport.boundingRectTop);
                        System.out.println("horizontalReport.center_mass_y = " + horizontalReport.center_mass_y);
                        System.out.println("horizHeight = " + horizHeight);
                        verticalScore = ratioToScore(1-(verticalReport.boundingRectTop - horizontalReport.center_mass_y)/(4*horizHeight));
                        total = leftScore > rightScore ? leftScore:rightScore;
                        total += tapeWidthScore + verticalScore;

                        //If the target is the best detected so far store the information about it
                        if(total > target.totalScore)
                        {
                            target.horizontalIndex = horizontalTargets[j];
                            target.verticalIndex = verticalTargets[i];
                            target.totalScore = total;
                            target.leftScore = leftScore;
                            target.rightScore = rightScore;
                            target.tapeWidthScore = tapeWidthScore;
                            target.verticalScore = verticalScore;
                        }
                    }
                    //Determine if the best target is a Hot target
                    target.Hot = hotOrNot(target);
                }

                if(verticalTargetCount > 0)
                {
                    //Information about the target is contained in the "target" structure
                    //To get measurement information such as sizes or locations use the
                    //horizontal or vertical index to get the particle report as shown below
                    ParticleAnalysisReport distanceReport = filteredImage.getParticleAnalysisReport(target.verticalIndex);
                    double distance = computeDistance(filteredImage, distanceReport, target.verticalIndex);

                    filteredImage.free();
                    thresholdImage.free();
                    image.free();
                    if(target.Hot)
                    {
                        System.out.println("Hot target located");
                        System.out.println("Distance: " + distance);
                        return distance;
                    } else {
                        System.out.println("No hot target present");
                        //System.out.println("Distance: " + distance);
                        return -1;
                    }
                }
            }

            filteredImage.free();
            thresholdImage.free();
            image.free();

        } catch (AxisCameraException ex) {        // this is needed if the camera.getImage() is called
            ex.printStackTrace();
        }  catch (NIVisionException ex) {
            ex.printStackTrace();
        }

        return -1;
    }

    /**
     * Computes the estimated distance to a target using the height of the particle in the image. For more information and graphics
     * showing the math behind this approach see the Vision Processing section of the ScreenStepsLive documentation.
     *
     * @param image The image to use for measuring the particle estimated rectangle
     * @param report The Particle Analysis Report for the particle
     * @param outer True if the particle should be treated as an outer target, false to treat it as a center target
     * @return The estimated distance to the target in Inches.
     */
    double computeDistance (BinaryImage image, ParticleAnalysisReport report, int particleNumber) throws NIVisionException {
        double rectLong, height;
        int targetHeight;

        rectLong = NIVision.MeasureParticle(image.image, particleNumber, false, NIVision.MeasurementType.IMAQ_MT_EQUIVALENT_RECT_LONG_SIDE);
        //using the smaller of the estimated rectangle long side and the bounding rectangle height results in better performance
        //on skewed rectangles
        height = Math.min(report.boundingRectHeight, rectLong);
        targetHeight = 32;

        return Y_IMAGE_RES * targetHeight / (height * 12 * 2 * Math.tan(VIEW_ANGLE*Math.PI/(180*2)));
    }

    /**
     * Computes a score (0-100) comparing the aspect ratio to the ideal aspect ratio for the target. This method uses
     * the equivalent rectangle sides to determine aspect ratio as it performs better as the target gets skewed by moving
     * to the left or right. The equivalent rectangle is the rectangle with sides x and y where particle area= x*y
     * and particle perimeter= 2x+2y
     *
     * @param image The image containing the particle to score, needed to perform additional measurements
     * @param report The Particle Analysis Report for the particle, used for the width, height, and particle number
     * @param outer	Indicates whether the particle aspect ratio should be compared to the ratio for the inner target or the outer
     * @return The aspect ratio score (0-100)
     */
    public double scoreAspectRatio(BinaryImage image, ParticleAnalysisReport report, int particleNumber, boolean vertical) throws NIVisionException
    {
        double rectLong, rectShort, aspectRatio, idealAspectRatio;

        rectLong = NIVision.MeasureParticle(image.image, particleNumber, false, NIVision.MeasurementType.IMAQ_MT_EQUIVALENT_RECT_LONG_SIDE);
        rectShort = NIVision.MeasureParticle(image.image, particleNumber, false, NIVision.MeasurementType.IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE);
        idealAspectRatio = vertical ? (4.0/32) : (23.5/4);	//Vertical reflector 4" wide x 32" tall, horizontal 23.5" wide x 4" tall

        //Divide width by height to measure aspect ratio
        if(report.boundingRectWidth > report.boundingRectHeight){
            //particle is wider than it is tall, divide long by short
            aspectRatio = ratioToScore((rectLong/rectShort)/idealAspectRatio);
        } else {
            //particle is taller than it is wide, divide short by long
            aspectRatio = ratioToScore((rectShort/rectLong)/idealAspectRatio);
        }
	return aspectRatio;
    }

    /**
     * Compares scores to defined limits and returns true if the particle appears to be a target
     *
     * @param scores The structure containing the scores to compare
     * @param outer True if the particle should be treated as an outer target, false to treat it as a center target
     *
     * @return True if the particle meets all limits, false otherwise
     */
    boolean scoreCompare(Scores scores, boolean vertical){
	boolean isTarget = true;

	isTarget &= scores.rectangularity > RECTANGULARITY_LIMIT;
	if(vertical){
            isTarget &= scores.aspectRatioVertical > ASPECT_RATIO_LIMIT;
	} else {
            isTarget &= scores.aspectRatioHorizontal > ASPECT_RATIO_LIMIT;
	}

	return isTarget;
    }

    /**
     * Computes a score (0-100) estimating how rectangular the particle is by comparing the area of the particle
     * to the area of the bounding box surrounding it. A perfect rectangle would cover the entire bounding box.
     *
     * @param report The Particle Analysis Report for the particle to score
     * @return The rectangularity score (0-100)
     */
    double scoreRectangularity(ParticleAnalysisReport report){
        if(report.boundingRectWidth*report.boundingRectHeight !=0){
            return 100*report.particleArea/(report.boundingRectWidth*report.boundingRectHeight);
        } else {
            return 0;
        }
    }

    /**
     * Converts a ratio with ideal value of 1 to a score. The resulting function is piecewise
     * linear going from (0,0) to (1,100) to (2,0) and is 0 for all inputs outside the range 0-2
     */
    double ratioToScore(double ratio)
    {
        return (Math.max(0, Math.min(100*(1-Math.abs(1-ratio)), 100)));
    }

    /**
     * Takes in a report on a target and compares the scores to the defined score limits to evaluate
     * if the target is a hot target or not.
     *
     * Returns True if the target is hot. False if it is not.
     */
    boolean hotOrNot(TargetReport target)
    {
        boolean isHot = true;

        isHot &= target.tapeWidthScore >= TAPE_WIDTH_LIMIT;
        System.out.println("tape width " + target.tapeWidthScore);

        //problem!!
        isHot &= target.verticalScore >= VERTICAL_SCORE_LIMIT;
        System.out.println("vertical score " + target.verticalScore+" and the limit is: "+ this.VERTICAL_SCORE_LIMIT);

        isHot &= (target.leftScore > LR_SCORE_LIMIT) | (target.rightScore > LR_SCORE_LIMIT);
        System.out.println("left score " + target.leftScore);
        System.out.println("right score " + target.rightScore);

        return isHot;
    }
}


text:
std::string lastword(const std::string& input)
{
    const std::string firstLetter       = {input[0]};
    const std::string inputWithoutFirst = {std::next(input.begin()), input.end()};

    std::string result;
    result = firstLetter;

    for (auto& letter : inputWithoutFirst)
    {
        std::vector<std::string> newResults;
        newResults.push_back(result + letter);
        newResults.push_back(letter + result);
        std::sort(newResults.begin(), newResults.end());
        result = *newResults.rbegin();
    }

    return result;
}


text:
cp -R "$WEB_SRC_ROOT/" "$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/"
for f in `find "$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH" -name '*.html' -o -name '*.js' -o -name '*.css' -o -name '*.a' `; do rm -rf "$f"; done
/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/iphoneos-optimize "$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/"
find "$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/" -type d -empty -delete


text:
namespace System.ServiceModel
{
    using System;
    using System.Text;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Configuration;
    using System.Globalization;
    using System.Net;
    using System.Net.Security;
    using System.Runtime.Serialization;
    using System.Security.Principal;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Configuration;
    using System.ServiceModel.Security;
    using System.ComponentModel;
    using System.Xml;

    public abstract class WSHttpBindingBase : Binding, IBindingRuntimePreferences
    {
        WSMessageEncoding messageEncoding;
        OptionalReliableSession reliableSession;
        // private BindingElements
        HttpTransportBindingElement httpTransport;
        HttpsTransportBindingElement httpsTransport;
        TextMessageEncodingBindingElement textEncoding;
        MtomMessageEncodingBindingElement mtomEncoding;
        TransactionFlowBindingElement txFlow;
        ReliableSessionBindingElement session;

        protected WSHttpBindingBase()
            : base()
        {
            Initialize();
        }

        protected WSHttpBindingBase(bool reliableSessionEnabled)
            : this()
        {
            this.ReliableSession.Enabled = reliableSessionEnabled;
        }

        [DefaultValue(HttpTransportDefaults.BypassProxyOnLocal)]
        public bool BypassProxyOnLocal
        {
            get { return httpTransport.BypassProxyOnLocal; }
            set
            {
                httpTransport.BypassProxyOnLocal = value;
                httpsTransport.BypassProxyOnLocal = value;
            }
        }

        [DefaultValue(false)]
        public bool TransactionFlow
        {
            get { return this.txFlow.Transactions; }
            set { this.txFlow.Transactions = value; }
        }

        [DefaultValue(HttpTransportDefaults.HostNameComparisonMode)]
        public HostNameComparisonMode HostNameComparisonMode
        {
            get { return httpTransport.HostNameComparisonMode; }
            set
            {
                httpTransport.HostNameComparisonMode = value;
                httpsTransport.HostNameComparisonMode = value;
            }
        }

        [DefaultValue(TransportDefaults.MaxBufferPoolSize)]
        public long MaxBufferPoolSize
        {
            get { return httpTransport.MaxBufferPoolSize; }
            set
            {
                httpTransport.MaxBufferPoolSize = value;
                httpsTransport.MaxBufferPoolSize = value;
            }
        }

        [DefaultValue(TransportDefaults.MaxReceivedMessageSize)]
        public long MaxReceivedMessageSize
        {
            get { return httpTransport.MaxReceivedMessageSize; }
            set
            {
                if (value > int.MaxValue)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new ArgumentOutOfRangeException("value.MaxReceivedMessageSize",
                        SR.GetString(SR.MaxReceivedMessageSizeMustBeInIntegerRange)));
                }
                httpTransport.MaxReceivedMessageSize = value;
                httpsTransport.MaxReceivedMessageSize = value;
                mtomEncoding.MaxBufferSize = (int)value;
            }
        }

        [DefaultValue(WSHttpBindingDefaults.MessageEncoding)]
        public WSMessageEncoding MessageEncoding
        {
            get { return messageEncoding; }
            set { messageEncoding = value; }
        }

        [DefaultValue(HttpTransportDefaults.ProxyAddress)]
        [TypeConverter(typeof(UriTypeConverter))]
        public Uri ProxyAddress
        {
            get { return httpTransport.ProxyAddress; }
            set
            {
                httpTransport.ProxyAddress = value;
                httpsTransport.ProxyAddress = value;
            }
        }

        public XmlDictionaryReaderQuotas ReaderQuotas
        {
            get { return textEncoding.ReaderQuotas; }
            set
            {
                if (value == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
                value.CopyTo(textEncoding.ReaderQuotas);
                value.CopyTo(mtomEncoding.ReaderQuotas);
            }
        }

        public OptionalReliableSession ReliableSession
        {
            get { return reliableSession; }
            set
            {
                if (value == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
                }
                this.reliableSession.CopySettings(value);
            }
        }

        public override string Scheme { get { return GetTransport().Scheme; } }

        public EnvelopeVersion EnvelopeVersion
        {
            get { return EnvelopeVersion.Soap12; }
        }

        [TypeConverter(typeof(EncodingConverter))]
        public System.Text.Encoding TextEncoding
        {
            get { return textEncoding.WriteEncoding; }
            set
            {
                textEncoding.WriteEncoding = value;
                mtomEncoding.WriteEncoding = value;
            }
        }

        [DefaultValue(HttpTransportDefaults.UseDefaultWebProxy)]
        public bool UseDefaultWebProxy
        {
            get { return httpTransport.UseDefaultWebProxy; }
            set
            {
                httpTransport.UseDefaultWebProxy = value;
                httpsTransport.UseDefaultWebProxy = value;
            }
        }

        bool IBindingRuntimePreferences.ReceiveSynchronously
        {
            get { return false; }
        }

        internal HttpTransportBindingElement HttpTransport
        {
            get { return httpTransport; }
        }

        internal HttpsTransportBindingElement HttpsTransport
        {
            get { return httpsTransport; }
        }

        internal ReliableSessionBindingElement ReliableSessionBindingElement
        {
            get { return session; }
        }

        internal TransactionFlowBindingElement TransactionFlowBindingElement
        {
            get { return txFlow; }
        }

        static TransactionFlowBindingElement GetDefaultTransactionFlowBindingElement()
        {
            TransactionFlowBindingElement tfbe = new TransactionFlowBindingElement(false);
            tfbe.TransactionProtocol = TransactionProtocol.WSAtomicTransactionOctober2004;
            return tfbe;
        }

        void Initialize()
        {
            httpTransport = new HttpTransportBindingElement();
            httpsTransport = new HttpsTransportBindingElement();
            messageEncoding = WSHttpBindingDefaults.MessageEncoding;
            txFlow = GetDefaultTransactionFlowBindingElement();
            session = new ReliableSessionBindingElement(true);
            textEncoding = new TextMessageEncodingBindingElement();
            textEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10;
            mtomEncoding = new MtomMessageEncodingBindingElement();
            mtomEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10;
            reliableSession = new OptionalReliableSession(session);
        }

        void InitializeFrom(HttpTransportBindingElement transport, MessageEncodingBindingElement encoding, TransactionFlowBindingElement txFlow, ReliableSessionBindingElement session)
        {
            // transport
            this.BypassProxyOnLocal = transport.BypassProxyOnLocal;
            this.HostNameComparisonMode = transport.HostNameComparisonMode;
            this.MaxBufferPoolSize = transport.MaxBufferPoolSize;
            this.MaxReceivedMessageSize = transport.MaxReceivedMessageSize;
            this.ProxyAddress = transport.ProxyAddress;
            this.UseDefaultWebProxy = transport.UseDefaultWebProxy;

            // this binding only supports Text and Mtom encoding
            if (encoding is TextMessageEncodingBindingElement)
            {
                this.MessageEncoding = WSMessageEncoding.Text;
                TextMessageEncodingBindingElement text = (TextMessageEncodingBindingElement)encoding;
                this.TextEncoding = text.WriteEncoding;
                this.ReaderQuotas = text.ReaderQuotas;

            }
            else if (encoding is MtomMessageEncodingBindingElement)
            {
                messageEncoding = WSMessageEncoding.Mtom;
                MtomMessageEncodingBindingElement mtom = (MtomMessageEncodingBindingElement)encoding;
                this.TextEncoding = mtom.WriteEncoding;
                this.ReaderQuotas = mtom.ReaderQuotas;
            }
            this.TransactionFlow = txFlow.Transactions;
            this.reliableSession.Enabled = session != null;

            //session
            if (session != null)
            {
                // only set properties that have standard binding manifestations
                this.session.InactivityTimeout = session.InactivityTimeout;
                this.session.Ordered = session.Ordered;
            }
        }

        // check that properties of the HttpTransportBindingElement and
        // MessageEncodingBindingElement not exposed as properties on BasicHttpBinding
        // match default values of the binding elements
        bool IsBindingElementsMatch(HttpTransportBindingElement transport, MessageEncodingBindingElement encoding, TransactionFlowBindingElement txFlow, ReliableSessionBindingElement session)
        {

            if (!this.GetTransport().IsMatch(transport))
                return false;
            if (this.MessageEncoding == WSMessageEncoding.Text)
            {
                if (!this.textEncoding.IsMatch(encoding))
                    return false;
            }
            else if (this.MessageEncoding == WSMessageEncoding.Mtom)
            {
                if (!this.mtomEncoding.IsMatch(encoding))
                    return false;
            }
            if (!this.txFlow.IsMatch(txFlow))
                return false;

            if (reliableSession.Enabled)
            {
                if (!this.session.IsMatch(session))
                    return false;
            }
            else if (session != null)
            {
                return false;
            }

            return true;
        }

        public override BindingElementCollection CreateBindingElements()
        {   // return collection of BindingElements
            BindingElementCollection bindingElements = new BindingElementCollection();
            // order of BindingElements is important
            // context

            bindingElements.Add(txFlow);
            // reliable
            if (reliableSession.Enabled)
            {
                bindingElements.Add(session);
            }

            // add security (*optional)
            SecurityBindingElement wsSecurity = this.CreateMessageSecurity();
            if (wsSecurity != null)
            {
                bindingElements.Add(wsSecurity);
            }

            // add encoding (text or mtom)
            WSMessageEncodingHelper.SyncUpEncodingBindingElementProperties(textEncoding, mtomEncoding);
            if (this.MessageEncoding == WSMessageEncoding.Text)
                bindingElements.Add(textEncoding);
            else if (this.MessageEncoding == WSMessageEncoding.Mtom)
                bindingElements.Add(mtomEncoding);

            // add transport (http or https)
            bindingElements.Add(GetTransport());

            return bindingElements.Clone();
        }

        internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
        {
            binding = null;
            if (elements.Count > 6)
                return false;

            // collect all binding elements
            PrivacyNoticeBindingElement privacy = null;
            TransactionFlowBindingElement txFlow = null;
            ReliableSessionBindingElement session = null;
            SecurityBindingElement security = null;
            MessageEncodingBindingElement encoding = null;
            HttpTransportBindingElement transport = null;

            foreach (BindingElement element in elements)
            {
                if (element is SecurityBindingElement)
                    security = element as SecurityBindingElement;
                else if (element is TransportBindingElement)
                    transport = element as HttpTransportBindingElement;
                else if (element is MessageEncodingBindingElement)
                    encoding = element as MessageEncodingBindingElement;
                else if (element is TransactionFlowBindingElement)
                    txFlow = element as TransactionFlowBindingElement;
                else if (element is ReliableSessionBindingElement)
                    session = element as ReliableSessionBindingElement;
                else if (element is PrivacyNoticeBindingElement)
                    privacy = element as PrivacyNoticeBindingElement;
                else
                    return false;
            }

            if (transport == null)
                return false;
            if (encoding == null)
                return false;

            if (!transport.AuthenticationScheme.IsSingleton())
            {
                //multiple authentication schemes selected -- not supported in StandardBindings
                return false;
            }

            HttpsTransportBindingElement httpsTransport = transport as HttpsTransportBindingElement;
            if ( ( security != null ) && ( httpsTransport != null ) && ( httpsTransport.RequireClientCertificate != TransportDefaults.RequireClientCertificate ) )
            {
                return false;
            }

            if (null != privacy || !WSHttpBinding.TryCreate(security, transport, session, txFlow, out binding))
                if (!WSFederationHttpBinding.TryCreate(security, transport, privacy, session, txFlow, out binding))
                    if (!WS2007HttpBinding.TryCreate(security, transport, session, txFlow, out binding))
                        if (!WS2007FederationHttpBinding.TryCreate(security, transport, privacy, session, txFlow, out binding))
                            return false;

            if (txFlow == null)
            {
                txFlow = GetDefaultTransactionFlowBindingElement();
                if ((binding is WS2007HttpBinding) || (binding is WS2007FederationHttpBinding))
                {
                    txFlow.TransactionProtocol = TransactionProtocol.WSAtomicTransaction11;
                }
            }

            WSHttpBindingBase wSHttpBindingBase = binding as WSHttpBindingBase;
            wSHttpBindingBase.InitializeFrom(transport, encoding, txFlow, session);
            if (!wSHttpBindingBase.IsBindingElementsMatch(transport, encoding, txFlow, session))
                return false;

            return true;
        }

        protected abstract TransportBindingElement GetTransport();
        protected abstract SecurityBindingElement CreateMessageSecurity();

        [EditorBrowsable(EditorBrowsableState.Never)]
        public bool ShouldSerializeReaderQuotas()
        {
            return (!EncoderDefaults.IsDefaultReaderQuotas(this.ReaderQuotas));
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public bool ShouldSerializeTextEncoding()
        {
            return (!this.TextEncoding.Equals(TextEncoderDefaults.Encoding));
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public bool ShouldSerializeReliableSession()
        {
            return this.ReliableSession.Ordered != ReliableSessionDefaults.Ordered
                || this.ReliableSession.InactivityTimeout != ReliableSessionDefaults.InactivityTimeout
                || this.ReliableSession.Enabled != ReliableSessionDefaults.Enabled;
        }
    }
}


text:
package org.jbpm.formModeler.core.processing.formRendering;

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

public class RenderFieldInstruction extends TemplateRenderingInstruction {
    private static transient Logger log = LoggerFactory.getLogger(RenderFieldInstruction.class);

    private String fieldName;

    public RenderFieldInstruction(String fieldName) {
        this.fieldName = fieldName;
    }

    public void doRender(FormRenderer renderer) {
        renderer.renderField(fieldName);
    }
}


text:
import os
import pandas as pd
import numpy as np

from .. import utils

from zipline.utils.calendars import get_calendar
from zipline.data.data_portal import DataPortal
from zipline.data.history_loader import MinuteHistoryLoader

from sqlalchemy import (
    create_engine,
    select, and_,
    Table,
    MetaData,
    Column,
    Integer,
    String
)

from zipline.data.minute_bars import MinuteBarReader

OHLCVP_FIELDS = frozenset([
    "open", "high", "low", "close", "volume", "price"
])

VOLUME_MULTIPLIER = 1000000000

class SqlDataPortal(DataPortal):

    def __init__(self, minute_reader, asset_finder):
        self.asset_finder = asset_finder
        self.minute_reader = minute_reader
        self.minute_reader.load_data_cache([37])

        self._adjustment_reader = None

        self.trading_calendar = minute_reader.trading_calendar
        self._minute_history_loader = MinuteHistoryLoader(self.trading_calendar,
                                                          minute_reader,
                                                          None)

        self._first_trading_minute = self.trading_calendar.schedule.iloc[0]['market_open'].tz_localize("UTC")

    def get_spot_value(self, asset, field, dt, data_frequency):
        if data_frequency == 'daily':
            raise "Unimplemented"
        elif data_frequency == 'minute':
            return self.minute_reader.get_value(asset.sid,
                                                dt,
                                                field)

class SqlMinuteReader(MinuteBarReader):
    def __init__(self, db_url, trading_calendar=None):
        echo = os.environ.get("SQL_ECHO", False) == 'true'
        self.engine = create_engine(db_url,
                                    echo=echo)
        self.trading_calendar = trading_calendar or get_calendar("NYSE")

    def load_data_cache(self, sids, start=None, end=None):
        self._cache = {}
        if start is None:
            start = self.trading_calendar.opens()[0]  # Pending PR to remove method call
        if end is None:
            end = self.trading_calendar.closes[1]
        for s in sids:
            symbol = utils.symbol(s)
            s_table = table(symbol)
            query = select([s_table]) \
                        .where(
                            and_(
                                s_table.c.datetime >= start,
                                s_table.c.datetime <= end
                            )
                        ).order_by(s_table.c.datetime)

            self._cache[s] = pd.read_sql(query,
                                         self.engine,
                                         index_col='datetime',
                                         parse_dates=['datetime'])

    @property
    def days_of_data(self):
        return [v for (_, v) in self._cache.items()][0].index

    @property
    def last_available_dt(self):
        s = self.days_of_data[-1].tz_localize("UTC") \
                .replace(hour=0, minute=0)
        (_, close) = self.trading_calendar.open_and_close_for_session(s)
        return close

    @property
    def first_trading_day(self):
        return self.days_of_data[0]

    @property
    def get_last_traded_dt(self, asset, dt):
        return self.days_of_data[-1]

    def get_value(self, sid, dt, field):
        if field == 'price':
            field = 'close'
        try:
            val = self._cache[sid].ix[dt, field]
        except KeyError:
            if field == 'volume':
                return 0
            else:
                return np.nan
        if field == 'volume':
            return int(val) * VOLUME_MULTIPLIER
        else:
            return int(val) * utils.float_multiplier(sid)

    def load_raw_arrays(self, fields, start_dt, end_dt, sids):
        """
        Parameters
        ----------
        fields : list of str
           'open', 'high', 'low', 'close', or 'volume'
        start_dt: Timestamp
           Beginning of the window range.
        end_dt: Timestamp
           End of the window range.
        sids : list of int
           The asset identifiers in the window.

        Returns
        -------
        list of np.ndarray
            A list with an entry per field of ndarrays with shape
            (minutes in range, sids) with a dtype of float64, containing the
            values for the respective field over start and end dt range.
        """
        results = []
        # index = self._cache[sids[0]].index
        # interested_period = index[start_dt:end_dt]

        for field in fields:
            df = pd.DataFrame()
            for s in sids:
                df[s] = self._cache[s][start_dt:end_dt][field].copy()
            if field != 'volume':
                df[s] = df[s] * utils.float_multiplier(s)
            else:
                df[s] = df[s] * VOLUME_MULTIPLIER
            results.append(df.as_matrix())

        return results

def table(symbol):
    metadata = MetaData()
    return Table('minute_bars_{}'.format(symbol), metadata,
                 Column('datetime', String(30), primary_key=True),
                 Column('open', Integer, nullable=False),
                 Column('high', Integer, nullable=False),
                 Column('low', Integer, nullable=False),
                 Column('close', Integer, nullable=False),
                 Column('volume', Integer, nullable=False))


text:
These classes define the several useful utilities used
throughout the router and applications.


text:
class TVectorRenderData;
class TVectorImageP;
class TRasterImageP;

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

class DVAPI TGLContextManager
{
public:
	virtual void store() = 0;
	virtual void restore() = 0;
};

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

class DVAPI TOfflineGL
{

public:
	class Imp
	{
	protected:
		int m_lx, m_ly;

	public:
		Imp(int lx, int ly) : m_lx(lx), m_ly(ly) {}
		virtual ~Imp(){};
		virtual void makeCurrent() = 0;
		virtual void doneCurrent() = 0; // Da implementare in Imp
		virtual void createContext(TDimension rasterSize, std::shared_ptr<Imp> shared) = 0;
		virtual void getRaster(TRaster32P) = 0;
		virtual int getLx() const { return m_lx; }
		virtual int getLy() const { return m_ly; }
	};
	typedef std::shared_ptr<Imp> ImpGenerator(const TDimension &dim, std::shared_ptr<Imp> shared);
	static ImpGenerator *defineImpGenerator(ImpGenerator *impGenerator);

	TOfflineGL(TDimension dim, const TOfflineGL *shared = 0);
	TOfflineGL(const TRaster32P &raster, const TOfflineGL *shared = 0);

	~TOfflineGL();

	void makeCurrent();
	void doneCurrent();

	static void setContextManager(TGLContextManager *contextManager);

	void initMatrix();

	void clear(TPixel32 color);

	void draw(TVectorImageP image, const TVectorRenderData &rd, bool doInitMatrix = false);

	void draw(TRasterImageP image, const TAffine &aff, bool doInitMatrix = false);

	void flush();

	TRaster32P getRaster(); // Ritorna il raster copiandolo dal buffer offline
	void getRaster(TRaster32P raster);
	void getRaster(TRasterP raster);

	int getLx() const;
	int getLy() const;
	TDimension getSize() const { return TDimension(getLx(), getLy()); };
	TRect getBounds() const { return TRect(0, 0, getLx() - 1, getLy() - 1); };

	static TOfflineGL *getStock(TDimension dim);
	// si usa cosi': TOfflineGL *ogl = TOfflineGL::getStock(d);
	// non bisogna liberare ogl
	std::shared_ptr<Imp> m_imp;

private:
private:
	// not implemented
	TOfflineGL(const TOfflineGL &);
	TOfflineGL &operator=(const TOfflineGL &);
};

#endif


text:
/*
 * Varian,Inc. All Rights Reserved.
 * This software contains proprietary and confidential
 * information of Varian, Inc. and its contributors.
 * Use, disclosure and reproduction is prohibited without
 * prior consent.
 */
/* DISCLAIMER :
     * ------------
     *
 * This is a beta version of the GALAXIE integration library.
 * This code is under development and is provided for information purposes.
 * The classes names and interfaces as well as the file names and
 * organization is subject to changes. Moreover, this code has not been
 * fully tested.
 *
 * For any bug report, comment or suggestion please send an email to
 * gilles.orazi@varianinc.com
 *
 * Copyright Varian JMBS (2002)
 */

// $History: owninglist.cpp $
/*  */
/* *****************  Version 4  ***************** */
/* User: Go           Date: 16/10/02   Time: 16:20 */
/* Updated in $/Orlando_2000/DLL_Integration/Cpp */
/* backup */
/*  */
/* *****************  Version 3  ***************** */
/* User: Go           Date: 9/10/02    Time: 9:53 */
/* Updated in $/Orlando_2000/DLL_Integration/Cpp */
/* backup */
/*  */
/* *****************  Version 2  ***************** */
/* User: Go           Date: 2/07/02    Time: 14:55 */
/* Updated in $/Orlando_2000/DLL_Integration/Cpp */

#include "owninglist.h"
#include <algorithm>

template<class T>
OwningList<T>::OwningList()
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
//nothing for the moment...
}

template<class T>
OwningList<T>::~OwningList()
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
    clear();
}

template<class T>
int OwningList<T>::size()
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
    return _list.size();
}

template<class T>
T& OwningList<T>::operator[] (int i)
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
    return *(_list[i]);
}

template<class T>
T& OwningList<T>::push_back()
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
    T* newitem = new T ;
    _list.push_back(newitem);
    return *newitem ;
}

template<class T>
T& OwningList<T>::push_back(T& item)
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
    _list.push_back(&item);
    return item;
}

template<class T>
void OwningList<T>::pop_back()
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
    erase(back()) ;
}

template<class T>
T& OwningList<T>::front()
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
    return *(_list.front());
}

template<class T>
T& OwningList<T>::back()
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
    return *(_list.back());
}

template<class T>
void OwningList<T>::erase(T& item)
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
    typename _type_list::iterator item_it = find(_list.begin(), _list.end(), &item);
    if (item_it != _list.end()) _list.erase(item_it);
    delete &item;
}

template<class T>
void OwningList<T>::erase(int index)
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
    typename _type_list::iterator it_item = _list.begin()+index ;
    T* pitem = *it_item;
    _list.erase(it_item);
    delete pitem;
}

template<class T>
int OwningList<T>::indexof(T& item)
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
    typename _type_list::iterator it = find(_list.begin(), _list.end(), &item);
    if (it!=_list.end())
        return it - _list.begin();
    else
        return -1 ;
}

template<class T>
void OwningList<T>::clear()
/* --------------------------
     * Author  : Gilles Orazi
 * Created : 06/2002
 * Purpose :
 * History :
 * -------------------------- */
{
    for_each(_list.begin(), _list.end(), _delete_owned_object());
    _list.clear();
}

// template<class T>
// iterator OwningList::begin()
// {
//   return _list.begin();
// }

// template<class T>
// iterator OwningList::end()
// {
//   return _list.end();
// }


text:
module Pump
  class AbstractApplication
    attr_reader :socket_path, :app_path

    def self.get_instance(app_path)
      @@apps ||= Hash.new
      @@apps[app_path] ||= new(app_path)
      debug "Got instance of application #{app_path}"
      @@apps[app_path]
    end

    def initialize(app_path)
      @app_path, @socket_path = app_path, File.join(PUMP_ROOT, "var", "run", "#{File.basename(app_path)}.sock")
      fork_app
    end

    def service(req, res)
      fork_app unless File.exist?(socket_path)
      socket = UNIXSocket.open(socket_path)

      env = req.meta_vars
      env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
      env["QUERY_STRING"] ||= ""
      unless env["PATH_INFO"] == ""
        path, n = req.request_uri.path, env["SCRIPT_NAME"].length
        env["PATH_INFO"] = path[n, path.length-n]
      end
      env["REQUEST_PATH"] ||= [env["SCRIPT_NAME"], env["PATH_INFO"]].join
      env["body"] = req.body.to_s

      socket.send Marshal.dump(env), 0

      data = receive_data(socket)
      debug "Response size: #{data.size}"

      status, headers, body = Marshal.load(data)

      res.status = status
      headers.each do |k, vs|
        if k.downcase == "set-cookie"
          res.cookies.concat vs.split("\n")
        else
          # Since WEBrick won't accept repeated headers,
          # merge the values per RFC 1945 section 4.2.
          res[k] = vs.split("\n").join(", ")
        end
      end
      res.body = body
    end

    def fork_app
      debug "Creating #{socket_path} socket"
      server_socket = UNIXServer.new(socket_path)

      debug "Forking new application"
      fork do
        args = Pump.pumpup_path, app_path, server_socket.fileno, socket_path
        if defined?(RVM)
          rvm_string = RVM.tools.path_identifier(app_path)
          RVM::Environment.new(rvm_string).exec(args)
        else
          exec(args)
        end
      end

      server_socket.close
    end

    def receive_data(socket, buffer = "")
      loop do
        part = socket.recv(1024)
        break if part.empty?
        buffer << part
      end
      buffer
    end
  end
end


text:
<?php

/** @var \Magento\Translation\Model\ResourceModel\StringUtils $translateString */
$translateString = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
    'Magento\Translation\Model\ResourceModel\StringUtils'
);
$translateString->saveTranslate('Fixture String', 'Fixture Db Translation');


text:
module Azure::ARM::Compute
  module Models
    #
    # Defines values for VirtualMachineScaleSetSkuScaleType
    #
    module VirtualMachineScaleSetSkuScaleType
      Automatic = "Automatic"
      None = "None"
    end
  end
end


text:
- [WWCode Algorithms and Interview Prep Resources] (http://meetupresources.herokuapp.com/whiteboard.html)
- [Interview Questions] (http://kelukelu.me/interview/questions.html)
- [A Guide to the CS Interview from a Khan Academy Student] (https://github.com/jdsutton/Technical-Interview-Megarepo)
- [Google Code Jam] (https://code.google.com/codejam/)
- [Hacker Rank] (https://www.hackerrank.com/domains/algorithms/warmup)
- [Big-0 Cheat Sheet] (http://bigocheatsheet.com/)
- Slides: [Technical Interviewing] (https://speakerdeck.com/rjz/technical-interviewing)


text:
#owl {
	width: 98.6%;
	max-width: 640px;
	max-height: 310px;
	margin: 0 auto;
	overflow: hidden;
}

#owl .item {
	display: block;
}

#owl img {
	display: block;
	width: 98.6%;
}

.owl-carousel .owl-wrapper:after {
	content: ".";
	display: block;
	clear: both;
	visibility: hidden;
	line-height: 0;
	height: 0;
}

.owl-carousel {
	display: none;
	position: relative;
	-ms-touch-action: pan-y;
}

.owl-carousel .owl-wrapper {
	display: none;
	position: relative;
	-webkit-transform: translate3d(0px, 0px, 0px);
}

.owl-carousel .owl-wrapper-outer {
	overflow: hidden;
	position: relative;
	width: 100%;
}

.owl-carousel .owl-wrapper-outer.autoHeight {
	-webkit-transition: height 500ms ease-in-out;
	-moz-transition: height 500ms ease-in-out;
	-ms-transition: height 500ms ease-in-out;
	-o-transition: height 500ms ease-in-out;
	transition: height 500ms ease-in-out;
}

.owl-carousel .owl-item {
	float: left;
}

.owl-controls .owl-page, .owl-controls .owl-buttons div {
	cursor: pointer;
}

.owl-controls {
	-webkit-user-select: none;
	-khtml-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
	-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}

.grabbing {
	cursor: url(grabbing.png) 8 8, move;
}

/* fix */
.owl-carousel  .owl-wrapper, .owl-carousel  .owl-item {
	-webkit-backface-visibility: hidden;
	-moz-backface-visibility: hidden;
	-ms-backface-visibility: hidden;
	-webkit-transform: translate3d(0, 0, 0);
	-moz-transform: translate3d(0, 0, 0);
	-ms-transform: translate3d(0, 0, 0);
}

.owl-theme .owl-controls {
	text-align: center;
	margin-top: 0px;
}

.owl-theme .owl-controls .owl-buttons div {
	color: #FFF;
	display: inline-block;
	zoom: 1;
	*display: inline; /*IE7 life-saver */
	margin: 5px;
	padding: 3px 10px;
	font-size: 12px;
	-webkit-border-radius: 50%;
	-moz-border-radius: 50%;
	border-radius: 50%;
	filter: Alpha(Opacity = 50); /*IE7 fix*/
	opacity: 0.5;
	background-color: #FF0000;
}

.owl-theme .owl-controls.clickable .owl-buttons div:hover {
	filter: Alpha(Opacity = 100); /*IE7 fix*/
	opacity: 1;
	text-decoration: none;
}

.owl-theme .owl-controls .owl-page {
	display: inline-block;
	zoom: 1;
	*display: inline; /*IE7 life-saver */
}

.owl-theme .owl-controls .owl-page span {
	display: block;
	width: 8px;
	height: 8px;
	margin: 5px 7px;
	filter: Alpha(Opacity = 50); /*IE7 fix*/
	opacity: 0.5;
	-webkit-border-radius: 50%;
	-moz-border-radius: 50%;
	border-radius: 50%;
	overflow: hidden;
	background-color: #7fc242;
}

.owl-theme .owl-controls .owl-page.active span, .owl-theme .owl-controls.clickable .owl-page:hover span
	{
	filter: Alpha(Opacity = 100); /*IE7 fix*/
	opacity: 1;
}

/* If PaginationNumbers is true */
.owl-theme .owl-controls .owl-page span.owl-numbers {
	height: auto;
	width: auto;
	color: #FFF;
	padding: 2px 10px;
	font-size: 12px;
	-webkit-border-radius: 30px;
	-moz-border-radius: 30px;
	border-radius: 30px;
}

/* preloading images */
.owl-item.loading {
	min-height: 150px;
	background: url(../images/loading.gif) no-repeat center center
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfGuidesProject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <GuidesProject>
    <Project>HeroinePanel</Project>
    <GuidesList />
  </GuidesProject>
  <GuidesProject>
    <Project>HeartLovePanel</Project>
    <GuidesList />
  </GuidesProject>
  <GuidesProject>
    <Project>BarLovePanel</Project>
    <GuidesList />
  </GuidesProject>
</ArrayOfGuidesProject>


text:
package br.eti.hmagalhaes.bomclima.model.entity;

public class TemperaturaPrevista extends MedicaoPrevista implements TemperaturaMensuravel {

	private float temperaturaEmCelcius;

	public float getTemperaturaEmCelcius() {
		return temperaturaEmCelcius;
	}

	public void setTemperaturaEmCelcius(float temperaturaEmCelcius) {
		this.temperaturaEmCelcius = temperaturaEmCelcius;
	}
}


text:
<?php

namespace Symfony\Component\Ldap\Adapter\ExtLdap;

use Symfony\Component\Ldap\Adapter\AdapterInterface;
use Symfony\Component\Ldap\Exception\LdapException;

/**
 * @author Charles Sarrazin <charles@sarraz.in>
 */
class Adapter implements AdapterInterface
{
    private $config;
    private $connection;
    private $entryManager;

    public function __construct(array $config = [])
    {
        if (!\extension_loaded('ldap')) {
            throw new LdapException('The LDAP PHP extension is not enabled.');
        }

        $this->config = $config;
    }

    /**
     * {@inheritdoc}
     */
    public function getConnection()
    {
        if (null === $this->connection) {
            $this->connection = new Connection($this->config);
        }

        return $this->connection;
    }

    /**
     * {@inheritdoc}
     */
    public function getEntryManager()
    {
        if (null === $this->entryManager) {
            $this->entryManager = new EntryManager($this->getConnection());
        }

        return $this->entryManager;
    }

    /**
     * {@inheritdoc}
     */
    public function createQuery($dn, $query, array $options = [])
    {
        return new Query($this->getConnection(), $dn, $query, $options);
    }

    /**
     * {@inheritdoc}
     */
    public function escape($subject, $ignore = '', $flags = 0)
    {
        $value = ldap_escape($subject, $ignore, $flags);

        // Per RFC 4514, leading/trailing spaces should be encoded in DNs, as well as carriage returns.
        if ((int) $flags & LDAP_ESCAPE_DN) {
            if (!empty($value) && ' ' === $value[0]) {
                $value = '\\20'.substr($value, 1);
            }
            if (!empty($value) && ' ' === $value[\strlen($value) - 1]) {
                $value = substr($value, 0, -1).'\\20';
            }
            $value = str_replace("\r", '\0d', $value);
        }

        return $value;
    }
}


text:
using System;

namespace DNX.Helpers.Exceptions
{
    /// <summary>
    /// EnumTypeException.
    /// </summary>
    /// <seealso cref="System.Exception" />
    public class EnumTypeException : Exception
    {
        /// <summary>
        /// The message template
        /// </summary>
        private const string MessageTemplate = "{0} is not an enumeration type";

        /// <summary>
        /// The type the exception was thrown for
        /// </summary>
        /// <value>The type.</value>
        public Type Type { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="EnumTypeException" /> class.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <remarks>Uses the default message template</remarks>
        public EnumTypeException(Type type)
            : this(type, MessageTemplate)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="EnumTypeException" /> class.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="messageTemplate">The message template.</param>
        public EnumTypeException(Type type, string messageTemplate)
            : base(string.Format(messageTemplate, type.Name))
        {
            Type = type;
        }
    }
}


text:
/* globals module */
module.exports = function(grunt) {
  'use strict';

  var
      host = grunt.option('hostname') ? grunt.option('hostname') : '<%= devServer.host %>',
      url = '<%= devServer.protocol %>' + host + ':<%= devServer.port %>/';

  return {
    options: {
      keepAlive: false
    },
    local: {
      options: {
        configFile: 'test/config/protractor.conf.js',
        args: {
          baseUrl: url
        }
      }
    },
    browserstack: {
      options: {
        configFile: 'test/config/protractor.bs.conf.js',
        noColor: true,
        args: {
          baseUrl: url
        }
      }
    }
  };
};