text:
import os
import pytest

from bokeh.io import output_file
from .screenshot import Screenshot

def pytest_addoption(parser):
    parser.addoption(
        "--set-new-base-screenshot", dest="set_new_base_screenshot", action="store_true", default=False, help="Use to set a new screenshot for imagediff testing. Be sure to only set for the tests you want by usign the -k pytest option to select your test."
    )

@pytest.fixture
def selenium(selenium):
    # Give items a chance to load
    selenium.implicitly_wait(10)
    selenium.set_window_size(width=1200, height=600)
    return selenium

@pytest.fixture(scope='session')
def base_url(request, file_server):
    return file_server.where_is('')

@pytest.fixture
def output_file_url(request, file_server):

    filename = request.function.__name__ + '.html'
    file_obj = request.fspath.dirpath().join(filename)
    file_path = file_obj.strpath

    output_file(file_path, mode='inline')

    def tearDown():
        if file_obj.isfile():
            file_obj.remove()
    request.addfinalizer(tearDown)

    return file_server.where_is(file_path)

def pytest_generate_tests(metafunc):
    # hasattr(metafunc.function, "foo") is like doing item.get_marker("foo")
    # This is ugly, but unfortunately there's not currently a better interface
    # https://github.com/pytest-dev/pytest/issues/1425
    if hasattr(metafunc.function, "cross_browser"):
        if metafunc.config.option.driver == "SauceLabs":
            cross_browser_list = [
                {
                    "browserName": "firefox",
                    "platform": "Linux",
                    "version": None
                },
                {
                    "browserName": "chrome",
                    "platform": "Linux",
                    "version": None
                },
            ]
            metafunc.fixturenames.append('test_browser')
            metafunc.parametrize('test_browser', cross_browser_list, ids=["firefox", "chrome"])

@pytest.fixture()
def test_browser():
    # If version is None, latest will be used
    return {"browserName": "firefox", "platform": "Linux", "version": None}

@pytest.fixture()
def capabilities(capabilities, test_browser):
    capabilities["browserName"] = test_browser["browserName"]
    capabilities["platform"] = test_browser["platform"]
    if test_browser["version"]:
        capabilities["version"] = test_browser["version"]
    return capabilities

@pytest.fixture(scope="session")
def session_capabilities(session_capabilities):
    session_capabilities["tunnel-identifier"] = os.environ.get("TRAVIS_JOB_NUMBER")
    return session_capabilities

@pytest.fixture
def screenshot(request):
    # Screenshot tests can only be run under the following circumstances:
    # - driver: SauceLabs
    # - capabilities: browserName: firefox
    # - capabilities: platform: linux
    # This helps ensure that screenshots are comparable.

    if request.config.option.driver != 'SauceLabs':
        pytest.skip('Screenshot tests can only be run with --driver=SauceLabs')

    capabilities = request.getfuncargvalue('capabilities')
    if capabilities['browserName'] != 'firefox':
        pytest.skip('Screenshot tests can only be run with browserName firefox. Capabilties are: %s' % capabilities)
    if capabilities['platform'] != 'Linux':
        pytest.skip('Screenshot tests can only be run with platform linux. Capabilities are: %s' % capabilities)

    if request.config.option.set_new_base_screenshot:
        screenshot = Screenshot(request=request, set_new_base=True)
    else:
        screenshot = Screenshot(request=request, set_new_base=False)
    return screenshot

#
# Hook into the pytest report to add the screnshot diff
#

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
    outcome = yield

    # Only run through this at the end of the test
    if call.when != 'call':
        return

    # Don't continue if this isn't a screenshot test
    if 'screenshot' not in item.fixturenames:
        return

    # Don't add screenshots if we can't create a screenshot
    try:
        screenshot = Screenshot(item=item)
    except AssertionError:
        return

    report = outcome.get_result()
    xfail = hasattr(report, 'wasxfail')
    failure = (report.skipped and xfail) or (report.failed and not xfail)
    pytest_html = item.config.pluginmanager.getplugin('html')

    # Don't add screenshots if test passed
    if failure:
        diff = pytest_html.extras.image(screenshot.get_diff_as_base64(), '')
        base = pytest_html.extras.image(screenshot.get_base_as_base64(), '')
        test = pytest_html.extras.image(screenshot.get_current_as_base64(), '')
        # Override existing extra and logs for screenshot tests (keeps output manageable)
        report.extra = [test, diff, base]
        report.longrepr = ''


text:
<?php

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

class Supportmatrix extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('session');
        $this->load->library('form_validation');
        $this->load->model(array('categories_model'));
		$this->load->model(array('supportmatrix_model'));
    }

    function Add_matrix() {
        $this->load->view('admin_template/Header');
        $this->load->view('supportmatrix/Add_supportmatrix');
        $this->load->view('admin_template/Footer');
    }

    function list_all_supportmatrix() {
        $list_all_supportmatrix = $this->supportmatrix_model->list_all_supportmatrix();
        echo json_encode($list_all_supportmatrix);
    }

    function delete_supportmatrix($id) {
        $delete_supportmatrix = $this->supportmatrix_model->delete_supportmatrix($id);
        if ($delete_supportmatrix) {
            echo json_encode(array("err_code" => 0, "status" => "SUCCESS"));
            exit;
        } else {
            echo json_encode(array("err_code" => 1, "status" => "FAILED"));
            exit;
        }
    }
	function create_supportmatrix(){

		$data= array('email' => $this->input->post('email'),
		'contact_no' => $this->input->post('contact_no'),
		'timings' => $this->input->post('timings'),
		'comments' => $this->input->post('comments'),
		'role_id' => $this->input->post('role_id'),
		'support_type' => $this->input->post('support_type')
		);

		$this->supportmatrix_model->create_supportmatrix($data);
		echo $this->db->last_query();exit;

	}
	function edit_supportmatrix(){

		$id = $this->uri->segment(3);

		$data['data'] = $this->supportmatrix_model->get_supportmatrix($id);

		$this->load->view('admin_template/Header');

		$this->load->view('supportmatrix/Edit_supportmatrix',$data);

        $this->load->view('admin_template/Footer');

	}
	function update_supportmatrix(){

	/*$update_category_data= array(
				'cat_Name' => $this->input->post('name'),
				'enable' => $this->input->post('status')

					);*/

	$data= array('email' => $this->input->post('email'),
		'contact_no' => $this->input->post('contact_no'),
		'timings' => $this->input->post('timings'),
		'comments' => $this->input->post('comments'),
		'role_id' => $this->input->post('role_id'),
		'support_type' => $this->input->post('support_type')
		);

						$id = $this->input->post('id');

				$this->supportmatrix_model->update_supportmatrixtable($data,$id);

	}

}

redpajama_set_name: RedPajamaGithub


text:
extern crate genbind;

pub fn main() {
    use std::env;
    // Default arguments
    let mut input_file = String::from("src/tests/test.rs");
    let mut output_file = String::from("myheader.h");

    let args: Vec<String> = env::args().collect();

    // argument 0 is the executable name
    if args.len() != 3 {
        println!("Usage: {} <input_source>.rs <output_header>.h", args[0]);
    }

    // Check for command-line arguments
    let mut i = 0;
    for argument in args {
        if i == 1 {
            input_file = argument;
        } else if i == 2 {
            output_file = argument;
        }
        i += 1;
    }
    println!("Reading source from {}", &input_file);

    genbind::write_c_header(
        &std::path::Path::new(&input_file),
        &std::path::Path::new(&output_file),
    );

    println!("Wrote {}", &output_file);
}


text:
import pathlib

import pytest

from cdflib import CDF

fname = (pathlib.Path(__file__) / '..' / 'testfiles' /
         'psp_fld_l2_mag_rtn_1min_20200104_v02.cdf')

def test_read():
    cdf = CDF(fname)

    info = cdf.cdf_info()
    assert isinstance(info, dict)

    varatts = cdf.varattsget('psp_fld_l2_mag_RTN_1min')
    assert isinstance(varatts, dict)

def test_context():
    with CDF(fname) as cdf:
        cdf.cdf_info()

def test_nonexist_file_errors(tmp_path):
    with pytest.raises(FileNotFoundError, match='not found'):
        CDF(tmp_path / 'nonexist.cdf')


text:
package org.nercel.joker.web.service;

import java.util.List;

import org.nercel.joker.web.entity.Demo;

/**
 *Description: <类功能描述>.

 *

	<使用说明>

 *Makedate:2014年8月19日 下午2:35:27
 * @author Administrator
 * @version V1.0
 */

public interface DemoService {

	public List<Demo> findAll();

	public Demo getById(long id);

	public void save(Demo demo);

	public void delete(Demo demo);

	public Demo getByName(long id,String name);
}


text:
<?php

namespace Tests\Feature\Steps;

use TheCrypticAce\Suitey\Steps;

class SeedDatabaseTest extends TestCase
{
    use RunStepTests;

    protected function name()
    {
        return "seed database";
    }

    protected function steps()
    {
        yield "using a given seeder" => [
            "steps" => [
                [
                    "class" => Steps\MigrateDatabase::class,
                    "options" => [],
                ],
                [
                    "class" => Steps\SeedDatabase::class,
                    "options" => ["class" => "TestSeeder"],
                ],
            ],

            "status" => 0,
            "output" => [
                "[1/4] Migrate database",
                "[2/4] Seed database using TestSeeder",
                "[3/4] Asserting",
                "[4/4] Run PHPUnit",
            ],

            "database" => [
                ["connection" => null, "table" => "default_tests", "attributes" => ["id" => 2]],
            ],
        ];
    }
}


text:
module Whatser
  class User < Whatser::Resource
    attr_accessor :id,:facebook_id,:gowalla_id,:foursquare_id,:twitter_id
    attr_accessor :name,:twitter_name,:avatar_pic,:location,:bio,:email
    attr_accessor :last_login_at,:promoted
    attr_writer   :avatar,:remote_avatar,:password,:lat,:lng
    attr_writer   :comments_count,:poi_count,:check_ins_count,:media_count,:taggings_count,:follows_count,:followers_count,:collections_count
    attr_writer   :access_token

    class << self
      def me
        api_request :get, "/api/users/me"
      end

      def anonymous
        api_request :get, "/api/users/anonymous"
      end

      def search(params={})
        api_request :get, "/api/users/lookup", {:query => params}
      end

      def suggested(params={})
        api_request :get, "/api/users/suggested", {:query => params}
      end

      def find(id, params={})
        api_request :get, "/api/users/#{id}/profile", {:query => params}
      end

      def create(params={})
        api_request :post, "/api/users", {:body => {'user' => params} }, :auth => :key
      end

      def invite(emails)
        api_request :post, "/api/invites", {:query => {'emails' => emails} }
      end

      def visitors(id, params={})
        api_request :get, "/api/poi/#{id}/visitors", {:query => params}
      end

      def collectors(id, params={})
        api_request :get, "/api/poi/#{id}/collectors", {:query => params}
      end
    end

    def save
      if id.blank?
        api_request :post, "/api/users", {:body => {'user' => to_params} }, :auth => :key
      else
        api_request :put, "/api/users/me", {:body => {'user' => to_params} }
      end
    end

    def connection
      Whatser::Follow.set(self.class.client).connection(id)
    end

    def followers(params={})
      Whatser::Follow.set(self.class.client).followers(id, params)
    end

    def thanks(poi_id,params={})
      api_request :post, "/api/users/#{id}/poi/#{poi_id}/thanks", {:query => params}
    end

    def oauth_token
      access_token
    end

    def facebook_connected?
      !facebook_id.blank?
    end

    def foursquare_connected?
      !foursquare_id.blank?
    end

    def gowalla_connected?
      !gowalla_id.blank?
    end

    def twitter_connected?
      !twitter_id.blank?
    end

    def to_params
      {:name=>name,:avatar_pic=>@remote_avatar,:location=>location,:bio=>bio,:email=>email}
    end
  end
end


text:
import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class PageService {
  constructor (private http: Http) {}

  private _listUrl = 'api/pages/list';
  private _addUrl = 'api/pages/add';
  private _updateSettingsUrl = 'api/pages/settings';
  private _removePageUrl = 'api/pages/remove';

  /**
   * Lists pages
   *
   */
  list () {
    let headers = new Headers();
    headers.append('X-AUTH', 'Bearer ' + localStorage.getItem('id_token'));
    let options = new RequestOptions({ headers: headers });

    return this.http.get(this._listUrl, options).map((res:Response) => res.json());
  }

  /**
   * Adds a page
   *
   * @param {string} url
   * @param {string} title
   * @param {string} description
   * @return {Observable}
   */
  add (url: string, title: string, description: string) {

    let body = JSON.stringify({ url, title, description });

    let headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('X-AUTH', 'Bearer ' + localStorage.getItem('id_token'));
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this._addUrl, body, options);

  }

  /**
   * Updates the settings for a page
   *
   * @param {string} url
   * @param {string} title
   * @param {string} description
   * @param {string} keywords
   * @param {string} callout
   * @param {string} layout
   * @param {string} language
   * @param {string} direction
   * @return {Observable}
   */
  updateSettings (url: string, title: string, description: string, keywords: string, callout: string, layout: string, language: string, direction: string) {

    let body = JSON.stringify({ url, title, description, keywords, callout, layout, language, direction });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('X-AUTH', 'Bearer ' + localStorage.getItem('id_token'));
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this._updateSettingsUrl, body, options);

  }

  /**
   * Removes the page
   *
   * @param {string} url
   * @return {Observable}
   */
  remove (url: string) {

    let body = JSON.stringify({ url });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('X-AUTH', 'Bearer ' + localStorage.getItem('id_token'));
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this._removePageUrl, body, options);

  }

}


text:
class file_format
{
public:
	file_format() {}
	virtual ~file_format() {}

	virtual int detect(file_definition& fd) = 0;
	virtual std::string name() = 0;
};

#endif // FILE_FORMAT_H


text:
package org.apache.shardingsphere.shardingproxy.frontend.executor;

import com.google.common.util.concurrent.ListeningExecutorService;
import lombok.Getter;
import org.apache.shardingsphere.underlying.common.config.properties.ConfigurationPropertyKey;
import org.apache.shardingsphere.underlying.executor.kernel.impl.ShardingSphereExecutorService;
import org.apache.shardingsphere.shardingproxy.context.ShardingProxyContext;

/**
 * Command execute engine.
 */
public final class UserExecutorGroup implements AutoCloseable {

    private static final ShardingProxyContext SHARDING_PROXY_CONTEXT = ShardingProxyContext.getInstance();

    private static final String NAME_FORMAT = "Command-%d";

    private static final UserExecutorGroup INSTANCE = new UserExecutorGroup();

    private final ShardingSphereExecutorService shardingSphereExecutorService;

    @Getter
    private final ListeningExecutorService executorService;

    private UserExecutorGroup() {
        shardingSphereExecutorService = new ShardingSphereExecutorService(SHARDING_PROXY_CONTEXT.getProperties().<Integer>getValue(ConfigurationPropertyKey.ACCEPTOR_SIZE), NAME_FORMAT);
        executorService = shardingSphereExecutorService.getExecutorService();
    }

    /**
     * Get instance of user executor group.
     *
     * @return user executor group
     */
    public static UserExecutorGroup getInstance() {
        return INSTANCE;
    }

    @Override
    public void close() {
        shardingSphereExecutorService.close();
    }
}


text:
require 'test_helper'
ActiveValidators.activate(:postal_code)

describe "Postal Code Validation" do
  def build_postal_code_record postal_code, attrs = {}
    TestRecord.reset_callbacks(:validate)
    TestRecord.validates :postal_code, :postal_code => postal_code
    TestRecord.new attrs
  end

  describe "when no country is given" do
    it 'should validate format of postal code with #####' do
      subject = build_postal_code_record true
      subject.postal_code = '11211'
      subject.valid?.must_equal true
      subject.errors.size.must_equal 0
    end

    it 'should validate format of postal code with #####-#####' do
      subject = build_postal_code_record true
      subject.postal_code = '94117-1234'
      subject.valid?.must_equal true
      subject.errors.size.must_equal 0
    end
  end

  ActiveModel::Validations::PostalCodeValidator.known_formats.each do |country, formats|
    describe "when given a :#{country} country parameter" do
      formats.each do |format|
        it "should validate format of lowercase postal code with #{format}" do
          subject = build_postal_code_record :country => country
          subject.postal_code = ActiveValidators::OneNineShims::OneNineString.new(format).gsub(/[@#]/, '@' => 'A', '#' => '9')
          subject.valid?.must_equal true
          subject.errors.size.must_equal 0
        end

        it "should validate format of upcase postal code with #{format}" do
          subject = build_postal_code_record :country => country.upcase
          subject.postal_code = ActiveValidators::OneNineShims::OneNineString.new(format).gsub(/[@#]/, '@' => 'A', '#' => '9')
          subject.valid?.must_equal true
          subject.errors.size.must_equal 0
        end
      end
    end
  end

  describe "for invalid formats" do
    it "rejects invalid formats" do
      subject = build_postal_code_record true, :postal_code => '999'
      subject.valid?.must_equal false
      subject.errors.size.must_equal 1
    end

    it "generates an error message of type invalid" do
      subject = build_postal_code_record true, :postal_code => '999'
      subject.valid?.must_equal false
      subject.errors[:postal_code].include?(subject.errors.generate_message(:postal_code, :invalid)).must_equal true
    end

    it "rejects injected content" do
      subject = build_postal_code_record true, :postal_code => "injected\n11211"
      subject.valid?.must_equal false
      subject.errors.size.must_equal 1
    end
  end
end


text:
# socks examples

## Example for SOCKS 'bind' command

The bind command tells the SOCKS proxy server to bind and listen on a new TCP port for an incoming connection. It communicates the newly opened port back to the origin client. Once a incoming connection is accepted by the SOCKS proxy server it then communicates the remote host that connected to the SOCKS proxy back through the same initial connection via the origin client.

This can be used for things such as FTP clients which require incoming TCP connections, etc.

**Connection Steps**

1. Client -(bind)-> Proxy    (Tells the proxy to bind to a new port)
2. Client <-(port)- Proxy    (Tells the origin client which port it opened)
3. Client2 --> Proxy    (Other client connects to the proxy on this port)
4. Client <--(client2's host info)  (Proxy tells the origin client who connected to it)
5. Original connection to the proxy is now a full TCP stream between client (you) and client2.
6. Client <--> Proxy <--> Client2

## Usage

The 'bind' command can only be used by creating a new SocksClient instance and listening for 'bound' and 'established' events.

```typescript
const SocksClient = require('socks').SocksClient;

const options = {
  proxy: {
    host: '104.131.124.203',
    port: 1081,
    type: 5
  },

  // This should be the ip and port of the expected client that will connect to the SOCKS proxy server on the newly bound port.
  // Most SOCKS servers accept 0.0.0.0 as a wildcard address to accept any client.
  destination: {
    host: '0.0.0.0',
    port: 0
  },

  command: 'bind'
};

const client = new SocksClient(options);

// This event is fired when the SOCKS server has started listening on a new port for incoming connections.
client.on('bound', (info) => {
  console.log(info);
  /*
  {
    socket: <Socket ...>,
    remoteHost: { // This is the remote ip and port of the SOCKS proxy that is now accepting incoming connections.
      host: '104.131.124.203',
      port: 49928
    }
  }
  */
});

// This event is fired when the SOCKS server has accepted an incoming connection on the newly bound port.
client.on('established', (info) => {
  console.log(info);
  /*
  {
    socket: <Socket ...>,
    remoteHost: { // This is the remote ip and port that connected to the SOCKS proxy on the newly bound port.
      host: '1.2.3.4',
      port: 58232
    }
  }
  */

  // At this point info.socket is a regular net.Socket TCP connection between client and client2 (1.2.3.4) (the client which connected to the proxy on the newly bound port.)

  console.log(info.socket);
  // <Socket ...>  (this is a raw net.Socket that is established to the destination host through the given proxy servers)
});

// SOCKS proxy failed to bind.
client.on('error', () => {
  // Handle errors
});
```


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- EN-Revision: 24249 -->
<!-- Reviewed: no -->
<sect1 id="learning.plugins.conclusion">
    <title>Conclusão</title>

    <para>
        Compreender o conceito de caminhos prefixados e a sobrescrita em plugins existentes irá
        ajudá-lo na compreensão de muitos componentes do framework. Plugins são usados em
        diversos lugares:
    </para>

    <itemizedlist>
        <listitem>
            <para>
                <classname>Zend_Application</classname>: recursos (resources).
            </para>
        </listitem>

        <listitem>
            <para>
                <classname>Zend_Controller_Action</classname>: auxiliares de ação (action helpers).
            </para>
        </listitem>

        <listitem>
            <para>
                <classname>Zend_Feed_Reader</classname>: plugins.
            </para>
        </listitem>

        <listitem>
            <para>
                <classname>Zend_Form</classname>: elementos, filtros, validadores e decoradores.
            </para>
        </listitem>

        <listitem>
            <para>
                <classname>Zend_View</classname>: auxiliares de visualização (view helpers).
            </para>
        </listitem>
    </itemizedlist>

    <para>
        E vários outros lugares. Entenda esses conceitos para que você possa aproveitar a
        capacidade extensiva do Zend Framework.
    </para>

    <note>
        <title>Observação</title>

        <para>
            Veremos que <classname>Zend_Controller_Front</classname> possui um sistema de plugin -
            mas não segue as orientações contidas neste tutorial. Os plugins registrados com o
            front controller devem ser instanciados diretamente e registrados individualmente.
            A razão para isto é que este sistema antecede qualquer outro plugin do framework,
            e alterações nisso devem ser cuidadosamente ponderadas para garantir que os
            plugins escritos por desenvolvedores continuem a funcionar corretamente.
        </para>
    </note>
</sect1>


text:
package org.gearvrf;

/**
 * For internal use only.
 *
 *

 * Provides methods for rendering scenes
 */
abstract class GVRMonoscopicRenderer {
    /**
     * Renders the given scene for the specified camera into the supplied
     * texture.
     *
     * @param scene
     *            The {@link GVRScene scene} to render.
     * @param camera
     *            The {@link GVRCamera camera} to render the scene for.
     * @param renderTexture
     *            The framebuffer {@link GVRRenderTexture texture} to render the
     *            scene into.
     * @param renderBundle
     *            Options and data for the renderer's use.
     * @param listPostEffectData
     *            Data for {@link GVRPostEffectMap custom} post-effect shaders.
     */
    static void renderCamera(GVRScene scene, GVRCamera camera, int viewportX,
            int viewportY, int viewportWidth, int viewportHeight,
            GVRRenderBundle renderBundle) {

        NativeMonoscopicRenderer.renderCamera(scene.getNative(), camera
                .getNative(), viewportX, viewportY, viewportWidth,
                viewportHeight, renderBundle.getMaterialShaderManager()
                        .getNative(), renderBundle.getPostEffectShaderManager()
                        .getNative(), renderBundle
                        .getPostEffectRenderTextureA().getNative(),
                renderBundle.getPostEffectRenderTextureB().getNative());
    }
}

class NativeMonoscopicRenderer {
    static native void renderCamera(long scene, long camera, int viewportX,
            int viewportY, int viewportWidth, int viewportHeight,
            long shaderManager, long postEffectShaderManager,
            long postEffectRenderTextureA, long postEffectRenderTextureB);
}


text:
FOUNDATION_EXPORT double Pods_complicationsappUITestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_complicationsappUITestsVersionString[];


text:
function filter_menu(def){
	refreshTable(window.location.hash.replace('#', ''));

	if (window.location.hash) {
		$('#top-level-menu a[href^="'+window.location.hash+'"]').addClass('active');
	} else {
		$('#top-level-menu a[href^="#'+def+'"]').addClass('active');
	}

	$('#top-level-menu a.filter-item').on('click', function(){
		var filter = $(this).attr('href').replace('#', '');
		$('input[name=filter-date]').val('');
		$('.date-filter-input').val('');

		refreshTable(filter);
		$(this).parent('#top-level-menu').children('a').removeClass('active');
		$(this).addClass('active');
	});
}


text:
<!DOCTYPE html>

    <title>W@ZzA Web Application - For Exchange</title>

    <link href="bootstrap/bootstrap.css" rel="stylesheet"/>
    <link href="bootstrap/bootstrap-theme.css" rel="stylesheet"/>

    W@ZzA
    <login-summary/>

<ng-view/>


text:
@interface IRRemoteInterfaceController ()

@end

@implementation IRRemoteInterfaceController
@synthesize irDevice, irCommandsTable;

- (void)awakeWithContext:(id)context {
  [super awakeWithContext:context];
  self.irDevice = context;
  [self setTitle:irDevice.name];
  [self configureTable];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(configureTable) name:NCNewDeviceInfoImage object:nil];
  // Configure interface objects here.
}

- (void)configureTable {
  if (![irDevice.info objectForKey:KeyIRCommands]) {
    NSLog(@"Array empty %@", irDevice.info);
    return;
  }
  NSArray *irCommands = [irDevice.info objectForKey:KeyIRCommands];
  int rowCount = [irCommands count]/3;
  int irCount = [irCommands count];
  NSLog(@"config ir device table, rows: %i, devices: %i", rowCount, irCount);
  NSLog(@"info array %@", irCommands);

  NSMutableArray *sorted = [[NSMutableArray alloc] initWithCapacity:irCount];
  for (int i = 0; i < irCount; i++) {
    NSDictionary *dummy = @{KeyImage: [[UIImage alloc] init], KeyName : @""};
    [sorted addObject:dummy];
  }
  for (int i = 0; i < irCount; i++) {
    NSDictionary *dict = [irCommands objectAtIndex:i];
    int index = [[dict objectForKey:KeyIndex] integerValue];
    if (index >= 0 && index < irCount) {
      [sorted replaceObjectAtIndex:index withObject:dict];
    }
  }

  for (int i = 0; i < irCount; i++) {
    for (int i = 0; i < irCount; i++) {

    }
  }

  [irCommandsTable setNumberOfRows:rowCount withRowType:@"irDeviceRowType"];

  int cmdIndex = 0;
  for (NSInteger i = 0; i < self.irCommandsTable.numberOfRows; i++) {
    IRRemoteRow* theRow = [self.irCommandsTable rowControllerAtIndex:i];
    theRow.delegate = self;
    if (cmdIndex >= irCount) break;
    NSDictionary *dict = [sorted objectAtIndex:cmdIndex];
    [theRow.leftButton setBackgroundImage:[dict objectForKey:KeyImage]];
    theRow.leftName = [dict objectForKey:KeyName];
    NSLog(@"index: %i, name %@", cmdIndex, [dict objectForKey:KeyName]);
    cmdIndex++;
    if (cmdIndex >= irCount) break;
    NSDictionary *dict2 = [sorted objectAtIndex:cmdIndex];
    [theRow.middleButton setBackgroundImage:[dict2 objectForKey:KeyImage]];
    theRow.middleName = [dict2 objectForKey:KeyName];
    NSLog(@"index: %i, name %@", cmdIndex, [dict2 objectForKey:KeyName]);
    cmdIndex++;
    if (cmdIndex >= irCount) break;
    NSDictionary *dict3 = [sorted objectAtIndex:cmdIndex];
    [theRow.rightButton setBackgroundImage:[dict3 objectForKey:KeyImage]];
    theRow.rightName = [dict3 objectForKey:KeyName];
    NSLog(@"index: %i, name %@", cmdIndex, [dict3 objectForKey:KeyName]);
    cmdIndex++;
    if (cmdIndex >= irCount) break;
  }
}

-(void)commandToggledWithName:(NSString *)name {
  NSLog(@"Toggled Command: %@", name);
  NSLog(@"Send toggle command");
  [[PhoneConnector sharedPhoneConnector] sendCommand:IRToggleCommand forDevice:self.irDevice withInfo:name];
}

-(void)table:(WKInterfaceTable *)table didSelectRowAtIndex:(NSInteger)rowIndex {
}

- (void)willActivate {
    // This method is called when watch view controller is about to be visible to user
    [super willActivate];
}

- (void)didDeactivate {
    // This method is called when watch view controller is no longer visible
    [super didDeactivate];
}

@end


text:
package com.baoyz.airdata.crud;

import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;

/**
 * AirData
 * Created by baoyz on 15/7/19.
 */
public class Delete {

    private Class<?> table;
    private String where;
    private String[] whereArgs;

    private AbstractDatabase database;
    private AirDatabaseHelper helper;

    public Delete(AbstractDatabase database) {
        this.database = database;
        this.helper = database.getDatabaseHelper();
    }

    public Delete from(Class<?> table) {
        this.table = table;
        return this;
    }

    public Delete where(String where, String... whereArgs) {
        this.where = where;
        this.whereArgs = whereArgs;
        return this;
    }

    public long execute() {
        return helper.delete(table, where, whereArgs);
    }

}


text:
title: Grails, opción real y escalable para sitios web de alta carga.
author: domix
layout: post
date: 2011-09-30
url: /2011/09/30/grails-opcion-real-y-escalable-para-sitios-web-de-alta-carga/
categories:
  - Groovy
---

He estado trabajando poco mas de un año en un proyecto que usa Grails, desde que lo comencé no pensé que se convertiría en lo que es ahora, es decir no pensé que llegara a tener tanta carga.

Básicamente es una tienda en linea, con diversas formas de pago. El stack de tecnologías se compone de varias cosas:

  * Sun JVM 1.6.24
  * Grails 1.3.4, Groovy 1.7
  * mySQL
  * Terracotta
  * RabbitMQ
  * AmazonS3
  * Tomcat 6

Usamos varios plugins de Grails entre ellos:

  * AWS
  * Rendering
  * RabbitMQ
  * SpringSecurityCore
  * Quartz
  * Feeds
  * Export
  * TinyMCE
  * Recaptcha
  * GrailsMelody
  * GPars

Y algunas librerías como:

  * XStream
  * HttpBuilder
  * OpenCSV
  * JSCH
  * iText
  * Apache POI
  * Barbecue
  * Groovy-WSLite
  * Grape

Estamos modularizando la aplicacion en mas aplicaciones y tenemos una app que usa Scala con ScalaQuery para la base de datos, en el futuro haremos muchas mas cosas con Scala y Akka.

Para JavaScript usamos JQuery y varios plugins.

Para trabajar usamos IntelliJ IDEA 10, Gradle, Archiva, Jira, Git, GitHub y mucha cerveza y café.

Un miembro del equipo desarrollo herramientas de monitoreo que revisan la salud de los load balancers y reportan los errores con mensajes directos de Twitter con Shell Scripts. También usamos logstalgia para monitorear casi en tiempo real la carga en los web servers.

El hardware esta compuesta de 5 cajas RHEL 5 de 64 bits, un LoadBalancer y un Firewall físicos. El load balancer dirige el trafico a los Apache HTTPD de 4 cajas, en cada una de esas cajas, esta  configurado con mod_proxy usando AJP hacia 2 Tomcats con un fail over a otra caja. En total se tienen 8 Tomcats atendiendo todo el trafico. Una de esas cajas tiene instalado RabbitMQ y otra caja Terracotta. Se usa una caja exclusivamente como servidor de mySQL.

Las cajas tienen los siguientes specs:

  * Dual Quad Core Xeon 2.26 HGZ
  * 24 GB de RAM
  * 300 GB SAS X 3

Estas cajas están en el hospedaje dedicado de RackSpace en Chicago.

Con todo lo anterior hemos podido suscribir 1.5 Millones de personas, logrado una carga tope de 80,000 usuarios concurrentes y 30,000 http request por minuto.

Unas de las claves ha sido usar procesamiento asíncrono con RabbitMQ y usar muchísimo el cache distribuido con Terracotta. Ademas de contar con un equipo de 4 desarrolladores mexicanos (yo entre ellos) y un alemán, con mucho talento todos ellos.

Grails es una excelente opción para desarrollo web, nos ha permitido implementar rápidamente los requerimientos de negocio, hemos hecho en un día hasta 12 despliegues de la aplicación sin sufrir downtimes. Grails es una herramienta que facilita el desarrollo web sin perder poder en los frameworks en los que se basa como Spring, Hibernate y otros…

Les dejo un video del análisis casi en tiempo de real que hace logstalgia del log de acceso de los 4 webservers


text:
@implementation UIView (Layout)

- (CGFloat)tz_left {
    return self.frame.origin.x;
}

- (void)setTz_left:(CGFloat)x {
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

- (CGFloat)tz_top {
    return self.frame.origin.y;
}

- (void)setTz_top:(CGFloat)y {
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}

- (CGFloat)tz_right {
    return self.frame.origin.x + self.frame.size.width;
}

- (void)setTz_right:(CGFloat)right {
    CGRect frame = self.frame;
    frame.origin.x = right - frame.size.width;
    self.frame = frame;
}

- (CGFloat)tz_bottom {
    return self.frame.origin.y + self.frame.size.height;
}

- (void)setTz_bottom:(CGFloat)bottom {
    CGRect frame = self.frame;
    frame.origin.y = bottom - frame.size.height;
    self.frame = frame;
}

- (CGFloat)tz_width {
    return self.frame.size.width;
}

- (void)setTz_width:(CGFloat)width {
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

- (CGFloat)tz_height {
    return self.frame.size.height;
}

- (void)setTz_height:(CGFloat)height {
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}

- (CGFloat)tz_centerX {
    return self.center.x;
}

- (void)setTz_centerX:(CGFloat)centerX {
    self.center = CGPointMake(centerX, self.center.y);
}

- (CGFloat)tz_centerY {
    return self.center.y;
}

- (void)setTz_centerY:(CGFloat)centerY {
    self.center = CGPointMake(self.center.x, centerY);
}

- (CGPoint)tz_origin {
    return self.frame.origin;
}

- (void)setTz_origin:(CGPoint)origin {
    CGRect frame = self.frame;
    frame.origin = origin;
    self.frame = frame;
}

- (CGSize)tz_size {
    return self.frame.size;
}

- (void)setTz_size:(CGSize)size {
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

+ (void)showOscillatoryAnimationWithLayer:(CALayer *)layer type:(TZOscillatoryAnimationType)type{
    NSNumber *animationScale1 = type == TZOscillatoryAnimationToBigger ? @(1.15) : @(0.7);
    NSNumber *animationScale2 = type == TZOscillatoryAnimationToBigger ? @(0.92) : @(1.15);

    [UIView animateWithDuration:0.15 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
        [layer setValue:animationScale1 forKeyPath:@"transform.scale"];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.15 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
            [layer setValue:animationScale2 forKeyPath:@"transform.scale"];
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
                [layer setValue:@(1.0) forKeyPath:@"transform.scale"];
            } completion:nil];
        }];
    }];
}

@end


text:
package com.scientificsoft.iremote.server.tools;

public class Strings {

	public static boolean isEmpty(String str) {
		return ( str == null ) || ( str.length() == 0 );
	}

	public static String capitalize(String str) {
		return
			String.valueOf(str.charAt(0)).toUpperCase()
			+ str.substring(1);
	}

}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>
Kumulative Verteilung
</title>
<link rel="stylesheet" type="text/css" href="help.css">

Definition

Zeigt den Anteil an Beobachtungen, deren Ausprägung unter einem bestimmten Wert liegt.

Parameter

Oberes Feld: quantitative Variable, die analysiert werden soll.

Aktionen

Verschieben Sie den Cursor nach rechts und links, um den Datensatz in Klassen einzuteilen, die in Bezug auf der Merkmal gleich breit sind.

Verschieben Sie den Cursor nach oben und unten, um den Datensatz in gleich große Klassen einzuteilen.

Ziehen Sie den rosa Pfeil in die Liste kategorialer Variablen (oben rechts), um eine neue Variable aus diesen Klassen zu erstellen.


text:
BOOST_MATH_HEADER_DEPRECATED("<boost/integer/common_factor_ct.hpp>");

namespace boost
{
namespace math
{

   using boost::integer::static_gcd;
   using boost::integer::static_lcm;
   using boost::integer::static_gcd_type;

}  // namespace math
}  // namespace boost
#else
#error Common factor is not available in standalone mode because it requires boost.integer.
#endif // BOOST_MATH_STANDALONE

#endif  // BOOST_MATH_COMMON_FACTOR_CT_HPP


text:
package network

import (
	"errors"
	"fmt"
	"net"
	"os"
	"time"

	"golang.org/x/net/icmp"
	"golang.org/x/net/ipv4"

	"github.com/monkeyherder/salus/checks"
)

// http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
const ICMP_PROTOCOL int = 1

type IcmpCheck struct {
	Address string
	Timeout time.Duration
}

func (icmpCheck IcmpCheck) Run() (checks.CheckInfo, error) {
	// Use a non-privileged datagram-oriented ICMP: https://lwn.net/Articles/420800/
	packetConn, err := icmp.ListenPacket("udp4", "0.0.0.0")

	if err != nil {
		return checks.CheckInfo{}, err
	}
	defer packetConn.Close()

	icmpRequest := icmp.Message{
		Type: ipv4.ICMPTypeEcho, Code: 0,
		Body: &icmp.Echo{
			ID: os.Getpid() & 0xffff, Seq: 1,
			Data: []byte{},
		},
	}
	icmpRequestBody, err := icmpRequest.Marshal(nil)
	if err != nil {
		return checks.CheckInfo{}, err
	}

	ipAddr, err := getAddr(icmpCheck.Address)
	if err != nil {
		return checks.CheckInfo{}, err
	}

	if _, err := packetConn.WriteTo(icmpRequestBody, ipAddr); err != nil {
		return checks.CheckInfo{}, err
	}

	deadline := time.Now().Add(icmpCheck.Timeout)
	packetConn.SetReadDeadline(deadline)

	readBuffer := make([]byte, 1500)
	responseReadLen, _, err := packetConn.ReadFrom(readBuffer)
	if err != nil {
		return checks.CheckInfo{}, err
	}

	icmpResponseMessage, err := icmp.ParseMessage(ICMP_PROTOCOL, readBuffer[:responseReadLen])
	if err != nil {
		return checks.CheckInfo{}, err
	}
	switch icmpResponseMessage.Type {
	case ipv4.ICMPTypeEchoReply:
		return checks.CheckInfo{}, nil
	default:
		return checks.CheckInfo{}, errors.New(fmt.Sprintf("got %+v; expected echo reply", icmpResponseMessage))
	}
}

func getAddr(host string) (net.Addr, error) {
	ips, err := net.LookupIP(host)
	if err != nil {
		return nil, err
	}

	for _, ip := range ips {
		if ip.To4() != nil {
			return &net.UDPAddr{IP: ip}, nil
		}
	}
	return nil, errors.New("no A record")
}


text:
package utils

import (
	"context"
	"database/sql"
	"io"
	"time"

	"github.com/pingcap/errors"
	"github.com/pingcap/log"
	berrors "github.com/pingcap/tidb/br/pkg/errors"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

const (
	// importSSTRetryTimes specifies the retry time. Its longest time is about 90s-100s.
	importSSTRetryTimes      = 16
	importSSTWaitInterval    = 40 * time.Millisecond
	importSSTMaxWaitInterval = 10 * time.Second

	downloadSSTRetryTimes      = 8
	downloadSSTWaitInterval    = 1 * time.Second
	downloadSSTMaxWaitInterval = 4 * time.Second

	resetTSRetryTime       = 16
	resetTSWaitInterval    = 50 * time.Millisecond
	resetTSMaxWaitInterval = 500 * time.Millisecond

	resetTSRetryTimeExt       = 600
	resetTSWaitIntervalExt    = 500 * time.Millisecond
	resetTSMaxWaitIntervalExt = 300 * time.Second
)

// RetryState is the mutable state needed for retrying.
// It likes the `utils.Backoffer`, but more fundamental:
// this only control the backoff time and knows nothing about what error happens.
// NOTE: Maybe also implement the backoffer via this.
type RetryState struct {
	maxRetry   int
	retryTimes int

	maxBackoff  time.Duration
	nextBackoff time.Duration
}

// Whether in the current state we can retry.
func (rs *RetryState) ShouldRetry() bool {
	return rs.retryTimes < rs.maxRetry
}

// Get the exponential backoff durion and transform the state.
func (rs *RetryState) ExponentialBackoff() time.Duration {
	rs.retryTimes++
	backoff := rs.nextBackoff
	rs.nextBackoff *= 2
	if rs.nextBackoff > rs.maxBackoff {
		rs.nextBackoff = rs.maxBackoff
	}
	return backoff
}

// InitialRetryState make the initial state for retrying.
func InitialRetryState(maxRetryTimes int, initialBackoff, maxBackoff time.Duration) RetryState {
	return RetryState{
		maxRetry:    maxRetryTimes,
		maxBackoff:  maxBackoff,
		nextBackoff: initialBackoff,
	}
}

// RecordRetry simply record retry times, and no backoff
func (rs *RetryState) RecordRetry() {
	rs.retryTimes++
}

// Attempt implements the `Backoffer`.
// TODO: Maybe use this to replace the `exponentialBackoffer` (which is nearly homomorphic to this)?
func (rs *RetryState) Attempt() int {
	return rs.maxRetry - rs.retryTimes
}

// NextBackoff implements the `Backoffer`.
func (rs *RetryState) NextBackoff(error) time.Duration {
	return rs.ExponentialBackoff()
}

type importerBackoffer struct {
	attempt      int
	delayTime    time.Duration
	maxDelayTime time.Duration
}

// NewBackoffer creates a new controller regulating a truncated exponential backoff.
func NewBackoffer(attempt int, delayTime, maxDelayTime time.Duration) Backoffer {
	return &importerBackoffer{
		attempt:      attempt,
		delayTime:    delayTime,
		maxDelayTime: maxDelayTime,
	}
}

func NewImportSSTBackoffer() Backoffer {
	return NewBackoffer(importSSTRetryTimes, importSSTWaitInterval, importSSTMaxWaitInterval)
}

func NewDownloadSSTBackoffer() Backoffer {
	return NewBackoffer(downloadSSTRetryTimes, downloadSSTWaitInterval, downloadSSTMaxWaitInterval)
}

func (bo *importerBackoffer) NextBackoff(err error) time.Duration {
	if MessageIsRetryableStorageError(err.Error()) {
		bo.delayTime = 2 * bo.delayTime
		bo.attempt--
	} else {
		e := errors.Cause(err)
		switch e { // nolint:errorlint
		case berrors.ErrKVEpochNotMatch, berrors.ErrKVDownloadFailed, berrors.ErrKVIngestFailed, berrors.ErrPDLeaderNotFound:
			bo.delayTime = 2 * bo.delayTime
			bo.attempt--
		case berrors.ErrKVRangeIsEmpty, berrors.ErrKVRewriteRuleNotFound:
			// Excepted error, finish the operation
			bo.delayTime = 0
			bo.attempt = 0
		default:
			switch status.Code(e) {
			case codes.Unavailable, codes.Aborted:
				bo.delayTime = 2 * bo.delayTime
				bo.attempt--
			default:
				// Unexcepted error
				bo.delayTime = 0
				bo.attempt = 0
				log.Warn("unexcepted error, stop to retry", zap.Error(err))
			}
		}
	}
	if bo.delayTime > bo.maxDelayTime {
		return bo.maxDelayTime
	}
	return bo.delayTime
}

func (bo *importerBackoffer) Attempt() int {
	return bo.attempt
}

type pdReqBackoffer struct {
	attempt      int
	delayTime    time.Duration
	maxDelayTime time.Duration
}

func NewPDReqBackoffer() Backoffer {
	return &pdReqBackoffer{
		attempt:      resetTSRetryTime,
		delayTime:    resetTSWaitInterval,
		maxDelayTime: resetTSMaxWaitInterval,
	}
}

func NewPDReqBackofferExt() Backoffer {
	return &pdReqBackoffer{
		attempt:      resetTSRetryTimeExt,
		delayTime:    resetTSWaitIntervalExt,
		maxDelayTime: resetTSMaxWaitIntervalExt,
	}
}

func (bo *pdReqBackoffer) NextBackoff(err error) time.Duration {
	// bo.delayTime = 2 * bo.delayTime
	// bo.attempt--
	e := errors.Cause(err)
	switch e { // nolint:errorlint
	case nil, context.Canceled, context.DeadlineExceeded, io.EOF, sql.ErrNoRows:
		// Excepted error, finish the operation
		bo.delayTime = 0
		bo.attempt = 0
	case berrors.ErrRestoreTotalKVMismatch:
		bo.delayTime = 2 * bo.delayTime
		bo.attempt--
	default:
		switch status.Code(e) {
		case codes.DeadlineExceeded, codes.NotFound, codes.AlreadyExists, codes.PermissionDenied, codes.ResourceExhausted, codes.Aborted, codes.OutOfRange, codes.Unavailable, codes.DataLoss, codes.Unknown:
			bo.delayTime = 2 * bo.delayTime
			bo.attempt--
		default:
			// Unexcepted error
			bo.delayTime = 0
			bo.attempt = 0
			log.Warn("unexcepted error, stop to retry", zap.Error(err))
		}
	}

	if bo.delayTime > bo.maxDelayTime {
		return bo.maxDelayTime
	}
	return bo.delayTime
}

func (bo *pdReqBackoffer) Attempt() int {
	return bo.attempt
}


text:
layout: post
Title: Processing the MTA turnstile data!
---

My fourth data science project at Metis is about sentiment analysis of tweets related to Apple Watch.
I used the twitter streaming API to pull 5000 tweets
that were tagged with #Applewatch. Subsequently, I carried out sentiment analysis on each tweet using Text Blob python package.

Fig1. Polarity histogram of twitter data related to Apple watch.

Fig2. Subjectivity histogram of twitter data related to Apple watch.


text:
Safely pipe node.js streams while capturing all errors to a single promise.

## Install

    npm install promisepipe

## API

```
promisePipe(<readable stream>, [transform streams...], <writeable stream>)
```

It returns a native promise. On success the resolved value will be an array of the
streams passed in. When rejected an error object is created with following
keys:

  - `source`: The stream that caused the error
  - `originalError`: Original error from the stream
  - `message`: The error message from original error

Note: the last stream in the chain needs to be a writable stream, not a duplex/transform stream. If you use a 3rd party library which returns deplux streams instead of writable streams, you'll need to add something like [`.pipe(devnull())`](https://www.npmjs.com/package/dev-null) to the end, otherwise the promise will never resolve ([#16](https://github.com/epeli/node-promisepipe/issues/16)).

Starting with v3, all streams are destroyed if there's an error to prevent memory leaks.

## Example

```javascript
var promisePipe = require("promisepipe");

promisePipe(
    fs.createReadStream(INPUT_FILE),
    new UpcaseTransform(),
    fs.createWriteStream(OUTPUT_FILE),
).then(function(streams){
    console.log("Done writing to the output file stream!");
}, function(err) {
    console.log("This stream failed:", err.source);
    console.log("Original error was:", err.originalError);
});
```

or with async-wait

```javascript
var promisePipe = require("promisepipe");

(async () => {
  try {
    await promisePipe(
      fs.createReadStream(INPUT_FILE),
      new UpcaseTransform(),
      fs.createWriteStream(OUTPUT_FILE)
    );
    console.log("Done writing to the output file stream!");
  } catch (err) {
    console.log("This stream failed:", err.source);
    console.log("Original error was:", err.originalError);
  }
})();

```

## Why?

Stream piping in node.js is cool, but error handling is not because streams
do not bubble errors to the target streams.

For example if the previous example is written like this:

```javascript
fs.createReadStream(INPUT_FILE)
  .pipe(new UpcaseTransform())
  .pipe(fs.createReadStream(OUTPUT_FILE))
```

It might crash your program at any time. You must handle the errors
from each stream manually like this:

```javascript
fs.createReadStream(INPUT_FILE).on("error", function(err) {
    // handle the error
}).pipe(new UpcaseTransform()).on("error", function(err) {
    // handle the error
}).pipe(fs.createReadStream(OUTPUT_FILE)).on("error", function(err) {
    // handle the error
})
```

Handling errors this way can be very cumbersome. `promisepipe` simplifies
error handling by sending the first error occurance into a promise.


text:
package com.example.android.asynctaskloader;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.android.asynctaskloader.utilities.NetworkUtils;

import java.io.IOException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    // COMPLETED (1) Create a static final key to store the query's URL
    static final String QUERY_URL = "QUERY_URL";
    // COMPLETED (2) Create a static final key to store the search's raw JSON
    static final String RESPONSE_JSON = "RESPONSE_JSON";

    private EditText mSearchBoxEditText;

    private TextView mUrlDisplayTextView;
    private TextView mSearchResultsTextView;

    private TextView mErrorMessageDisplay;

    private ProgressBar mLoadingIndicator;

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

        mSearchBoxEditText = (EditText) findViewById(R.id.et_search_box);

        mUrlDisplayTextView = (TextView) findViewById(R.id.tv_url_display);
        mSearchResultsTextView = (TextView) findViewById(R.id.tv_github_search_results_json);

        mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);

        mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);

        // COMPLETED (9) If the savedInstanceState bundle is not null, set the text of the URL and search results TextView respectively
        if (savedInstanceState != null) {
            mUrlDisplayTextView.setText(savedInstanceState.getString(QUERY_URL));
            mSearchResultsTextView.setText(savedInstanceState.getString(RESPONSE_JSON));
        }
    }

    /**
     * This method retrieves the search text from the EditText, constructs the
     * URL (using {@link NetworkUtils}) for the github repository you'd like to find, displays
     * that URL in a TextView, and finally fires off an AsyncTask to perform the GET request using
     * our {@link GithubQueryTask}
     */
    private void makeGithubSearchQuery() {
        String githubQuery = mSearchBoxEditText.getText().toString();
        URL githubSearchUrl = NetworkUtils.buildUrl(githubQuery);
        mUrlDisplayTextView.setText(githubSearchUrl.toString());
        new GithubQueryTask().execute(githubSearchUrl);
    }

    /**
     * This method will make the View for the JSON data visible and
     * hide the error message.
     *

     * Since it is okay to redundantly set the visibility of a View, we don't
     * need to check whether each view is currently visible or invisible.
     */
    private void showJsonDataView() {
        /* First, make sure the error is invisible */
        mErrorMessageDisplay.setVisibility(View.INVISIBLE);
        /* Then, make sure the JSON data is visible */
        mSearchResultsTextView.setVisibility(View.VISIBLE);
    }

    /**
     * This method will make the error message visible and hide the JSON
     * View.
     *

     * Since it is okay to redundantly set the visibility of a View, we don't
     * need to check whether each view is currently visible or invisible.
     */
    private void showErrorMessage() {
        /* First, hide the currently visible data */
        mSearchResultsTextView.setVisibility(View.INVISIBLE);
        /* Then, show the error */
        mErrorMessageDisplay.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemThatWasClickedId = item.getItemId();
        if (itemThatWasClickedId == R.id.action_search) {
            makeGithubSearchQuery();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // COMPLETED (3) Override onSaveInstanceState to persist data across Activity recreation
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // Do the following steps within onSaveInstanceState
        // COMPLETED (4) Make sure super.onSaveInstanceState is called before doing anything else
        // COMPLETED (5) Put the contents of the TextView that contains our URL into a variable
        String urlAddress = mUrlDisplayTextView.getText().toString();
        // COMPLETED (6) Using the key for the query URL, put the string in the outState Bundle
        outState.putString(QUERY_URL, urlAddress);
        // COMPLETED (7) Put the contents of the TextView that contains our raw JSON search results into a variable
        String rawJson = mSearchResultsTextView.getText().toString();
        // COMPLETED (8) Using the key for the raw JSON search results, put the search results into the outState Bundle
        outState.putString(RESPONSE_JSON, rawJson);
    }

    public class GithubQueryTask extends AsyncTask<URL, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mLoadingIndicator.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(URL... params) {
            URL searchUrl = params[0];
            String githubSearchResults = null;
            try {
                githubSearchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return githubSearchResults;
        }

        @Override
        protected void onPostExecute(String githubSearchResults) {
            mLoadingIndicator.setVisibility(View.INVISIBLE);
            if (githubSearchResults != null && !githubSearchResults.equals("")) {
                showJsonDataView();
                mSearchResultsTextView.setText(githubSearchResults);
            } else {
                showErrorMessage();
            }
        }
    }
}


text:
package cloudstack

// EnableStorageMaintenance represents the paramter of EnableStorageMaintenance
type EnableStorageMaintenanceParameter struct {
	// Primary storage ID
	Id ID
}

func NewEnableStorageMaintenanceParameter(id string) (p *EnableStorageMaintenanceParameter) {
	p = new(EnableStorageMaintenanceParameter)
	p.Id.Set(id)
	return p
}

// Puts storage pool into maintenance state
func (c *Client) EnableStorageMaintenance(p *EnableStorageMaintenanceParameter) (*StoragePool, error) {
	obj, err := c.Request("enableStorageMaintenance", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*StoragePool), err
}

// UpdateStoragePool represents the paramter of UpdateStoragePool
type UpdateStoragePoolParameter struct {
	// bytes CloudStack can provision from this storage pool
	CapacityBytes NullNumber
	// IOPS CloudStack can provision from this storage pool
	CapacityIops NullNumber
	// the Id of the storage pool
	Id ID
	// comma-separated list of tags for the storage pool
	Tags []string
}

func NewUpdateStoragePoolParameter(id string) (p *UpdateStoragePoolParameter) {
	p = new(UpdateStoragePoolParameter)
	p.Id.Set(id)
	return p
}

// Updates a storage pool.
func (c *Client) UpdateStoragePool(p *UpdateStoragePoolParameter) (*StoragePool, error) {
	obj, err := c.Request("updateStoragePool", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*StoragePool), err
}

// CancelStorageMaintenance represents the paramter of CancelStorageMaintenance
type CancelStorageMaintenanceParameter struct {
	// the primary storage ID
	Id ID
}

func NewCancelStorageMaintenanceParameter(id string) (p *CancelStorageMaintenanceParameter) {
	p = new(CancelStorageMaintenanceParameter)
	p.Id.Set(id)
	return p
}

// Cancels maintenance for primary storage
func (c *Client) CancelStorageMaintenance(p *CancelStorageMaintenanceParameter) (*StoragePool, error) {
	obj, err := c.Request("cancelStorageMaintenance", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*StoragePool), err
}

// CreateStoragePool represents the paramter of CreateStoragePool
type CreateStoragePoolParameter struct {
	// bytes CloudStack can provision from this storage pool
	CapacityBytes NullNumber
	// IOPS CloudStack can provision from this storage pool
	CapacityIops NullNumber
	// the cluster ID for the storage pool
	ClusterId ID
	// the details for the storage pool
	Details map[string]string
	// hypervisor type of the hosts in zone that will be attached to this storage
	// pool. KVM, VMware supported as of now.
	Hypervisor NullString
	// whether the storage should be managed by CloudStack
	Managed NullBool
	// the name for the storage pool
	Name NullString
	// the Pod ID for the storage pool
	PodId ID
	// the storage provider name
	Provider NullString
	// the scope of the storage: cluster or zone
	Scope NullString
	// the tags for the storage pool
	Tags NullString
	// the URL of the storage pool
	Url NullString
	// the Zone ID for the storage pool
	ZoneId ID
}

func NewCreateStoragePoolParameter(name string, url string, zoneid string) (p *CreateStoragePoolParameter) {
	p = new(CreateStoragePoolParameter)
	p.Name.Set(name)
	p.Url.Set(url)
	p.ZoneId.Set(zoneid)
	return p
}

// Creates a storage pool.
func (c *Client) CreateStoragePool(p *CreateStoragePoolParameter) (*StoragePool, error) {
	obj, err := c.Request("createStoragePool", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*StoragePool), err
}

// ListStoragePools represents the paramter of ListStoragePools
type ListStoragePoolsParameter struct {
	// list storage pools belongig to the specific cluster
	ClusterId ID
	// the ID of the storage pool
	Id ID
	// the IP address for the storage pool
	IpAddress NullString
	// List by keyword
	Keyword NullString
	// the name of the storage pool
	Name     NullString
	Page     NullNumber
	PageSize NullNumber
	// the storage pool path
	Path NullString
	// the Pod ID for the storage pool
	PodId ID
	// the ID of the storage pool
	Scope NullString
	// the Zone ID for the storage pool
	ZoneId ID
}

func NewListStoragePoolsParameter() (p *ListStoragePoolsParameter) {
	p = new(ListStoragePoolsParameter)
	return p
}

// Lists storage pools.
func (c *Client) ListStoragePools(p *ListStoragePoolsParameter) ([]*StoragePool, error) {
	obj, err := c.Request("listStoragePools", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.([]*StoragePool), err
}

// DeleteStoragePool represents the paramter of DeleteStoragePool
type DeleteStoragePoolParameter struct {
	// Force destroy storage pool (force expunge volumes in Destroyed state as a
	// part of pool removal)
	Forced NullBool
	// Storage pool id
	Id ID
}

func NewDeleteStoragePoolParameter(id string) (p *DeleteStoragePoolParameter) {
	p = new(DeleteStoragePoolParameter)
	p.Id.Set(id)
	return p
}

// Deletes a storage pool.
func (c *Client) DeleteStoragePool(p *DeleteStoragePoolParameter) (*Result, error) {
	obj, err := c.Request("deleteStoragePool", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Result), err
}

// FindStoragePoolsForMigration represents the paramter of FindStoragePoolsForMigration
type FindStoragePoolsForMigrationParameter struct {
	// the ID of the volume
	Id ID
	// List by keyword
	Keyword  NullString
	Page     NullNumber
	PageSize NullNumber
}

func NewFindStoragePoolsForMigrationParameter(id string) (p *FindStoragePoolsForMigrationParameter) {
	p = new(FindStoragePoolsForMigrationParameter)
	p.Id.Set(id)
	return p
}

// Lists storage pools available for migration of a volume.
func (c *Client) FindStoragePoolsForMigration(p *FindStoragePoolsForMigrationParameter) (*StoragePool, error) {
	obj, err := c.Request("findStoragePoolsForMigration", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*StoragePool), err
}


text:
<?php
/* Prototype  : bool arsort ( array &$array [, int $sort_flags] )
 * Description: Sort an array and maintain index association.
                Elements will be arranged from highest to lowest when this function has completed.
 * Source code: ext/standard/array.c
*/

/*
 * testing arsort() by providing different octal array for $array argument with following flag values
 * 1.flag value as defualt
 * 2.SORT_REGULAR - compare items normally
 * 3.SORT_NUMERIC - compare items numerically
*/

echo "*** Testing arsort() : usage variations ***\n";

// an array contains unsorted octal values
$unsorted_oct_array = array (
   01235 => 01235, 0321 => 0321, 0345 => 0345, 066 => 066, 0772 => 0772,
   077 => 077, -066 => -066, -0345 => -0345, 0 => 0
);

echo "\n-- Testing arsort() by supplying octal value array, 'flag' value is defualt  --\n";
$temp_array = $unsorted_oct_array;
var_dump( arsort($temp_array) ); // expecting : bool(true)
var_dump($temp_array);

echo "\n-- Testing arsort() by supplying octal value array, 'flag' value is SORT_REGULAR  --\n";
$temp_array = $unsorted_oct_array;
var_dump( arsort($temp_array, SORT_REGULAR) ); // expecting : bool(true)
var_dump($temp_array);

echo "\n-- Testing arsort() by supplying octal value array, 'flag' value is SORT_NUMERIC  --\n";
$temp_array = $unsorted_oct_array;
var_dump( arsort($temp_array, SORT_NUMERIC) ); // expecting : bool(true)
var_dump($temp_array);

echo "Done\n";
?>


text:
package net.eusashead.bjugquerydsl.hateoas;

import java.util.ArrayList;
import java.util.List;

import org.springframework.web.util.UriTemplate;

import com.theoryinpractise.halbuilder.api.Representation;
import com.theoryinpractise.halbuilder.api.RepresentationFactory;

public class RepresentationConverterImpl implements RepresentationConverter {

	private final RepresentationFactory representationFactory;

	private final List<ResourceMetadataExtractor> extractors = new ArrayList<ResourceMetadataExtractor>();

	private final SimplePropertyConverter simplePropertyConverter;

	public RepresentationConverterImpl(RepresentationFactory representationFactory, SimplePropertyConverter simplePropertyConverter) {
		this.representationFactory = representationFactory;
		this.simplePropertyConverter = simplePropertyConverter;
	}

	public void registerExtractor(ResourceMetadataExtractor extractor) {
		this.extractors.add(extractor);
	}

	/* (non-Javadoc)
	 * @see net.eusashead.bjugquerydsl.hateoas.RepresentationConverter#convert(java.lang.Object)
	 */
	@Override
	public Representation convert(Object bean) {
		return convert(bean, null, true);
	}

	/* (non-Javadoc)
	 * @see net.eusashead.bjugquerydsl.hateoas.RepresentationConverter#convert(java.lang.Object, java.lang.String)
	 */
	@Override
	public Representation convert(Object bean, String...properties) {
		return convert(bean, null, true, properties);
	}

	/* (non-Javadoc)
	 * @see net.eusashead.bjugquerydsl.hateoas.RepresentationConverter#convert(java.lang.Object, org.springframework.web.util.UriTemplate, java.lang.String)
	 */
	@Override
	public Representation convert(Object bean, UriTemplate uriTemplate, String...properties) {
		return convert(bean, uriTemplate, true, properties);
	}

	private Representation convert(Object bean, UriTemplate uriTemplate,
			boolean recursive, String... properties) {

		// Validate arguments
		if (bean == null) {
			throw new IllegalArgumentException("Cannot pass null bean to convert()");
		}

		Class<?> target = bean.getClass();

		// Get the ResourceMetadataExtractor
		ResourceMetadataExtractor extractor = findMatchingExtractor(target);

		// Get the metadata
		ResourceMetadata metadata = extractor.extract(target);

		// Get the URI template from metadata or argument
		uriTemplate = uriTemplate != null ? uriTemplate : metadata.getUriTemplate();

		// Get the URI from the template
		String uri = null;
		if (uriTemplate != null) {
			uri = uriTemplate.expand(metadata.getUriVariables(bean)).toString();
		}

		// Create the representation
		Representation representation = representationFactory.newRepresentation(uri);

		// Determine the scope
		List<Property> scope;
		if (properties == null || properties.length == 0) {
			scope = metadata.getAllProperties();
		} else {
			scope = metadata.getPropertiesByName(properties);
		}

		// Copy the properties
		for (Property property : scope) {

			// Get the property value
			Object value = property.getValue(bean);

			// Copy if not null
			if (value != null) {

				// Is it an embedded resource or a property
				if (EmbeddedResource.class.isAssignableFrom(property.getClass())) {

					// Only copy embedded if recursive
					if (recursive) {

						// Add the embedded resource
						EmbeddedResource embedded = EmbeddedResource.class.cast(property);
						addRepresentation(representation, embedded.getName(), embedded.getUriTemplate(), value);
					}
				} else {

					// It's a simple property, add it
					addProperty(representation, property.getName(), value);
				}
			}
		}
		return representation;
	}

	/**
	 * Find a {@link ResourceMetadataExtractor}
	 * that can extract {@link ResourceMetadata}
	 * for the given {@link Class}
	 * @param target
	 * @return
	 */
	private ResourceMetadataExtractor findMatchingExtractor(
			Class<? extends Object> target) {
		for (ResourceMetadataExtractor extractor : extractors) {
			if (extractor.canExtract(target)) {
				return extractor;
			}
		}
		throw new RuntimeException(String.format("No matching ResourceMetadataExtractor for class %s", target));
	}

	/* (non-Javadoc)
	 * @see net.eusashead.bjugquerydsl.hateoas.RepresentationConverter#addProperty(com.theoryinpractise.halbuilder.api.Representation, java.lang.String, java.lang.Object)
	 */
	@Override
	public void addProperty(Representation representation, String name, Object value) {
		if (SimplePropertyUtil.isSimpleProperty(value.getClass())) {
			Object converted = simplePropertyConverter.convert(value, String.class);
			representation.withProperty(name, converted);
		} else {
			throw new IllegalArgumentException(String.format("Property %s of type %s is not a simple property", name, value.getClass()));
		}
	}

	/* (non-Javadoc)
	 * @see net.eusashead.bjugquerydsl.hateoas.RepresentationConverter#addRepresentation(com.theoryinpractise.halbuilder.api.Representation, java.lang.String, java.lang.Object)
	 */
	@Override
	public void addRepresentation(Representation representation, String rel, Object value) {
		addRepresentation(representation, rel, null, value);
	}

	/* (non-Javadoc)
	 * @see net.eusashead.bjugquerydsl.hateoas.RepresentationConverter#addRepresentation(com.theoryinpractise.halbuilder.api.Representation, java.lang.String, org.springframework.web.util.UriTemplate, java.lang.Object)
	 */
	@Override
	public void addRepresentation(Representation representation, String rel, UriTemplate uriTemplate, Object value) {

		if (!SimplePropertyUtil.isSimpleProperty(value.getClass())) {
			// Handle collections
			if (Iterable.class.isAssignableFrom(value.getClass())) {
				for (Object obj : Iterable.class.cast(value)) {
					// Create a representation
					Representation child = this.convert(obj, uriTemplate, false);
					representation.withRepresentation(rel, child);
				}
			} else {
				// Create a representation
				Representation child = this.convert(value, uriTemplate, false);
				representation.withRepresentation(rel, child);
			}
		} else {
			throw new IllegalArgumentException(String.format("Property %s of type %s is not a representation type", rel, value.getClass()));
		}
	}

}


text:
A simple [socket.io](socket.io)-like Javascript front-end for Django Channels apps.

## Django Channels and `channel.js`

NodeJS' [socket.io](http://socket.io/) provides the simplest client-side API for developing websocket-based real-time applications. [Django Channels](https://channels.readthedocs.io/en/latest/) provides a simple and powerful backend API for managing real-time communications that easily ties in with [Django's ORM](http://tutorial.djangogirls.org/en/django_orm/). This project aims to provide a socket.io-like Javascript API for simple real-time applications.

## Getting started

Simply add the following references to your client-side HTML markup:
```html
<script type="text/javascript" src="
https://raw.githubusercontent.com/k-pramod/channel.js/master/dist/reconnecting-websocket.js"></script>
<script type="text/javascript" src="
https://raw.githubusercontent.com/k-pramod/channel.js/master/dist/channel-0.2.0.js"></script>
```

Or clone this repo and use the latest files from the `dist` directory.

## Documentation

Check out this [project's API](channel.md) and [brief tutorial](tutorial.md) in the [`docs`](docs) directory.

## Example

This project features a fully-worked, front-to-back example that illustrates how `channel.js` and Django Channels tie in together. Find the source code in the [`examples/chatter`](examples/chatter) directory where brief setup instructions can also be found.

## Future work

Features to be implemented in the near future include:

* More diverse examples with ['Deploy to Heroku'](https://devcenter.heroku.com/articles/heroku-button) buttons

## Contributing

If you would like to propose new features, please use this repo's [GitHub Issue tracker](https://github.com/k-pramod/channel.js/issues). If you would like to submit code to be included in future releases, please fork this repo and submit Pull Requests.

---
[Pramod Kotipalli](http://pramodk.net/)


text:
"use strict";

// Initial file from https://github.com/rolandstarke/node-cache-manager-fs-hash @ af52d2d

/**
 * adds an callback param to the original function
 * @param {function} fn
 * @returns {function}
 */
module.exports = function wrapCallback(fn) {
  return function (...args) {
    let cb;

    if (typeof args[args.length - 1] === `function`) {
      cb = args.pop();
    }

    const promise = fn.apply(this, args);

    if (typeof cb === `function`) {
      promise.then(value => setImmediate(cb, null, value), err => setImmediate(cb, err));
    }

    return promise;
  };
};
//# sourceMappingURL=wrap-callback.js.map


text:
package myCoolApps;

import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

public class ClipboardDetails {

	/**
	 * http://www.codeproject.com/Articles/227478/Cool-Java-Programs
	 * @param args
	 * @throws IOException
	 * @throws UnsupportedFlavorException
	 */
	public static void main(String[] args) throws UnsupportedFlavorException, IOException {
		Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
		if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
			String text = (String)t.getTransferData(DataFlavor.stringFlavor);
			System.out.println("Current ClipBoard data is:\n"+text);
			text="I changed clipboard text";
			StringSelection ss = new StringSelection(text);
			Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
			System.out.println("Changed ClipBoard data is:\n"+text);
		}
	}

}


text:
FROM google/cloud-sdk

# Add the server to respond to HTTP requests at port 8080.
COPY epoxy_boot_server /
RUN chmod -R a+rx /epoxy_boot_server
ENTRYPOINT ["/epoxy_boot_server"]


text:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using BeeDevelopment.Brazil;
using BeeDevelopment.Sega8Bit.Hardware.Controllers;
using BeeDevelopment.Sega8Bit.Mappers;
using BeeDevelopment.Zip;
using System.Globalization;

#if SILVERLIGHT
using EnumEx = System.EnumEx;
using ArrayEx = System.ArrayEx;
#else
using EnumEx = System.Enum;
using ArrayEx = System.Array;
#endif

namespace BeeDevelopment.Sega8Bit.Utility {
	public static class SaveState {

		#region Public Methods

		/// <summary>
		/// Saves the state of an <see cref="Emulator"/> to a <see cref="ZipFile"/>.
		/// </summary>
		/// <param name="emulator">The <see cref="Emulator"/> state to save.</param>
		/// <param name="zipFile">The <see cref="ZipFile"/> to save the state to.</param>
		public static void Save(Emulator emulator, ZipFile zipFile) {

#if !SILVERLIGHT

			lock (emulator) {

				emulator.Sound.FlushQueuedWrites();
				emulator.FmSound.FlushQueuedWrites();

				IniSerialiseObject(emulator, "", "Main.ini", zipFile);
				IniSerialiseObject(emulator.Video, "Video", "Video.ini", zipFile);
				IniSerialiseObject(emulator.Sound, "Sound", "PSG.ini", zipFile);
#if EMU2413
				IniSerialiseObject(emulator.FmSound, @"Sound\OPLL", "YM2413.ini", zipFile);

				IniSerialiseObject(emulator.FmSound.Opll, @"Sound\OPLL\emu2413", "State.ini", zipFile);
				for (int i = 0; i < emulator.FmSound.Opll.Patch.Length; ++i) IniSerialiseObject(emulator.FmSound.Opll.Patch[i], @"Sound\OPLL\emu2413\Patches", string.Format(CultureInfo.InvariantCulture, "{0:D2}.ini", i), zipFile);
				for (int i = 0; i < emulator.FmSound.Opll.Slot.Length; ++i) {
					IniSerialiseObject(emulator.FmSound.Opll.Slot[i], string.Format(CultureInfo.InvariantCulture, @"Sound\OPLL\emu2413\Slots\{0:D2}", i), "Slot.ini", zipFile);
					IniSerialiseObject(emulator.FmSound.Opll.Slot[i].Patch, string.Format(CultureInfo.InvariantCulture, @"Sound\OPLL\emu2413\Slots\{0:D2}", i), "Patch.ini", zipFile);
				}
#endif
				for (int i = 0; i < 2; ++i) {
					IniSerialiseObject(emulator.SegaPorts[i], Path.Combine(@"Controllers\Sega", i.ToString()), "Port.ini", zipFile);
					foreach (var Property in emulator.SegaPorts[i].GetType().GetProperties()) {
						if (Property.PropertyType == typeof(SegaControllerPort.UnidirectionalPin) || Property.PropertyType == typeof(SegaControllerPort.BidirectionalPin)) {
							IniSerialiseObject(Property.GetValue(emulator.SegaPorts[i], null), Path.Combine(@"Controllers\Sega", i.ToString()), Property.Name + ".ini", zipFile);
						}
					}
				}

				foreach (var Property in emulator.GetType().GetProperties()) {
					if (Property.PropertyType == typeof(MemoryDevice)) {
						IniSerialiseObject(Property.GetValue(emulator, null), Path.Combine("Memory", Property.Name), Property.Name + ".ini", zipFile);
					}
				}
			}

#endif

		}

		/// <summary>
		/// Loads the state of an <see cref="Emulator"/> from a <see cref="ZipFile"/>.
		/// </summary>
		/// <param name="emulator">The emulator to load into.</param>
		/// <param name="zipFile">The <see cref="ZipFile"/> to load the state from.</param>
		public static void Load(out Emulator emulator, ZipFile zipFile) {
#if SILVERLIGHT
			emulator = null;
#else
			emulator = (Emulator)IniDeserialiseObject(null, "", "Main.ini", zipFile);
			lock (emulator) {
				IniDeserialiseObject(emulator.Video, "Video", "Video.ini", zipFile);
				IniDeserialiseObject(emulator.Sound, "Sound", "PSG.ini", zipFile);
#if EMU2413
				IniDeserialiseObject(emulator.FmSound, @"Sound\OPLL", "YM2413.ini", zipFile);
				IniDeserialiseObject(emulator.FmSound.Opll, @"Sound\OPLL\emu2413", "State.ini", zipFile);
				for (int i = 0; i < emulator.FmSound.Opll.Patch.Length; ++i) {
					var P = emulator.FmSound.Opll.Patch[i];
					IniDeserialiseObject(P, @"Sound\OPLL\emu2413\Patches", string.Format(CultureInfo.InvariantCulture, "{0:D2}.ini", i), zipFile);
					emulator.FmSound.Opll.Patch[i] = P;
				}
				for (int i = 0; i < emulator.FmSound.Opll.Slot.Length; ++i) {
					var S = emulator.FmSound.Opll.Slot[i];
					IniDeserialiseObject(S, string.Format(CultureInfo.InvariantCulture, @"Sound\OPLL\emu2413\Slots\{0:D2}", i), "Slot.ini", zipFile);
					var P = S.Patch;
					IniDeserialiseObject(P, string.Format(CultureInfo.InvariantCulture, @"Sound\OPLL\emu2413\Slots\{0:D2}", i), "Patch.ini", zipFile);
					S.Patch = P;
					emulator.FmSound.Opll.Slot[i] = S;
				}
				emulator.FmSound.Update();
#endif
				for (int i = 0; i < 2; ++i) {
					IniDeserialiseObject(emulator.SegaPorts[i], Path.Combine(@"Controllers\Sega", i.ToString()), "Port.ini", zipFile);
					foreach (var Property in emulator.SegaPorts[i].GetType().GetProperties()) {
						if (Property.PropertyType == typeof(SegaControllerPort.UnidirectionalPin) || Property.PropertyType == typeof(SegaControllerPort.BidirectionalPin)) {
							var DeserialisedPort = IniDeserialiseObject(Property.GetValue(emulator.SegaPorts[i], null), Path.Combine(@"Controllers\Sega", i.ToString()), Property.Name + ".ini", zipFile);
							if (DeserialisedPort != null) Property.SetValue(emulator.SegaPorts[i], DeserialisedPort, null);
						}
					}
				}

				foreach (var Property in emulator.GetType().GetProperties()) {
					if (Property.PropertyType == typeof(MemoryDevice)) {
						IniDeserialiseObject(Property.GetValue(emulator, null), Path.Combine("Memory", Property.Name), Property.Name + ".ini", zipFile);
					}
				}
			}
#endif
		}

		#endregion

		#region Private Methods

		/// <summary>
		/// Serialise an object to an ini file inside a zip archive.
		/// </summary>
		/// <param name="toSerialise">The object to serialise.</param>
		/// <param name="iniDirectory">The directory inside the zip archive to store the ini file in.</param>
		/// <param name="iniFilename">The name of the ini file.</param>
		/// <param name="zipFile">The zip file to add the ini file to.</param>
		private static void IniSerialiseObject(object toSerialise, string iniDirectory, string iniFilename, ZipFile zipFile) {

			var IniFile = new StringBuilder(2048);

			IniFile.AppendLine(string.Format(@"[Type({0})]", toSerialise.GetType().FullName));

			foreach (var Property in toSerialise.GetType().GetProperties()) {
				if (Property.CanRead) {
					if (Property.GetCustomAttributes(typeof(StateNotSavedAttribute), false).Length == 0) {
						var Value = Property.GetValue(toSerialise, null);
						if (Value != null) {
							if (Property.PropertyType.IsPrimitive || Value is Enum) {
								IniFile.AppendLine(string.Format("{0}={1}", Property.Name, Value));
							} else if (Property.PropertyType.IsArray && Property.PropertyType.GetElementType() == typeof(byte)) {
								string RawDataName = Path.Combine(iniDirectory, Property.Name + ".bin");
								zipFile.Add(new ZipFileEntry() {
									Name = RawDataName,
									Data = (byte[])Value,
								});
								IniFile.AppendLine(string.Format("{0}=Dump({1})", Property.Name, RawDataName));
							} else if (Property.PropertyType.IsArray && (Property.PropertyType.GetElementType() == typeof(short) || Property.PropertyType.GetElementType() == typeof(ushort))) {
								string RawDataName = Path.Combine(iniDirectory, Property.Name + ".bin");
								using (var DumpedShorts= new MemoryStream()) {
									using (var ShortWriter = new BinaryWriter(DumpedShorts)) {
										foreach (var i in (short[])Value) ShortWriter.Write(i);
									}
									zipFile.Add(new ZipFileEntry() {
										Name = RawDataName,
										Data = DumpedShorts.ToArray(),
									});
								}
								IniFile.AppendLine(string.Format("{0}=Dump({1})", Property.Name, RawDataName));
							} else if (Property.PropertyType.IsArray && (Property.PropertyType.GetElementType() == typeof(int) || Property.PropertyType.GetElementType() == typeof(uint))) {
								string RawDataName = Path.Combine(iniDirectory, Property.Name + ".bin");
								using (var DumpedInts = new MemoryStream()) {
									using (var IntWriter = new BinaryWriter(DumpedInts)) {
										foreach (var i in (int[])Value) IntWriter.Write(i);
									}
									zipFile.Add(new ZipFileEntry() {
										Name = RawDataName,
										Data = DumpedInts.ToArray(),
									});
								}
								IniFile.AppendLine(string.Format("{0}=Dump({1})", Property.Name, RawDataName));
							} else {
								IniFile.AppendLine(string.Format("; {0} (Type: {1})", Property.Name, Property.PropertyType));
							}
						}
					}
				}

			}

			if (toSerialise is MemoryDevice && ((MemoryDevice)toSerialise).Memory != null) {
				IniSerialiseObject(((MemoryDevice)toSerialise).Memory, iniDirectory, "Memory.ini", zipFile);
			}

			zipFile.Add(new ZipFileEntry() {
				Name = Path.Combine(iniDirectory, iniFilename),
				Data = Encoding.UTF8.GetBytes(IniFile.ToString()),
			});
		}

		private static object IniDeserialiseObject(object toDeserialiseInto, string iniDirectory, string iniFilename, ZipFile zipFile) {

			var SourceData = zipFile[Path.Combine(iniDirectory, iniFilename)];
			if (SourceData == null) return null; // No entry in the zip file.
			var IniLines = ArrayEx.ConvertAll(Encoding.UTF8.GetString(SourceData.Data).Split('\n'), s => s.Split(';')[0].Trim());

			object Result = toDeserialiseInto;

			foreach (var IniItem in IniLines) {

				if (string.IsNullOrEmpty(IniItem)) continue;

				if (IniItem.StartsWith("[") && IniItem.EndsWith("]")) {
					// Section and/or attribute.
					var SectionHeader = IniItem.Substring(1, IniItem.Length - 2);
					if (SectionHeader.StartsWith("Type(") && SectionHeader.EndsWith(")")) {
						if (toDeserialiseInto == null) {
							var TypeName = SectionHeader.Substring(5, SectionHeader.Length - 6);
							var ObjectType = Type.GetType(TypeName);
							if (ObjectType == null) throw new InvalidDataException("Cannot deserialise object of type '" + TypeName + "'.");
							Result = ObjectType.GetConstructor(Type.EmptyTypes).Invoke(null);
						}
					}
				} else {
					var Parameter = ArrayEx.ConvertAll(IniItem.Split('='), s => s.Trim());
					if (Result == null) throw new InvalidDataException("Cannot set parameter before type is specified.");
					if (Parameter.Length != 2) throw new InvalidDataException("Invalid parameter.");

					var Property = Result.GetType().GetProperty(Parameter[0]);
					if (Property == null) continue; // No matching property found, but no matter.
					if (!Property.CanWrite) continue; // No setter, but no matter.

					ZipFileEntry DumpedData = null;
					if (Parameter[1].StartsWith("Dump(") && Parameter[1].EndsWith(")")) {
						DumpedData = zipFile[Parameter[1].Substring(5, Parameter[1].Length - 6)];
					}

					if (Property.PropertyType.IsPrimitive) {
						Property.SetValue(Result, Convert.ChangeType(Parameter[1], Property.PropertyType, CultureInfo.CurrentCulture), null);
					} else if (Property.PropertyType.BaseType == typeof(Enum)) {
						foreach (var EnumValue in EnumEx.GetValues(Property.PropertyType)) {
							if (EnumValue.ToString() == Parameter[1]) {
								Property.SetValue(Result, EnumValue, null);
							}
						}
					} else if (Property.PropertyType.IsArray && Property.PropertyType.GetElementType() == typeof(byte)) {
						if (DumpedData != null) { Property.SetValue(Result, DumpedData.Data, null); }
					} else if (Property.PropertyType.IsArray && (Property.PropertyType.GetElementType() == typeof(short) || Property.PropertyType.GetElementType() == typeof(ushort))) {
						if (DumpedData != null) {
							var ShortArray = new short[DumpedData.Data.Length / 2];
							for (int i = 0; i < ShortArray.Length; ++i) ShortArray[i] = BitConverter.ToInt16(DumpedData.Data, i * 2);
							if (Property.PropertyType.GetElementType() == typeof(short)) {
								Property.SetValue(Result, ShortArray, null);
							} else if (Property.PropertyType.GetElementType() == typeof(ushort)) {
								Property.SetValue(Result, ArrayEx.ConvertAll(ShortArray, i => (ushort)i), null);
							}

						}
					} else if (Property.PropertyType.IsArray && (Property.PropertyType.GetElementType() == typeof(int) || Property.PropertyType.GetElementType() == typeof(uint))) {
						if (DumpedData != null) {
							var IntArray = new int[DumpedData.Data.Length / 4];
							for (int i = 0; i < IntArray.Length; ++i) IntArray[i] = BitConverter.ToInt32(DumpedData.Data, i * 4);
							if (Property.PropertyType.GetElementType() == typeof(int)) {
								Property.SetValue(Result, IntArray, null);
							} else if (Property.PropertyType.GetElementType() == typeof(uint)) {
								Property.SetValue(Result, ArrayEx.ConvertAll(IntArray, i => (uint)i), null);
							}

						}
					} else {
						// Not deserialised.
					}

				}
			}

			if (Result is MemoryDevice) {
				((MemoryDevice)Result).Memory = IniDeserialiseObject(null, iniDirectory, "Memory.ini", zipFile) as IMemoryMapper;
			}

			if (Result is IDeserializationCallback) ((IDeserializationCallback)Result).OnDeserialization(null);

			return Result;
		}

		#endregion
	}
}


text:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources>

    <!-- common use通用字符串 -->
    <string name="app_name">appcantemplate</string>
    <string name="back">返回</string>
    <string name="confirm">确定</string>
    <string name="cancel">取消</string>
    <string name="prompt">提示</string>
    <string name="complete">完成</string>
    <string name="path_error">路径错误!</string>
    <string name="settings">设置</string>
    <string name="save">保存</string>
    <string name="select_all">全选</string>
    <string name="cancel_select_all">取消选定</string>
    <string name="select">选择</string>
    <string name="can_not_find_suitable_app_perform_this_operation">找不到适合的程序执行此操作!</string>
    <string name="exit">退出</string>
    <string name="confirm_delete">确定删除</string>
    <string name="ma">吗?</string>
    <string name="exit_message_server">该应用暂停服务</string>
    <string name="exit_message_appid">当前应用ID非法</string>
    <string name="error_parameter">参数错误</string>
    <string name="no_have_read_limits_power">没有读取权限</string>
    <string name="no_have_write_limits_power">没有写入权限</string>
    <string name="error_sdcard_is_not_available">SD卡不可用</string>
    <string name="error_file_does_not_exist">文件不存在</string>
    <string name="error_no_permisson_RW">没有读写权限</string>
    <string name="error_no_permisson_INTERNET">没有网络访问权限</string>
    <string name="no_permisson_declare">没有申明相关权限</string>
    <string name="info_update">发现新版本,是否升级?</string>

    <!-- browser use -->
    <string name="browser_exitdialog_app_text">确定要退出程序吗?</string>
    <string name="browser_exitdialog_msg">退出提示</string>
    <string name="browser_dialog_error">错误提示</string>
    <string name="browser_init_error">程序不完整</string>
    <!-- 3000.1.02.000.00.00.9999.000 -->
    <!-- Analytics config -->
    <string name="appkey" translatable="false">38c2a32f-999b-2cf3-3971-71bb074b2f27</string>
    <string name="appstatus" translatable="false">6E4E99740100CFB7447DAB9CCC55DD75F7D658</string>
    <string name="push" translatable="false">true</string>
    <string name="certificate_psw" translatable="false" />
    <string name="widget_startup_report_host" translatable="false">http://newdc.appcan.cn/</string>
    <string name="push_host" translatable="false">newpush.appcan.cn:1883</string>
    <string name="bindUser_host" translatable="false">http://newpush.appcan.cn/</string>
    <string name="analytics_host" translatable="false">http://newdc.appcan.cn/</string>
    <string name="mam_host" translatable="false">http://newdc.appcan.cn/</string>
    <string name="mam_push_host_and_port" translatable="false">newpush.appcan.cn:1883</string>

    <!-- platform myspace  use -->
    <string name="platform_myspace_app_center">应用中心</string>
    <string name="platform_myspace_recommend_apps">推荐应用</string>
    <string name="platform_myspace_my_apps">我的应用</string>
    <string name="platform_myspace_pull_to_refresh">下拉刷新推荐列表</string>
    <string name="platform_myspace_release_to_refresh">释放刷新推荐列表</string>
    <string name="platform_myspace_loading">加载中…</string>
    <string name="platform_myspace_tap_to_refresh">点击刷新推荐列表</string>
    <string name="widgetone_version" translatable="false">4030.1.02.001.00.00.9999.000</string>
    <string name="platform_no_configuration_decryption_permissions">没有配置解密权限!</string>
    <string name="platform_downloading_file">正在下载文件</string>
    <string name="platform_connect_failed">连接失败,请重试!</string>
    <string name="platform_download_failed">下载出错,请重试!</string>
    <string name="platform_only_test">测试版本仅用于开发测试</string>
    <string name="platform_choose_app">请选择:</string>
    <string name="platform_widget_id_not_exist">AppId为 %1$s 的Widget不存在</string>
    <string name="platform_widget_path_not_exist">路径为 %1$s 的Widget不存在</string>
    <string name="platform_widget_search_failed">搜索Widget发生异常!请确认Widget是否损坏!</string>
    <string name="warning">警告</string>
    <string name="no_permission_to_open_window">没有打开%1$s窗口的权限</string>
    <string name="load_uex_object_error">uex对象加载发生异常,请检查XML文件!</string>
    <string name="install">安装…</string>
    <string name="install_failed">安装失败</string>
    <string name="get_open_login_list">尚未登录,正在获取开放平台登录列表</string>
    <string name="operation_cancel">操作已取消!</string>
    <string name="get_info_failed">获取信息失败!</string>
    <string name="download_info_error">下载信息错误!</string>
    <string name="app_has_download_please_run">应用已下载,请直接运行</string>
    <string name="app_downloading">应用正在下载请稍候…</string>
    <string name="get_user_info">正在获取用户登录信息…</string>
    <string name="get_login_list">尚未登录,获取登录列表…</string>
    <string name="app_is_download_please_wait">应用正在下载请稍候…</string>
    <string name="get_user_info_failed">获取登录信息失败!</string>
    <string name="delete">删除</string>
    <string name="is_uninstalling">正在卸载…</string>
    <string name="login_failed">登录失败…</string>
    <string name="select_operation">请选择操作</string>
    <string name="cannot_find_this_widget">未找到此widget,无法启动!</string>
    <string name="refresh_success">更新成功!</string>
    <string name="refresh_failed">刷新失败</string>
    <string name="plugin_config_no_exist">插件配置文件不存在!</string>
    <string name="more">更多</string>
    <string name="widget_not_exist_id_path">在%1$s目录下的 appId 是%2$s的widget不存在</string>
    <string name="not_any_widget">该应用下没有任何widget</string>

    <!-- uexPedometer -->
    <string name="plugin_pedometer_step_service_ticker">开始后台记步</string>
    <string name="plugin_pedometer_step_number">步</string>
    <string name="plugin_pedometer_step_calorie">千卡</string>

</resources>


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateElementSetsTable extends Migration
{

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('reg_schema', function(Blueprint $table)
		{
			$table->increments('id');
			$table->integer('id', true);
			$table->integer('agent_id');
			$table->dateTime('created_at');
			$table->dateTime('updated_at');
			$table->dateTime('deleted_at');
			$table->integer('created_user_id');
			$table->integer('updated_user_id');
			$table->dateTime('child_updated_at');
			$table->integer('child_updated_user_id');
			$table->string('name', 255);
			$table->text('note');
			$table->string('uri', 255);
			$table->string('url', 255);
			$table->string('base_domain', 255);
			$table->string('token', 255);
			$table->string('community', 255);
			$table->integer('last_uri_id');
			$table->integer('status_id');
			$table->string('language', 255);
			$table->integer('profile_id');
			$table->string('ns_type', 255);
			$table->text('prefixes');
			$table->text('languages');
			$table->string('repo', 255);
			$table->timestamps();
			$table->softDeletes();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('reg_schema');
	}

}


text:
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using Framework.Core.Configuration;
using Framework.Core.Helpers.Images;

namespace Framework.Core
{
    /// <summary>
    /// Registers standard framework components.
    /// </summary>
    public class CoreInstaller : IWindsorInstaller
    {
        #region IWindsorInstaller

        /// <summary>
        /// Performs the installation in the <see cref="T:Castle.Windsor.IWindsorContainer"/>.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="store">The configuration store.</param>
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(Component.For<IConfigurationManager>()
                                .ImplementedBy<ConfigurationManagerWrapper>()
                                .Named("configuration_manager"));

            container.Register(Component.For<IApplicationConfigurator>()
                                .ImplementedBy<YamlDatabaseConfigurator>()
                                .Named("database_configurator")
                                .Parameters(Parameter.ForKey("configPath").Eq("Config/database.yml")));

            container.Register(Component.For<IImageUtility>()
                                .ImplementedBy<DefaultImageUtility>()
                                .Named("image_utility"));
        }

        #endregion
    }
}


text:
extern crate cdrs;
extern crate r2d2;

use std::thread;

use cdrs::client::CDRS;
use cdrs::authenticators::PasswordAuthenticator;
use cdrs::compression::Compression;
use cdrs::frame::events::{SimpleServerEvent, ServerEvent, ChangeType, Target};
use cdrs::transport::TransportTcp;

// default credentials
const _USER: &'static str = "cassandra";
const _PASS: &'static str = "cassandra";
const _ADDR: &'static str = "127.0.0.1:9042";

fn main() {
    let transport = TransportTcp::new(_ADDR).unwrap();
    let authenticator = PasswordAuthenticator::new(_USER, _PASS);
    let client = CDRS::new(transport, authenticator);
    let session = client.start(Compression::None).unwrap();

    let (mut listener, stream) = session
        .listen_for(vec![SimpleServerEvent::SchemaChange])
        .unwrap();

    thread::spawn(move || listener.start(&Compression::None).unwrap());

    let new_tables = stream
        // inspects all events in a stream
        .inspect(|event| println!("inspect event {:?}", event))
        // filter by event's type: schema changes
        .filter(|event| event == &SimpleServerEvent::SchemaChange)
        // filter by event's specific information: new node was added
        .filter(|event| {
            match event {
                &ServerEvent::SchemaChange(ref event) => {
                    event.change_type == ChangeType::Created && event.target == Target::Table
                },
                _ => false
            }
        });

    println!("Start listen for server events");

    for change in new_tables {
        println!("server event {:?}", change);
    }
}


text:
package science.atlarge.graphalytics.neo4j.metrics;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;

import java.io.FileWriter;
import java.io.IOException;

import static science.atlarge.graphalytics.neo4j.Neo4jConstants.ID_PROPERTY;

/**
 * Generic class for serializing the output of a metric.
 *

 * This class assumes that:
 *

 *
the results are stored as properties

 *
the results are descendant of the {@link Number} class

 *

 *
 * @param <N> is the type of variable
 *
 * @author Bálint Hegyi
 */
public class OutputSerializer<N extends Number> {

    private final String property;
    private final N defaultValue;

    /**
     * Instantiates a new {@link OutputSerializer}
     * @param property the name of the property storing the result
     * @param defaultValue a value which should be used if the property is not
     *                     set on a node
     */
    public OutputSerializer(String property, N defaultValue) {
        this.property = property;
        this.defaultValue = defaultValue;
    }

    /**
     * Serializes the {@code graphDatabase} parameter into the file {@code outputPath}
     *

     * The serialization will decide what format it should write out the results:
     *

     *
{@link Double} or {@link Float}: in scientific notation

     *
Else: decimal number notation

     *

     *
     * @param graphDatabase the database serialized
     * @param outputPath the path where the output file should be written
     * @throws IOException when the file cannot be opened
     */
    public void serialize(
            GraphDatabaseService graphDatabase,
            String outputPath) throws IOException {
        try (FileWriter writer = new FileWriter(outputPath)) {
            try (Transaction ignored = graphDatabase.beginTx()) {
                for (Node node : graphDatabase.getAllNodes()) {
                    writer.write(serializeValue(node, this.property) + "\n");
                }
            }
        }
    }

    private String serializeValue(Node node, String property) {
        long id = ((Number) node.getProperty(ID_PROPERTY)).longValue();
        N value = (N) node.getProperty(property, this.defaultValue);

        if (value instanceof Double || value instanceof Float) {
            return String.format("%d %e", id, value.doubleValue());
        } else {
            return String.format("%d %d", id, value.longValue());
        }

    }
}