text:
Test the PDO::query() method.
--ENV--
PHPT_EXEC=true
--SKIPIF--
<?php require('skipif_mid-refactor.inc'); ?>
--FILE--
<?php
require_once("MsCommon_mid-refactor.inc");
require_once("MsData_PDO_AllTypes.inc");

function queryDefault($conn, $tbname)
{
    $stmt = $conn->query("Select * from $tbname");
    $result = $stmt->fetch();
    var_dump($result);
}

function queryColumn($conn, $tbname)
{
    $stmt = $conn->query("Select * from $tbname", PDO::FETCH_COLUMN, 2);
    $result = $stmt->fetch();
    var_dump($result);
}

function queryClass($conn, $tbname)
{
    global $mainTypesClass;
    $stmt = $conn->query("Select * from $tbname", PDO::FETCH_CLASS, $mainTypesClass);
    $result = $stmt->fetch();
    $result->dumpAll();
}

function queryInto($conn, $tbname)
{
    global $mainTypesClass;
    $obj = new $mainTypesClass;
    $stmt = $conn->query("Select * from $tbname", PDO::FETCH_INTO, $obj);
    $result = $stmt->fetch();
    $result->dumpAll();
}

function queryEmptyTable($conn)
{
    createTable($conn, 'emptyTable', array("c1" => "int", "c2" => "int"));
    $stmt = $conn->query("Select * from emptyTable");
    $result = $stmt->fetch();
    var_dump($result);
    dropTable($conn, 'emptyTable');
}

try {
    $db = connect();
    $tbname = "PDO_MainTypes";
    createAndInsertTableMainTypes($db, $tbname);
    echo "TEST_1 : query with default fetch style :\n";
    queryDefault($db, $tbname);

    echo "TEST_2 : query with FETCH_COLUMN :\n";
    queryColumn($db, $tbname);

    echo "TEST_3 : query with FETCH_CLASS :\n";
    queryClass($db, $tbname);

    echo "TEST_4 : query with FETCH_INTO :\n";
    queryInto($db, $tbname);

    echo "TEST_5 : query an empty table :\n";
    queryEmptyTable($db);

    dropTable($db, $tbname);
    unset($db);
} catch (PDOException $e) {
    var_dump($e);
    exit;
}

?>
--EXPECT--
TEST_1 : query with default fetch style :
array(16) {
  ["IntCol"]=>
  string(1) "1"
  [0]=>
  string(1) "1"
  ["CharCol"]=>
  string(10) "STRINGCOL1"
  [1]=>
  string(10) "STRINGCOL1"
  ["NCharCol"]=>
  string(10) "STRINGCOL1"
  [2]=>
  string(10) "STRINGCOL1"
  ["DateTimeCol"]=>
  string(23) "2000-11-11 11:11:11.110"
  [3]=>
  string(23) "2000-11-11 11:11:11.110"
  ["VarcharCol"]=>
  string(10) "STRINGCOL1"
  [4]=>
  string(10) "STRINGCOL1"
  ["NVarCharCol"]=>
  string(10) "STRINGCOL1"
  [5]=>
  string(10) "STRINGCOL1"
  ["FloatCol"]=>
  string(7) "111.111"
  [6]=>
  string(7) "111.111"
  ["XmlCol"]=>
  string(431) "<xml> 1 This is a really large string used to test certain large data types like xml data type. The length of this string is greater than 256 to correctly test a large data type. This is currently used by atleast varchar type and by xml type. The fetch tests are the primary consumer of this string to validate that fetch on large types work fine. The length of this string as counted in terms of number of characters is 417.</xml>"
  [7]=>
  string(431) "<xml> 1 This is a really large string used to test certain large data types like xml data type. The length of this string is greater than 256 to correctly test a large data type. This is currently used by atleast varchar type and by xml type. The fetch tests are the primary consumer of this string to validate that fetch on large types work fine. The length of this string as counted in terms of number of characters is 417.</xml>"
}
TEST_2 : query with FETCH_COLUMN :
string(10) "STRINGCOL1"
TEST_3 : query with FETCH_CLASS :
string(1) "1"
string(10) "STRINGCOL1"
string(10) "STRINGCOL1"
string(23) "2000-11-11 11:11:11.110"
string(10) "STRINGCOL1"
string(10) "STRINGCOL1"
string(7) "111.111"
string(431) "<xml> 1 This is a really large string used to test certain large data types like xml data type. The length of this string is greater than 256 to correctly test a large data type. This is currently used by atleast varchar type and by xml type. The fetch tests are the primary consumer of this string to validate that fetch on large types work fine. The length of this string as counted in terms of number of characters is 417.</xml>"
TEST_4 : query with FETCH_INTO :
string(1) "1"
string(10) "STRINGCOL1"
string(10) "STRINGCOL1"
string(23) "2000-11-11 11:11:11.110"
string(10) "STRINGCOL1"
string(10) "STRINGCOL1"
string(7) "111.111"
string(431) "<xml> 1 This is a really large string used to test certain large data types like xml data type. The length of this string is greater than 256 to correctly test a large data type. This is currently used by atleast varchar type and by xml type. The fetch tests are the primary consumer of this string to validate that fetch on large types work fine. The length of this string as counted in terms of number of characters is 417.</xml>"
TEST_5 : query an empty table :
bool(false)


text:
"""Tests for stateless random-number generation ops."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import math

import numpy as np

from tensorflow.compiler.tests import xla_test
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import stateless_random_ops as stateless
from tensorflow.python.ops.distributions import special_math
from tensorflow.python.platform import test

class StatelessRandomOpsTest(xla_test.XLATestCase):
  """Test cases for stateless random-number generator operators."""

  def _random_types(self, include_int=False):
    allowed_types = {dtypes.float32, dtypes.float64, dtypes.bfloat16}
    if include_int:
      allowed_types.update({dtypes.int32, dtypes.int64})
    return self.all_tf_types & allowed_types

  def testDeterminism(self):
    # Stateless values should be equal iff the seeds are equal (roughly)
    with self.cached_session(), self.test_scope():
      seed_t = array_ops.placeholder(dtypes.int32, shape=[2])
      seeds = [(x, y) for x in range(5) for y in range(5)] * 3
      for stateless_op in [
          stateless.stateless_random_uniform, stateless.stateless_random_normal
      ]:
        for shape in (), (3,), (2, 5):
          for dtype in self._random_types():
            # Skip bfloat16. The result of bfloat16 is truncated from 32-bit
            # result. With different seeds, the 32-bit results are different,
            # but the truncated 16-bit results might be the same.
            if dtype == dtypes.bfloat16:
              continue
            pure = stateless_op(shape, seed=seed_t, dtype=dtype)
            values = [(seed, pure.eval(feed_dict={
                seed_t: seed
            })) for seed in seeds]
            for s0, v0 in values:
              for s1, v1 in values:
                self.assertEqual(s0 == s1, np.all(v0 == v1))

  def testRandomUniformIsInRange(self):
    with self.cached_session() as sess, self.test_scope():
      for dtype in self._random_types(include_int=True):
        maxval = 1
        if dtype.is_integer:
          maxval = 100
        seed_t = array_ops.placeholder(dtypes.int32, shape=[2])
        x = stateless.stateless_random_uniform(
            shape=[1000], seed=seed_t, maxval=maxval, dtype=dtype)
        y = sess.run(x, {seed_t: [0x12345678, 0xabcdef12]})
        self.assertTrue(np.all(y >= 0))
        self.assertTrue(np.all(y < maxval))

  def _chi_squared(self, x, bins):
    """Pearson's Chi-squared test."""
    x = np.ravel(x)
    n = len(x)
    histogram, _ = np.histogram(x, bins=bins, range=(0, 1))
    expected = n / float(bins)
    return np.sum(np.square(histogram - expected) / expected)

  def testDistributionOfStatelessRandomUniform(self):
    """Use Pearson's Chi-squared test to test for uniformity."""
    with self.cached_session() as sess, self.test_scope():
      for dtype in self._random_types(include_int=True):
        seed_t = array_ops.placeholder(dtypes.int32, shape=[2])
        n = 1000
        maxval = 1
        if dtype.is_integer:
          maxval = 100
        x = stateless.stateless_random_uniform(
            shape=[n], seed=seed_t, maxval=maxval, dtype=dtype)
        y = sess.run(x, {seed_t: [565656, 121212]})
        if maxval > 1:
          # Normalize y to range [0, 1).
          y = y.astype(float) / maxval
        # Tests that the values are distributed amongst 10 bins with equal
        # probability. 16.92 is the Chi^2 value for 9 degrees of freedom with
        # p=0.05. This test is probabilistic and would be flaky if the random
        # seed were not fixed.
        self.assertTrue(self._chi_squared(y, 10) < 16.92)

  def testRandomNormalIsFinite(self):
    with self.cached_session() as sess, self.test_scope():
      for dtype in self._random_types():
        seed_t = array_ops.placeholder(dtypes.int32, shape=[2])
        x = stateless.stateless_random_normal(
            shape=[10000], seed=seed_t, dtype=dtype)
        y = sess.run(x, {seed_t: [0x12345678, 0xabcdef12]})
        self.assertTrue(np.all(np.isfinite(y)))

  def _normal_cdf(self, x):
    """Cumulative distribution function for a standard normal distribution."""
    return 0.5 + 0.5 * np.vectorize(math.erf)(x / math.sqrt(2))

  def _anderson_darling(self, x):
    """Anderson-Darling test for a standard normal distribution."""
    x = np.sort(np.ravel(x))
    n = len(x)
    i = np.linspace(1, n, n)
    z = np.sum((2 * i - 1) * np.log(self._normal_cdf(x)) +
               (2 * (n - i) + 1) * np.log(1 - self._normal_cdf(x)))
    return -n - z / n

  def testDistributionOfStatelessRandomNormal(self):
    """Use Anderson-Darling test to test distribution appears normal."""
    with self.cached_session() as sess, self.test_scope():
      for dtype in self._random_types():
        seed_t = array_ops.placeholder(dtypes.int32, shape=[2])
        n = 1000
        x = stateless.stateless_random_normal(
            shape=[n], seed=seed_t, dtype=dtype)
        y = sess.run(x, {seed_t: [25252, 314159]})
        # The constant 2.492 is the 5% critical value for the Anderson-Darling
        # test where the mean and variance are known. This test is probabilistic
        # so to avoid flakiness the seed is fixed.
        self.assertTrue(self._anderson_darling(y.astype(float)) < 2.492)

  def testTruncatedNormalIsInRange(self):
    for dtype in self._random_types():
      with self.cached_session() as sess, self.test_scope():
        seed_t = array_ops.placeholder(dtypes.int32, shape=[2])
        n = 10000000
        x = stateless.stateless_truncated_normal(
            shape=[n], seed=seed_t, dtype=dtype)
        y = sess.run(x, {seed_t: [0x12345678, 0xabcdef12]})

        def normal_cdf(x):
          return .5 * math.erfc(-x / math.sqrt(2))

        def normal_pdf(x):
          return math.exp(-(x**2) / 2.) / math.sqrt(2 * math.pi)

        def probit(x, sess=sess):
          return self.evaluate(special_math.ndtri(x))

        a = -2.
        b = 2.
        mu = 0.
        sigma = 1.

        alpha = (a - mu) / sigma
        beta = (b - mu) / sigma
        z = normal_cdf(beta) - normal_cdf(alpha)

        self.assertTrue((y >= a).sum() == n)
        self.assertTrue((y <= b).sum() == n)

        # For more information on these calculations, see:
        # Burkardt, John. "The Truncated Normal Distribution".
        # Department of Scientific Computing website. Florida State University.
        expected_mean = mu + (normal_pdf(alpha) - normal_pdf(beta)) / z * sigma
        y = y.astype(float)
        actual_mean = np.mean(y)
        self.assertAllClose(actual_mean, expected_mean, atol=5e-4)

        expected_median = mu + probit(
            (normal_cdf(alpha) + normal_cdf(beta)) / 2.) * sigma
        actual_median = np.median(y)
        self.assertAllClose(actual_median, expected_median, atol=8e-4)

        expected_variance = sigma**2 * (1 + (
            (alpha * normal_pdf(alpha) - beta * normal_pdf(beta)) / z) - (
                (normal_pdf(alpha) - normal_pdf(beta)) / z)**2)
        actual_variance = np.var(y)
        self.assertAllClose(actual_variance, expected_variance,
                            rtol=5e-3 if dtype == dtypes.bfloat16 else 1e-3)

if __name__ == '__main__':
  test.main()

redpajama_set_name: RedPajamaGithub


text:
export interface IDocumentCardExampleProps {
  description: string;
}


text:
package com.amazonaws.resources.glacier;

import com.amazonaws.resources.ResultCapture;
import com.amazonaws.services.glacier.model.CreateVaultRequest;
import com.amazonaws.services.glacier.model.CreateVaultResult;
import com.amazonaws.services.glacier.model.ListVaultsRequest;

/**
 * The Account resource.
 * Each Account object is uniquely identified by these
 * identifier(s):
 *

 *
Id

 *

 */
public interface Account {
    /**
     * Returns true if this resource's attributes have been loaded. If this
     * method returns {@code false}, calls to attribute getter methods on this
     * instance will make an implicit call to {@code load()} to retrieve the
     * value.
     */
    boolean isLoaded();

    /**
     * Gets the value of the Id identifier. This method always directly returns
     * the identifier and never involves a service call.
     */
    String getId();

    /**
     * Gets a subresource.
     */
    Vault getVault(String name);

    /**
     * Retrieves the Vaults collection referenced by this resource.
     */
    VaultCollection getVaults();

    /**
     * Retrieves the Vaults collection referenced by this resource.
     */
    VaultCollection getVaults(ListVaultsRequest request);

    /**
     * Performs the CreateVault action.
     *
     *

     *
     * @return The Vault resource object associated with the result
     *         of this action.
     * @see CreateVaultRequest
     */
    com.amazonaws.resources.glacier.Vault createVault(CreateVaultRequest request
            );

    /**
     * Performs the CreateVault action and use a ResultCapture to
     * retrieve the low-level client response.
     *
     *

     *
     * @return The Vault resource object associated with the result
     *         of this action.
     * @see CreateVaultRequest
     */
    com.amazonaws.resources.glacier.Vault createVault(CreateVaultRequest request
            , ResultCapture<CreateVaultResult> extractor);

    /**
     * The convenient method form for the CreateVault action.
     *
     * @see #createVault(CreateVaultRequest)
     */
    com.amazonaws.resources.glacier.Vault createVault();

    /**
     * The convenient method form for the CreateVault action.
     *
     * @see #createVault(CreateVaultRequest, ResultCapture)
     */
    com.amazonaws.resources.glacier.Vault createVault(
            ResultCapture<CreateVaultResult> extractor);

    /**
     * The convenient method form for the CreateVault action.
     *
     * @see #createVault(CreateVaultRequest)
     */
    com.amazonaws.resources.glacier.Vault createVault(String vaultName);

    /**
     * The convenient method form for the CreateVault action.
     *
     * @see #createVault(CreateVaultRequest, ResultCapture)
     */
    com.amazonaws.resources.glacier.Vault createVault(String vaultName,
            ResultCapture<CreateVaultResult> extractor);

    /**
     * The convenient method form for the CreateVault action.
     *
     * @see #createVault(CreateVaultRequest)
     */
    com.amazonaws.resources.glacier.Vault createVault(String accountId, String
            vaultName);

    /**
     * The convenient method form for the CreateVault action.
     *
     * @see #createVault(CreateVaultRequest, ResultCapture)
     */
    com.amazonaws.resources.glacier.Vault createVault(String accountId, String
            vaultName, ResultCapture<CreateVaultResult> extractor);
}


text:
package org.b3log.solo.processor;

import freemarker.template.Template;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.action.AbstractCacheablePageAction;
import org.b3log.latke.annotation.RequestProcessing;
import org.b3log.latke.annotation.RequestProcessor;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer;
import org.b3log.latke.util.Locales;
import org.b3log.latke.util.freemarker.Templates;
import org.b3log.solo.model.PageTypes;
import org.b3log.solo.model.Preference;
import org.b3log.solo.processor.renderer.FrontRenderer;
import org.b3log.solo.processor.util.Filler;
import org.b3log.solo.service.PreferenceQueryService;
import org.b3log.solo.util.Skins;
import org.json.JSONObject;

/**
 * User template processor.
 *
 *

 * User can add a template (for example "links.ftl") then visits the page ("links.html").
 *

 *
 *

 * See issue 409 for more details.
 *

 *
 * @author Liang Ding
 * @version 1.0.0.2, May 28, 2012
 * @since 0.4.5
 */
@RequestProcessor
public final class UserTemplateProcessor {

    /**
     * Logger.
     */
    private static final Logger LOGGER = Logger.getLogger(ArticleProcessor.class.getName());
    /**
     * Filler.
     */
    private Filler filler = Filler.getInstance();
    /**
     * Preference query service.
     */
    private PreferenceQueryService preferenceQueryService = PreferenceQueryService.getInstance();
    /**
     * Language service.
     */
    private LangPropsService langPropsService = LangPropsService.getInstance();

    /**
     * Shows the user template page.
     *
     * @param context the specified context
     * @param request the specified HTTP servlet request
     * @param response the specified HTTP servlet response
     * @throws IOException io exception
     */
    @RequestProcessing(value = "/*.html", method = HTTPRequestMethod.GET)
    public void showPage(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
            throws IOException {
        final String requestURI = request.getRequestURI();
        String templateName = StringUtils.substringAfterLast(requestURI, "/");
        templateName = StringUtils.substringBefore(templateName, ".") + ".ftl";
        LOGGER.log(Level.FINE, "Shows page[requestURI={0}, templateName={1}]", new Object[]{requestURI, templateName});

        final AbstractFreeMarkerRenderer renderer = new FrontRenderer();
        context.setRenderer(renderer);
        renderer.setTemplateName(templateName);

        final Map<String, Object> dataModel = renderer.getDataModel();

        final Template template = Templates.getTemplate((String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), templateName);
        if (null == template) {
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);

                return;
            } catch (final IOException ex) {
                LOGGER.severe(ex.getMessage());
            }
        }

        try {
            final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request));
            dataModel.putAll(langs);
            final JSONObject preference = preferenceQueryService.getPreference();

            filler.fillBlogHeader(request, dataModel, preference);
            filler.fillUserTemplate(template, dataModel, preference);
            filler.fillBlogFooter(dataModel, preference);
            Skins.fillSkinLangs(preference.optString(Preference.LOCALE_STRING),
                                (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel);

            request.setAttribute(AbstractCacheablePageAction.CACHED_OID, "No id");
            request.setAttribute(AbstractCacheablePageAction.CACHED_TITLE, requestURI);
            request.setAttribute(AbstractCacheablePageAction.CACHED_TYPE, langs.get(PageTypes.USER_TEMPLATE_PAGE));
            request.setAttribute(AbstractCacheablePageAction.CACHED_LINK, requestURI);
        } catch (final Exception e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);

            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            } catch (final IOException ex) {
                LOGGER.severe(ex.getMessage());
            }
        }
    }
}


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

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

import com.taobao.gecko.service.Connection;
import com.taobao.gecko.service.RemotingClient;
import com.taobao.gecko.service.RemotingFactory;
import com.taobao.gecko.service.RequestProcessor;
import com.taobao.gecko.service.config.ClientConfig;
import com.taobao.gecko.service.exception.NotifyRemotingException;
import com.taobao.gecko.service.notify.request.NotifyDummyRequestCommand;
import com.taobao.gecko.service.notify.response.NotifyDummyAckCommand;

public class MultiGroupBenchmarkClient {

    static String body = null;
    static final int BODY_LEN = 128;
    static {
        final StringBuffer sb = new StringBuffer(BODY_LEN);
        for (int i = 0; i < BODY_LEN; i++) {
            sb.append("a");
        }
        body = sb.toString();
    }

    private static final class BenchmarkRequestProcessor implements RequestProcessor<NotifyDummyRequestCommand> {
        private final AtomicInteger counter = new AtomicInteger(0);

        private final ExecutorService executor = Executors.newCachedThreadPool();

        public ThreadPoolExecutor getExecutor() {

            return (ThreadPoolExecutor) this.executor;
        }

        public int getCounter() {
            return this.counter.get();
        }

        public void handleRequest(final NotifyDummyRequestCommand request, final Connection conn) {
            try {
                this.counter.incrementAndGet();
                conn.response(new NotifyDummyAckCommand(request, body));
            }
            catch (final NotifyRemotingException e) {

            }
        }
    }

    public static void main(final String[] args) throws Exception {

        final BenchmarkRequestProcessor processor = new BenchmarkRequestProcessor();
        final ClientConfig clientConfig = new ClientConfig();
        clientConfig.setCallBackExecutorPoolSize(20);
        // clientConfig.setMaxScheduleWrittenBytes(Runtime.getRuntime().maxMemory()
        // / 8 / 10);
        final RemotingClient client = RemotingFactory.connect(clientConfig);
        client.registerProcessor(NotifyDummyRequestCommand.class, processor);
        client.start();
        client.connect("tcp://localhost:8099", 1);

        client.awaitReadyInterrupt("tcp://localhost:8099");

        // server.stop();
        // client.stop();

    }
}


text:
@interface TapToZoom ()

@end

@implementation TapToZoom

- (void)viewDidLoad {
    [super viewDidLoad];

}

@end


text:
/*
 * Project Horizon
 * (c) 2014 VMware, Inc. All rights reserved.
 * VMware Confidential.
 */
package com.vmware.jira.domain;

public class MenuSection {

    public String id;

    public String title;

    public MenuItem[] items;

}


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      Curriculum Vitae · Sanchit Alekh

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/hyde.css">

  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png">
                                 <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

          Sanchit Alekh

Data Engineer at Rubinstein and Schmiedel AG, Munich

      Home

            About Me

            Academics and Research

            Curriculum Vitae

            Personal Life

      LinkedIn
      GitHub

© 2022. All rights reserved.

Curriculum Vitae

Note

The most up-to-date source of my professional and academic history would be my LinkedIn page, which can be accessed here.

Curriculum Vitae in PDF form

Comprehensive Industry CV

Academic Version - EN

Academic Version - DE

Education

MSc. in Software Systems Engineering -  RWTH Aachen University, Aachen, Germany GPA: 1.3 (German Scale)

B.Tech (Honours) in Information Technology -  Indian Institute of Information Technology, Allahabad. GPA: 9.08/10.0

Higher Secondary Schooling -   Delhi Public School, Patna, India. Grades: 93.6%

Work Experience

 Consultant Big Data Engineer  at Data Reply GmbH, Munich, Germany

 Data Scientist Intern  at AUDI AG Production IT, Neckarsulm, Germany (2018-2019)

Research Experience

 Bachelor Thesis Work -  Conducted at the Chair of Databases and Information Systems, RWTH Aachen. Slides and Report available.

Summer Internship -  Conducted at the Knowledge Mining and Assessment Group, TU Darmstadt, Germany.

Internship -  At the Center for Development of Advanced Computing, Pune, India.

Summer Internship -  At the University of Wisconsin, Milwaukee, USA.

Publications

To access these papers in their original form, please visit my Google Scholar Page.

An Integrated Ontology-Based Approach for Patent Classification in Medical Engineering

Ontology Matching for Patent Classification

Automatic Raga Recognition in Hindustani Classical Music

Combining Keystroke Dynamics and Face Recognition for User Verification

Ontology-based Classification and Analysis of non- emergency Smart-city Events

Standardized Test Scores

Graduate Record Exam : 329/340 -  Quantitative: 170/170, Verbal: 159/170, Analytical Writing: 5/6

 TOEFL : 118/120

 DSM Sprachenzentrum RWTH Aachen  (German Level B1) : 2,0 (German Grading Scale)


text:
package org.sundqvist.repository.cassandra.evolutions.domain;

import org.junit.Test;

import java.util.Arrays;

import static org.junit.Assert.assertEquals;

/**
 * Test class for {@link ChangeSets}
 *
 * @author Joakim Sundqvist
 * @since 22/06/15
 */
public class ChangeSetsTest {

    @Test
    public void testGetChangeSets() throws Exception {

        final ChangeSets demo = new ChangeSets(Arrays.asList(new Meta("", "", 2), new Meta("", "", 5), new Meta("", "", 0), new Meta("", "", 1)), "demo");

        assertEquals(demo.getChangeSets().get(0).getId(), 0);
        assertEquals(demo.getChangeSets().get(3).getId(), 5);

    }
}


text:
from django.core.exceptions import ImproperlyConfigured, PermissionDenied

class AutoPermissionViewSetMixin:
    """
    Enforces object-level permissions in ``rest_framework.viewsets.ViewSet``,
    deriving the permission type from the particular action to be performed..

    As with ``rules.contrib.views.AutoPermissionRequiredMixin``, this only works when
    model permissions are registered using ``rules.contrib.models.RulesModelMixin``.
    """

    # Maps API actions to model permission types. None as value skips permission
    # checks for the particular action.
    # This map needs to be extended when custom actions are implemented
    # using the @action decorator.
    # Extend or replace it in subclasses like so:
    # permission_type_map = {
    #     **AutoPermissionViewSetMixin.permission_type_map,
    #     "close": "change",
    #     "reopen": "change",
    # }
    permission_type_map = {
        "create": "add",
        "destroy": "delete",
        "list": None,
        "partial_update": "change",
        "retrieve": "view",
        "update": "change",
    }

    def initial(self, *args, **kwargs):
        """Ensures user has permission to perform the requested action."""
        super().initial(*args, **kwargs)

        if not self.request.user:
            # No user, don't check permission
            return

        # Get the handler for the HTTP method in use
        try:
            if self.request.method.lower() not in self.http_method_names:
                raise AttributeError
            handler = getattr(self, self.request.method.lower())
        except AttributeError:
            # method not supported, will be denied anyway
            return

        try:
            perm_type = self.permission_type_map[self.action]
        except KeyError:
            raise ImproperlyConfigured(
                "AutoPermissionViewSetMixin tried to authorize a request with the "
                "{!r} action, but permission_type_map only contains: {!r}".format(
                    self.action, self.permission_type_map
                )
            )
        if perm_type is None:
            # Skip permission checking for this action
            return

        # Determine whether we've to check object permissions (for detail actions)
        obj = None
        extra_actions = self.get_extra_actions()
        # We have to access the unbound function via __func__
        if handler.__func__ in extra_actions:
            if handler.detail:
                obj = self.get_object()
        elif self.action not in ("create", "list"):
            obj = self.get_object()

        # Finally, check permission
        perm = self.get_queryset().model.get_perm(perm_type)
        if not self.request.user.has_perm(perm, obj):
            raise PermissionDenied


text:
import {
  DatepickerFormatOptions, DatepickerRenderOptions, DaysCalendarModel, MonthViewModel,
  MonthViewOptions
} from '../models/index';
import { defaultFormatOptions, defaultMonthOptions, defaultRenderOptions } from './_defaults';

export class BsDatepickerState {
  // initial date of calendar, today by default
  viewDate: Date;
  hoveredDate?: Date;
  selectedDate?: Date;

  monthsModel?: DaysCalendarModel[];
  formattedMonths?: MonthViewModel[];
  flaggedMonths?: MonthViewModel[];

  monthViewOptions: MonthViewOptions;

  formatOptions: DatepickerFormatOptions;
  renderOptions: DatepickerRenderOptions;

  // daterange picker
  selectedRange?: Date[];
}

export const initialDatepickerState: BsDatepickerState = {
  viewDate: new Date(),
  selectedRange: [],
  monthViewOptions: defaultMonthOptions,
  formatOptions: defaultFormatOptions,
  renderOptions: defaultRenderOptions
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Mobile Clinic: FIUPatientRegistrationViewController Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Mobile Clinic
    1.0

Senior Project

Main Page

Related Pages

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Structures

Data Structure Index

Class Hierarchy

Data Fields

 All Data Structures Functions Properties Pages

Public Member Functions |
Protected Attributes |
Properties

FIUPatientRegistrationViewController Class Reference

Inheritance diagram for FIUPatientRegistrationViewController:

  <map id="FIUPatientRegistrationViewController_map" name="FIUPatientRegistrationViewController_map">
<area href="protocol_screen_navigation_delegate-p.html" alt="<ScreenNavigationDelegate>" shape="rect" coords="0,0,219,24"/>
</map>

Public Member Functions

(IBAction) 	- patientPictureButton:

(IBAction) 	- registerPatientButton:

(BOOL) 	- validateRegistration

(IBAction) 	- cancelRegistration:

(void) 	- setScreenHandler:

Protected Attributes

UIImagePickerController * 	pCtrl

ScreenHandler 	handler

CameraFacade * 	facade

BOOL 	shouldDismiss

Properties

IBOutlet UITextField * 	familyNameField

IBOutlet UITextField * 	patientNameField

IBOutlet UITextField * 	villageNameField

IBOutlet UITextField * 	patientWeightField

IBOutlet UIButton * 	patientAgeField

IBOutlet UIImageView * 	patientPictureImage

IBOutlet UIButton * 	SaveButton

IBOutlet UISegmentedControl * 	patientSexSegment

PatientObject * 	patient

The documentation for this class was generated from the following files:

Mobile Clinic/FIUPatientRegistrationViewController.h

Mobile Clinic/FIUPatientRegistrationViewController.m

FIUPatientRegistrationViewController

Generated on Mon Feb 25 2013 00:19:23 for Mobile Clinic by

     1.8.1.1


text:
Here you may find thousands pre-made source code pieces for easy implementation in your own programming C# projects. ByteScout PDF Viewer SDK was made to help with PDF viewer control hosted in WPF in C#. ByteScout PDF Viewer SDK is the component that helps in adding pdf viewer into your desktop WinForms application. User may select multiple areas with mouse, can use keyboard shortcuts and zoom in or zoom out and change scaling. You may read coordinates, handle custom painting code and retrieve text inside selection area.

This rich sample source code in C# for ByteScout PDF Viewer SDK includes the number of functions and options you should do calling the API to implement PDF viewer control hosted in WPF. This C# sample code should be copied and pasted into your application's code editor. Then just compile and run it to see how it works. This basic programming language sample code for C# will do the whole work for you in implementing PDF viewer control hosted in WPF in your app.

Trial version can be downloaded from our website. Source code samples for C# and documentation are included.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20PDF%20Viewer%20SDK%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20PDF%20Viewer%20SDK%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****App.xaml.cs:**

```
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace PdfViewerInWpf
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	public partial class App : Application
	{
	}
}

```

<!-- code block end -->

<!-- code block begin -->

##### ****MainWindow.xaml.cs:**

```
using System;
using System.Drawing;
using System.Windows;

namespace PdfViewerInWpf
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();
		}

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			// Load a sample document on startup
			pdfViewerControl1.InputFile = "sample.pdf";
		}

		private void menuItemOpen_Click(object sender, RoutedEventArgs e)
		{
			Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog
			{
				Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*"
			};

			bool? result = dlg.ShowDialog();

			if (result == true)
				pdfViewerControl1.InputFile = dlg.FileName;
		}
	}
}

```

<!-- code block end -->

<!-- code block begin -->

##### ****PdfViewerInWpf.VS2010.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{C521F82E-7924-49DB-90FB-5AC6719757E2}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>PdfViewerInWpf</RootNamespace>
    <AssemblyName>PdfViewerInWpf</AssemblyName>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDFViewer, Version=8.0.0.2544, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\Program Files\Bytescout PDF Viewer SDK\net4.00\Bytescout.PDFViewer.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Windows.Forms" />
    <Reference Include="System.Xml" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Xaml">
      <RequiredTargetFramework>4.0</RequiredTargetFramework>
    </Reference>
    <Reference Include="UIAutomationProvider" />
    <Reference Include="WindowsBase" />
    <Reference Include="PresentationCore" />
    <Reference Include="PresentationFramework" />
    <Reference Include="WindowsFormsIntegration" />
  </ItemGroup>
  <ItemGroup>
    <ApplicationDefinition Include="App.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </ApplicationDefinition>
    <Page Include="MainWindow.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </Page>
    <Compile Include="App.xaml.cs">
      <DependentUpon>App.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="MainWindow.xaml.cs">
      <DependentUpon>MainWindow.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Properties\AssemblyInfo.cs">
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
      <DesignTime>True</DesignTime>
      <DependentUpon>Resources.resx</DependentUpon>
    </Compile>
    <Compile Include="Properties\Settings.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Settings.settings</DependentUpon>
      <DesignTimeSharedInput>True</DesignTimeSharedInput>
    </Compile>
    <EmbeddedResource Include="Properties\Resources.resx">
      <Generator>ResXFileCodeGenerator</Generator>
      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
    </EmbeddedResource>
    <None Include="Properties\Settings.settings">
      <Generator>SettingsSingleFileGenerator</Generator>
      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
    </None>
    <AppDesigner Include="Properties\" />
    <Content Include="sample.pdf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****PdfViewerInWpf.VS2012.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{C521F82E-7924-49DB-90FB-5AC6719757E2}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>PdfViewerInWpf</RootNamespace>
    <AssemblyName>PdfViewerInWpf</AssemblyName>
    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDFViewer, Version=8.0.0.2544, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\Program Files\Bytescout PDF Viewer SDK\net4.00\Bytescout.PDFViewer.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Windows.Forms" />
    <Reference Include="System.Xml" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Xaml">
      <RequiredTargetFramework>4.0</RequiredTargetFramework>
    </Reference>
    <Reference Include="UIAutomationProvider" />
    <Reference Include="WindowsBase" />
    <Reference Include="PresentationCore" />
    <Reference Include="PresentationFramework" />
    <Reference Include="WindowsFormsIntegration" />
  </ItemGroup>
  <ItemGroup>
    <ApplicationDefinition Include="App.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </ApplicationDefinition>
    <Page Include="MainWindow.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </Page>
    <Compile Include="App.xaml.cs">
      <DependentUpon>App.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="MainWindow.xaml.cs">
      <DependentUpon>MainWindow.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Properties\AssemblyInfo.cs">
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
      <DesignTime>True</DesignTime>
      <DependentUpon>Resources.resx</DependentUpon>
    </Compile>
    <Compile Include="Properties\Settings.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Settings.settings</DependentUpon>
      <DesignTimeSharedInput>True</DesignTimeSharedInput>
    </Compile>
    <EmbeddedResource Include="Properties\Resources.resx">
      <Generator>ResXFileCodeGenerator</Generator>
      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
    </EmbeddedResource>
    <None Include="Properties\Settings.settings">
      <Generator>SettingsSingleFileGenerator</Generator>
      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
    </None>
    <AppDesigner Include="Properties\" />
    <Content Include="sample.pdf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****PdfViewerInWpf.VS2013.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{C521F82E-7924-49DB-90FB-5AC6719757E2}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>PdfViewerInWpf</RootNamespace>
    <AssemblyName>PdfViewerInWpf</AssemblyName>
    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDFViewer, Version=8.0.0.2544, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\Program Files\Bytescout PDF Viewer SDK\net4.00\Bytescout.PDFViewer.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Windows.Forms" />
    <Reference Include="System.Xml" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Xaml">
      <RequiredTargetFramework>4.0</RequiredTargetFramework>
    </Reference>
    <Reference Include="UIAutomationProvider" />
    <Reference Include="WindowsBase" />
    <Reference Include="PresentationCore" />
    <Reference Include="PresentationFramework" />
    <Reference Include="WindowsFormsIntegration" />
  </ItemGroup>
  <ItemGroup>
    <ApplicationDefinition Include="App.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </ApplicationDefinition>
    <Page Include="MainWindow.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </Page>
    <Compile Include="App.xaml.cs">
      <DependentUpon>App.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="MainWindow.xaml.cs">
      <DependentUpon>MainWindow.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Properties\AssemblyInfo.cs">
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
      <DesignTime>True</DesignTime>
      <DependentUpon>Resources.resx</DependentUpon>
    </Compile>
    <Compile Include="Properties\Settings.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Settings.settings</DependentUpon>
      <DesignTimeSharedInput>True</DesignTimeSharedInput>
    </Compile>
    <EmbeddedResource Include="Properties\Resources.resx">
      <Generator>ResXFileCodeGenerator</Generator>
      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
    </EmbeddedResource>
    <None Include="Properties\Settings.settings">
      <Generator>SettingsSingleFileGenerator</Generator>
      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
    </None>
    <AppDesigner Include="Properties\" />
    <Content Include="sample.pdf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****PdfViewerInWpf.VS2015.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{C521F82E-7924-49DB-90FB-5AC6719757E2}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>PdfViewerInWpf</RootNamespace>
    <AssemblyName>PdfViewerInWpf</AssemblyName>
    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDFViewer, Version=8.0.0.2544, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\Program Files\Bytescout PDF Viewer SDK\net4.00\Bytescout.PDFViewer.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Windows.Forms" />
    <Reference Include="System.Xml" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Xaml">
      <RequiredTargetFramework>4.0</RequiredTargetFramework>
    </Reference>
    <Reference Include="UIAutomationProvider" />
    <Reference Include="WindowsBase" />
    <Reference Include="PresentationCore" />
    <Reference Include="PresentationFramework" />
    <Reference Include="WindowsFormsIntegration" />
  </ItemGroup>
  <ItemGroup>
    <ApplicationDefinition Include="App.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </ApplicationDefinition>
    <Page Include="MainWindow.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </Page>
    <Compile Include="App.xaml.cs">
      <DependentUpon>App.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="MainWindow.xaml.cs">
      <DependentUpon>MainWindow.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Properties\AssemblyInfo.cs">
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
      <DesignTime>True</DesignTime>
      <DependentUpon>Resources.resx</DependentUpon>
    </Compile>
    <Compile Include="Properties\Settings.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Settings.settings</DependentUpon>
      <DesignTimeSharedInput>True</DesignTimeSharedInput>
    </Compile>
    <EmbeddedResource Include="Properties\Resources.resx">
      <Generator>ResXFileCodeGenerator</Generator>
      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
    </EmbeddedResource>
    <None Include="Properties\Settings.settings">
      <Generator>SettingsSingleFileGenerator</Generator>
      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
    </None>
    <AppDesigner Include="Properties\" />
    <Content Include="sample.pdf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->


text:
cd $(dirname $0)

. check_reqs.include

check_reqs

echo "Configuring ldap support"
echo "Left blank and press enter to set up defaults"

echo "Do you want to enable ldap support?(no)"
read answer
if [ "$answer" != "yes" ];then
  echo "ldap support disabled"
  exit 0
fi

default="localhost"
echo "hostname($default)"
read ldap_hostname
if [ "$ldap_hostname" == "" ];then
  ldap_hostname=$default
fi

default=389
echo "port($default)"
read ldap_port
if [ "$ldap_port" == "" ];then
  ldap_port=$default
fi

default="ou=users, dc=example, dc=com"
echo "base($default)"
read ldap_base
if [ "$ldap_base" == "" ];then
  ldap_base=$default
fi

# enable option
sed -e "s/# SetEnv PORTUS_LDAP_ENABLED/SetEnv PORTUS_LDAP_ENABLED/g" -i $APACHE_CONF_PATH/portus.conf
# set option
sed -e "s/SetEnv PORTUS_LDAP_ENABLED.*/SetEnv PORTUS_LDAP_ENABLED true/g" -i $APACHE_CONF_PATH/portus.conf

# enable option
sed -e "s/# SetEnv PORTUS_LDAP_HOSTNAME/SetEnv PORTUS_LDAP_HOSTNAME/g" -i $APACHE_CONF_PATH/portus.conf
# set option
sed -e "s/SetEnv PORTUS_LDAP_HOSTNAME.*/SetEnv PORTUS_LDAP_HOSTNAME $ldap_hostname/g" -i $APACHE_CONF_PATH/portus.conf

# enable option
sed -e "s/# SetEnv PORTUS_LDAP_PORT/SetEnv PORTUS_LDAP_PORT/g" -i $APACHE_CONF_PATH/portus.conf
# set option
sed -e "s/SetEnv PORTUS_LDAP_PORT.*/SetEnv PORTUS_LDAP_PORT $ldap_port/g" -i $APACHE_CONF_PATH/portus.conf

# enable option
sed -e "s/# SetEnv PORTUS_LDAP_BASE/SetEnv PORTUS_LDAP_BASE/g" -i $APACHE_CONF_PATH/portus.conf
# set option
sed -e "s/SetEnv PORTUS_LDAP_BASE.*/SetEnv PORTUS_LDAP_BASE \"$ldap_base\"/g" -i $APACHE_CONF_PATH/portus.conf


text:
var request = require('request');
var config = require('./config');
var googleApiKey = config.CONFIG.currentEnv.googleApiKey;
var darkSkyKey = config.CONFIG.currentEnv.darkSkyKey;//https://api.darksky.net/forecast/[key]/[latitude],[longitude]
var lat = 32.8025956;
var lng = -97.0891169;

/**
 * getCurrentLocation : with geocoding
 * ex) https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY
 * @param:
 */
exports.getCurrentLocation = function(req, res) {

  //if lat and lng are exist, change it
  if(req.query && req.query.lat && req.query.lng ){
    lat = req.query.lat;
    lng = req.query.lng;
  }

    request.get({
        url: "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&key=" + googleApiKey,
        headers: {
            'ContentType': 'application/json',
        },
    }, function(err, response, body) {
        if (!err && response.statusCode == 200) {
            var json = JSON.parse(response.body);
            res.send(json);
        } else {
            res.send(err);
        }
    });

};

/**
 * startListen : start google speach
 * @param:
 */
exports.getWeather = function(req, res) {
    request.get({
        url: "https://api.darksky.net/forecast/" + darkSkyKey + "/" + lat + "," + lng,
        headers: {
            'Content-Type': 'application/json',
        },
    }, function(err, response, body) {
        if (!err && response.statusCode == 200) {
            var json = JSON.parse(response.body);
            res.send(json);
        } else {
            res.send(err);
        }
    });

};


text:
<?php
// autogenerated file 30.09.2013 15:20
// $Id: $
// $Log: $
//
//
require_once 'EbatNs_ComplexType.php';

/**
 * Defines the options available for an automated listing rule thatkeeps a minimum
 * number of items on the site.
 *
 * @link http://developer.ebay.com/DevZone/XML/docs/Reference/eBay/types/SellingManagerAutoListMinActiveItemsType.html
 *
 */
class SellingManagerAutoListMinActiveItemsType extends EbatNs_ComplexType
{
	/**
	 * @var int
	 */
	protected $MinActiveItemCount;
	/**
	 * @var time
	 */
	protected $ListTimeFrom;
	/**
	 * @var time
	 */
	protected $ListTimeTo;
	/**
	 * @var int
	 */
	protected $SpacingIntervalInMinutes;
	/**
	 * @var int
	 */
	protected $ListingHoldInventoryLevel;

	/**
	 * @return int
	 */
	function getMinActiveItemCount()
	{
		return $this->MinActiveItemCount;
	}
	/**
	 * @return void
	 * @param int $value
	 */
	function setMinActiveItemCount($value)
	{
		$this->MinActiveItemCount = $value;
	}
	/**
	 * @return time
	 */
	function getListTimeFrom()
	{
		return $this->ListTimeFrom;
	}
	/**
	 * @return void
	 * @param time $value
	 */
	function setListTimeFrom($value)
	{
		$this->ListTimeFrom = $value;
	}
	/**
	 * @return time
	 */
	function getListTimeTo()
	{
		return $this->ListTimeTo;
	}
	/**
	 * @return void
	 * @param time $value
	 */
	function setListTimeTo($value)
	{
		$this->ListTimeTo = $value;
	}
	/**
	 * @return int
	 */
	function getSpacingIntervalInMinutes()
	{
		return $this->SpacingIntervalInMinutes;
	}
	/**
	 * @return void
	 * @param int $value
	 */
	function setSpacingIntervalInMinutes($value)
	{
		$this->SpacingIntervalInMinutes = $value;
	}
	/**
	 * @return int
	 */
	function getListingHoldInventoryLevel()
	{
		return $this->ListingHoldInventoryLevel;
	}
	/**
	 * @return void
	 * @param int $value
	 */
	function setListingHoldInventoryLevel($value)
	{
		$this->ListingHoldInventoryLevel = $value;
	}
	/**
	 * @return
	 */
	function __construct()
	{
		parent::__construct('SellingManagerAutoListMinActiveItemsType', 'urn:ebay:apis:eBLBaseComponents');
		if (!isset(self::$_elements[__CLASS__]))
				self::$_elements[__CLASS__] = array_merge(self::$_elements[get_parent_class()],
				array(
					'MinActiveItemCount' =>
					array(
						'required' => false,
						'type' => 'int',
						'nsURI' => 'http://www.w3.org/2001/XMLSchema',
						'array' => false,
						'cardinality' => '0..1'
					),
					'ListTimeFrom' =>
					array(
						'required' => false,
						'type' => 'time',
						'nsURI' => 'http://www.w3.org/2001/XMLSchema',
						'array' => false,
						'cardinality' => '0..1'
					),
					'ListTimeTo' =>
					array(
						'required' => false,
						'type' => 'time',
						'nsURI' => 'http://www.w3.org/2001/XMLSchema',
						'array' => false,
						'cardinality' => '0..1'
					),
					'SpacingIntervalInMinutes' =>
					array(
						'required' => false,
						'type' => 'int',
						'nsURI' => 'http://www.w3.org/2001/XMLSchema',
						'array' => false,
						'cardinality' => '0..1'
					),
					'ListingHoldInventoryLevel' =>
					array(
						'required' => false,
						'type' => 'int',
						'nsURI' => 'http://www.w3.org/2001/XMLSchema',
						'array' => false,
						'cardinality' => '0..1'
					)
				));
	}
}
?>


text:
module GoogleMusicApi
  module Artist

    # Gets an artists details
    # @param [String] artist_id
    # @param [boolean] include_albums
    # @param [integer] max_top_tracks
    # @param [integer] max_related_artists
    def get_artist_info(artist_id, include_albums = true, max_top_tracks = 5, max_related_artists = 5)
      url = 'fetchartist'

      options = {
          query: {
              nid: artist_id,
              'include-albums': include_albums,
              'num-top-tracks': max_top_tracks,
              'num-related-artists': max_related_artists
          }
      }

      make_get_request(url, options)
    end

    #Searches albums
    # @param [string] query
    # @param [integer] max_results
    # @return [Hash] describing artists
    def search_artists(query, max_results=50)
      search(query, '2', max_results)
    end

  end
end


text:
package com.amazonaws.services.clouddirectory.model;

import javax.annotation.Generated;

/**
 * <p>
 * Indicates that the provided ARN value is not valid.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidArnException extends com.amazonaws.services.clouddirectory.model.AmazonCloudDirectoryException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new InvalidArnException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public InvalidArnException(String message) {
        super(message);
    }

}


text:
{% extends "layout.html" %}
{% block head %}
	{{ super() }}

{% endblock %}
{% block title %}Apps/Edit{% endblock %}
{% block header %}ZK - Apps/Edit{% endblock %}
{% block content %}

	<form method="POST" action="{{ url_for('app_edit', id=id) }}">
		<input type="hidden" id="le-csrf" name="le-csrf" value="{{ csrf }}" />

			<input type="hidden" id="le-type" name="le-type" value="name" />

				App Name

				<input type="text" id="le-name" name="le-name" maxlength="64" value="{{ app.name }}"/>

			<input type="submit" id="le-submit" name="le-submit" value="Update" />

	</form>
	<form method="POST" action="{{ url_for('app_edit', id=id) }}">
		<input type="hidden" id="le-csrf" name="le-csrf" value="{{ csrf }}" />

			<input type="hidden" id="le-type" name="le-type" value="language" />

				Language

				<select id="le-language" name="le-language" style="width: 35%;">
					{% if def_language %}
						{% for language in languages %}
						<option value="{{ language }}"{% if language == app.language %} selected{% endif %}>{{ language }}</option>
						{% endfor %}
						<option id="option-other" value="Other">Other</option>
						<input type="text" id="le-other-language" name="le-other-language" maxlength="32" style="width: 85px; display: none;" value="" />
					{% else %}
						{% for language in languages %}
						<option value="{{ language }}">{{ language }}</option>
						{% endfor %}
						<option id="option-other" value="Other" selected>Other</option>
						<input type="text" id="le-other-language" name="le-other-language"
							style="width: 85px;" maxlength="32" value="{{ app.language }}"/>
					{% endif %}
				</select>

			<input type="submit" id="le-submit" name="le-submit" value="Update" />

	</form>
	<form method="POST" action="{{ url_for('app_edit', id=id) }}">
		<input type="hidden" id="le-csrf" name="le-csrf" value="{{ csrf }}" />

			<input type="hidden" id="le-type" name="le-type" value="active" />

				Active

				<select id="le-active" name="le-active">
					<option value="yes" {% if app.active == 1 %}selected{% endif %}>Yes</option>
					<option value="no" {%if app.active == 0 %}selected{% endif %}>No</option>
				</select>

			<input type="submit" id="le-submit" name="le-submit" value="Update" />

	</form>
	<form method="POST" action="{{ url_for('app_edit', id=id) }}">
		<input type="hidden" id="le-csrf" name="le-csrf" value="{{ csrf }}" />

			<input type="hidden" id="le-type" name="le-type" value="version" />

				Version

				<input type="text" id="le-version" name="le-version" value="{{ app.version }}" disabled/>

			<input type="submit" id="le-submit" name="le-submit" value="Push" />

	</form>

{% endblock %}


text:
"""
rdfsSubject.py

rdfsSubject is similar to rdfsSubject but includes more
processing and *magic* based on an `RDF Schema`__

__ ::http://www.w3.org/TR/rdf-schema/

Created by Philip Cooper on 2008-05-14.
Copyright (c) 2008 Openvest. All rights reserved.
"""

from rdfalchemy import (
    rdfSubject,
    RDF,
    RDFS,
    Namespace,
    BNode,
    URIRef
)
try:
    from rdflib.py3compat import PY3
except:
    from six import PY3
from rdflib.term import Identifier
from descriptors import (
    rdfSingle,
    rdfMultiple,
    owlTransitive
)
from orm import mapper, allsub

import logging
log = logging.getLogger(__name__)
#log.debug("logger is %s",log.name)
log.setLevel(logging.INFO)

from weakref import WeakValueDictionary
import re

OWL = Namespace("http://www.w3.org/2002/07/owl#")

_all_ = ['rdfsSubject', 'rdfsClass', 'rdfsProperty',
         'owlObjectProperty', 'owlDatatypeProperty',
         'owlSymetricProperty', 'owlTransitiveProperty',
         'owlFunctionalProperty', 'owlInverseFunctionalProperty']

re_ns_n = re.compile(r'(.*[/#])(.*)')

class rdfsSubject(rdfSubject, Identifier):
    _weakrefs = WeakValueDictionary()

    def __new__(cls, resUri=None, schemaGraph=None, *args, **kwargs):
        #  create a bnode
        if not resUri or isinstance(resUri, BNode) or issubclass(cls, BNode):
            obj = BNode.__new__(cls, resUri)
            obj._nodetype = BNode
        # user the identifier passed in
        elif isinstance(resUri, URIRef) or issubclass(cls, URIRef):
            obj = URIRef.__new__(cls, resUri)
            obj._nodetype = URIRef
        # use the resUri of the subject passed in
        elif isinstance(resUri, rdfSubject):
            obj = type(resUri.resUri).__new__(cls, resUri.resUri)
            obj._nodetype = type(resUri.resUri)
        # create one from a <uri> or _:bnode string
        elif isinstance(resUri, (str, unicode)):
            if resUri[0] == "<" and resUri[-1] == ">":
                obj = URIRef.__new__(cls, resUri[1:-1])
                obj._nodetype = URIRef
            elif resUri.startswith("_:"):
                obj = BNode.__new__(cls, resUri[2:])
                obj._nodetype = BNode
        else:
            raise AttributeError(
                "cannot construct rdfSubject from %s" % (str(resUri)))

        # At this point we have an obj to return...but we might want to look
        # deeper if there is an RDF:type entry on the Graph, find the mapped
        # subclass and return an object of that new type
        if resUri:
            rdf_type = obj[RDF.type]
            if rdf_type:
                class_dict = dict(
                    [(str(cl.rdf_type), cl)
                        for cl in allsub(cls) if cl.rdf_type])
                subclass = class_dict.get(str(rdf_type.resUri), cls)
            else:
                subclass = cls
        else:
            subclass = cls

        # improve this do do some kind of hash with classname??
        # this uses _weakrefs to allow us to return an existing object
        # rather than copies
        md5id = obj.n3()
        newobj = rdfsSubject._weakrefs.get(md5id, None)
        log.debug("looking for weakref %s found %s" % (md5id, newobj))
        if newobj:
            return newobj
        newobj = super(rdfSubject, obj).__new__(subclass, obj.resUri)
        log.debug("add a weakref %s", newobj)
        newobj._nodetype = obj._nodetype
        rdfsSubject._weakrefs[newobj.n3()] = newobj
        return newobj

    def __init__(self, resUri=None, **kwargs):
        if not self[RDF.type] and self.rdf_type:
            self.db.add((self.resUri, RDF.type, self.rdf_type))
        if kwargs:
            self._set_with_dict(kwargs)

    @property
    def resUri(self):
        if PY3:
            return self._nodetype(self)
        else:
            return self._nodetype(str(self))

    def _splitname(self):
        return re.match(r'(.*[/#])(.*)', self.resUri).groups()

    @classmethod
    def ClassInstances(cls):
        """return a generator for instances of this rdf:type
        you can look in MyClass.rdf_type to see the predicate being used"""
        # Start with all things of "my" type in the db
        beenthere = set([])
        for i in cls.db.subjects(RDF.type, cls.rdf_type):
            if not i in beenthere:
                yield cls(i)
                beenthere.add(i)

        # for all subclasses of me in python do the same (recursivly)
        pySubClasses = allsub(cls)
        for sub in pySubClasses:
            for i in sub.ClassInstances():
                if not i in beenthere:
                    yield i
                    beenthere.add(i)

        # not done yet, for all db subclasses that I have not processed
        # already...get them too
        dbSubClasses = rdfsClass(cls.rdf_type).transitive_subClasses
        moreSubClasses = [
            dbsub.resUri for dbsub in dbSubClasses
            if dbsub.resUri not in [
                pysub.rdf_type for pysub in pySubClasses]]
        for sub in moreSubClasses:
            for i in cls.db.subjects(RDF.type, sub):
                if '' and not i in beenthere:
                    yield i
                    beenthere.add(i)

class rdfsClass(rdfsSubject):
    """rdfSbject with some RDF Schema addons
    *Some* inferencing is implied
    Bleading edge: be careful"""
    rdf_type = RDFS.Class
    comment = rdfSingle(RDFS.comment)
    label = rdfSingle(RDFS.label)
    subClassOf = rdfMultiple(RDFS.subClassOf, range_type=RDFS.Class)

    @property
    def transitive_subClassOf(self):
        return [
            rdfsClass(s)
            for s in self.db.transitive_objects(
                self.resUri, RDFS.subClassOf)]

    @property
    def transitive_subClasses(self):
        return [
            rdfsClass(s)
            for s in self.db.transitive_subjects(
                RDFS.subClassOf, self.resUri)]

    @property
    def properties(self):
        # this doesn't get the rdfsProperty subclasses
        # return list(rdfsProperty.filter_by(domain=self.resUri))
        # TODO: why iterate all rdfsProperty subclasses
        #       try self.db.subjects(RDFS.domain,self.resUri)
        return [x for x in rdfsProperty.ClassInstances() if x.domain == self]

    def _emit_rdfSubject(self, visitedNS={}, visitedClass=set([])):
        """
        Produce the text that might be used for a .py file
        TODO: This code should probably move into the commands module since
        that's the only place it's used
        """
        ns, loc = self._splitname()
        try:
            prefix, qloc = self.db.qname(self.resUri).split(':')
        except:
            raise Exception(
                "don't know how to handle a qname like %s" % (
                    self.db.qname(self.resUri)))
        prefix = prefix.upper()

        if not visitedNS:
            src = """
from rdfalchemy import rdfSubject, Namespace, URIRef
from rdfalchemy.rdfsSubject import rdfsSubject
from rdfalchemy.orm import mapper

"""
            for k, v in self.db.namespaces():
                visitedNS[str(v)] = k.upper()
                src += '%s = Namespace("%s")\n' % (
                    k.upper().replace('-', '_'), v)
        else:
            src = ""

        mySupers = []
        for mySuper in self.subClassOf:
            sns, sloc = mySuper._splitname()
            if ns == sns:
                src += mySuper._emit_rdfSubject(visitedNS=visitedNS)
                mySupers.append(sloc.replace('-', '_'))

        mySupers = ",".join(mySupers) or "rdfsSubject"
        src += '\nclass %s(%s):\n' % (loc.replace('-', '_'), mySupers)
        src += '\t"""%s %s"""\n' % (self.label, self.comment)
        src += '\trdf_type = %s["%s"]\n' % (visitedNS[ns], loc)

        for p in self.properties:
            pns, ploc = p._splitname()
            ppy = '%s["%s"]' % (visitedNS[pns], ploc)
            try:
                assert str(p.range[RDF.type].resUri).endswith('Class')
                rns, rloc = rdfsSubject(p.range)._splitname()
                range_type = ', range_type = %s["%s"]' % (visitedNS[rns], rloc)
            except Exception:
                range_type = ''
            src += '\t%s = rdfMultiple(%s%s)\n' % (
                ploc.replace('-', '_'), ppy, range_type)

        # Just want this once at the end
        src.replace("mapper()\n", "")
        src += "mapper()\n"
        return src

class rdfsProperty(rdfsSubject):
    rdf_type = RDF.Property
    domain = rdfSingle(RDFS.domain, range_type=RDFS.Class)
    range = rdfSingle(RDFS.range)
    subPropertyOf = rdfMultiple(RDFS.subPropertyOf)
    default_descriptor = rdfMultiple

#####################################################################
# Beginings of a OWL package

class owlClass(rdfsClass):
    """rdfSbject with some RDF Schema addons
    *Some* inferencing is implied
    Bleading edge: be careful"""
    rdf_type = OWL["Class"]
    disjointWith = rdfMultiple(
        OWL["disjointWith"], range_type=OWL["Class"])
    equivalentClass = rdfMultiple(
        OWL["equivalentClass"], range_type=OWL["Class"])
    intersectionOf = rdfMultiple(
        OWL["intersectionOf"])
    unionOf = rdfMultiple(
        OWL["unionOf"])
    complementOf = rdfMultiple(
        OWL["complementOf"], range_type=OWL["Class"])

########################################
# properties

class owlFunctionalProperty(rdfsProperty):
    rdf_type = OWL.FunctionalProperty
    default_descriptor = rdfSingle

class owlDatatypeProperty(rdfsProperty):
    rdf_type = OWL.DatatypeProperty
    range = rdfSingle(RDFS.range, range_type=RDFS.Class)
    default_descriptor = rdfMultiple

########################################
# Object properties
class owlObjectProperty(rdfsProperty):
    rdf_type = OWL.ObjectProperty
    range = rdfSingle(RDFS.range, range_type=RDFS.Class)
    inverseOf = rdfSingle(OWL.inverseOf, range_type=OWL.ObjectProperty)
    default_descriptor = rdfMultiple

class owlInverseFunctionalProperty(owlObjectProperty):
    rdf_type = OWL.InverseFunctionalProperty
    default_descriptor = rdfSingle

class owlSymetricProperty(owlObjectProperty):
    rdf_type = OWL.SymetricProperty
    default_descriptor = rdfMultiple

class owlTransitiveProperty(owlObjectProperty):
    rdf_type = OWL.TransitiveProperty
    default_descriptor = owlTransitive

# this maps the return type of subClassOf back to rdfsClass
mapper()


text:
#import "SafariActivityItem.h"
#import "SafariService.h"

@implementation SafariActivityItem
- (NSString *)activityType
{
    return SafariActivity;
}

- (NSString *)activityTitle
{
    return @"Safari";
}

- (UIImage *)activityImage
{
    return [UIImage imageNamed:@"UIActivitySafari.png"];
}

- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems
{
    return YES;
}

- (void)prepareWithActivityItems:(NSArray *)activityItems
{
    // Need to check if image is nil
    // If image item is nil then make a dictionary with only url and title
    // url and title will never be nil as they will just be empty strings if nil was passed in
    NSDictionary *dict = [[NSDictionary alloc] initWithObjects:activityItems forKeys:([activityItems count] == 3) ? @[@"title",@"url", @"image"] : @[@"title",@"url"]];
    [SafariService shareWithParams:dict onViewController:nil];
}
@end


text:
package com.yxkang.android.commonparser.map;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by yexiaokang on 2016/6/6.
 */
public class MapFieldMethod {

    /**
     * reflect field
     */
    private Field mField;

    /**
     * reflect method
     */
    private Method mMethod;

    public Field getField() {
        return mField;
    }

    public void setField(Field field) {
        mField = field;
    }

    public Method getMethod() {
        return mMethod;
    }

    public void setMethod(Method method) {
        mMethod = method;
    }
}


text:
import java.util.List;

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

import com.google.bitcoin.core.Block;
import com.google.bitcoin.core.GetDataMessage;
import com.google.bitcoin.core.Message;
import com.google.bitcoin.core.Peer;
import com.google.bitcoin.core.PeerEventListener;
import com.google.bitcoin.core.Transaction;
import com.google.bitcoin.store.BlockStoreException;

public class ChancecoinPeerEventListener implements PeerEventListener {
    Logger logger = LoggerFactory.getLogger(ChancecoinPeerEventListener.class);

	@Override
	public List<Message> getData(Peer peer, GetDataMessage message) {
		return null;
	}

	@Override
	public void onBlocksDownloaded(Peer peer, Block block, int blocksLeft) {
		logger.info("Block downloaded: "+blocksLeft);
		/*
		//this doesn't work
		Blocks blocks = Blocks.getInstance();
		try {
			blocks.importBlock(block, blocks.blockStore.get(block.getHash()).getHeight());
		} catch (BlockStoreException e) {
		}
		*/
	}

	@Override
	public void onChainDownloadStarted(Peer peer, int blocksLeft) {
		logger.info("Chain download started: "+blocksLeft);
	}

	@Override
	public void onPeerConnected(Peer peer, int peerCount) {
		logger.info("Peer connected: "+peerCount);
	}

	@Override
	public void onPeerDisconnected(Peer peer, int peerCount) {
		logger.info("Peer disconnected: "+peerCount);
	}

	@Override
	public Message onPreMessageReceived(Peer peer, Message message) {
		return null;
	}

	@Override
	public void onTransaction(Peer peer, Transaction tx) {
		logger.info("Got transaction");
	}

}


text:
package com.leohart.buildwhisperer.repositories;

import com.leohart.buildwhisperer.status.BuildStatus;
import com.leohart.buildwhisperer.status.SimpleBuildStatus;

public class DummyBuildStatusRepository implements BuildStatusRepository<BuildStatus> {

	private BuildStatus buildStatus;

	public DummyBuildStatusRepository() {
		this.buildStatus = new SimpleBuildStatus(true);
	}

	public DummyBuildStatusRepository(BuildStatus buildStatus) {
		super();
		this.buildStatus = buildStatus;
	}

	@Override
	public BuildStatus getBuildStatus() throws BuildStatusRepositoryException {
		return this.buildStatus;
	}

}


text:
require 'spec_helper'

describe FeedsController do

  describe "GET 'show'" do

    context 'when the feed does not exist' do

      it 'returns not found' do
        get :show, feed_name: 'feed1', format: :atom

        assert_response 404
      end

    end

    context 'when the feed exists' do
      it 'renders the feed' do
        FactoryGirl.create(:feed, name: 'feed1')

        get :show, feed_name: 'feed1', format: :atom

        expect(response).to render_template(:show)
      end
    end

    context 'conditional get' do
      it 'returns 304' do
        feed = FactoryGirl.create(:feed, name: 'feed1')

        request.env['HTTP_IF_MODIFIED_SINCE'] = (feed.updated_at + 1).httpdate

        get :show, feed_name: 'feed1', format: :atom

        expect(response.status).to eq 304
        expect(response.body).to be_empty
      end

    end

  end

  describe "POST 'add_item'" do

    context 'when the feed does not exist' do

      it 'creates the feed' do
        post :add_item, feed_name: 'feed1', title: 'test', link: 'http://test.com/', author: 'a', content: 'c'

        expect(Feed.last.name).to eq 'feed1'
      end

      it 'adds an item to the feed' do
        post :add_item, feed_name: 'feed1', title: 'test', link: 'http://test.com/', author: 'a', content: 'c'

        feed_item = Feed.last.feed_items.first

        expect(feed_item.title).to eq 'test'
        expect(feed_item.link).to eq 'http://test.com/'
        expect(feed_item.author).to eq 'a'
        expect(feed_item.content).to eq 'c'
      end

      it 'sets the write authorization if provided' do
        request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(
            nil, 'secret')
        post :add_item, feed_name: 'feed1', title: 'test', link: 'http://test.com/', author: 'a', content: 'c'

        expect(Feed.last.write_auth).to_not be_nil
      end

    end

    context 'when the feed exists' do
      let(:feed) { FactoryGirl.create(:feed) }

      it 'adds an item to the feed' do
        post :add_item, feed_name: feed.name, title: 'test', link: 'http://test.com/', author: 'a', content: 'c'

        last = feed.feed_items.last

        expect(last.title).to eq 'test'
        expect(last.link).to eq 'http://test.com/'
        expect(last.author).to eq 'a'
        expect(last.content).to eq 'c'
      end

      context 'when the feed has a password' do
        let(:feed) { FactoryGirl.create(:feed, write_auth: 'secret') }
        let(:try_password) { 'secret' }

        before do
          request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(
              nil, try_password)
        end

        context 'when the password is correct' do

          it 'adds an item to the feed' do
            expect {
              post :add_item, feed_name: feed.name, link: 'http://test.com/'
            }.to change { Feed.count }.by(1)
          end

        end

        context 'when the password is incorrect' do
          let(:try_password) { 'wrong' }

          it 'returns unauthorized' do
            post :add_item, feed_name: feed.name, link: 'http://test.com/'

            assert_response 401
          end

        end
      end

    end

  end

end


text:
/**
 * This file provided by IPT-Intellectual Products & Technologies (IPT)
 * is for non-commercial testing and evaluation purposes only.
 * IPT reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
'use strict';

var sqlite3 = require('sqlite3').verbose();
const express = require('express');
const path = require('path');
// const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

const rootPath = path.normalize(path.join(__dirname, '..'));
const routes = require('./routes');
// const fs = require('fs');

const app = express();
app.set('app', path.join(rootPath, 'app'));

// uncomment after placing your favicon in /public
//app.use(favicon(dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// app.use(express.static(path.join(rootPath, 'app/assets')));

app.use('/api/comments', routes);
// app.get('/api/tests', function (req, res) {
//   res.send('Hello World!')
// })

/// catch 404 and forwarding to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res) {
    res.status(err.status || 500);
    res.json({
      message: err.message,
      error: err
    });
  });
} else {
  // production error handler
  // no stacktraces leaked to user
  app.use(function (err, req, res) {
    res.status(err.status || 500);
    res.json({
      message: err.message,
      error: {}
    });
  });
}

// Initialize DB
const DB_FILE = path.join(__dirname, 'comments.sqlite');
const TABLE_NAME = 'comments';
const db = new sqlite3.Database(DB_FILE, (err) => {
  if (err) throw err;

  //Test if comments table exists - if not create it
  let result = db.get(`SELECT name FROM sqlite_master WHERE type='table' AND name=?;`, [TABLE_NAME]);
  console.log(result);
  if (!result) {
    db.run(`CREATE TABLE comments (id INTEGER PRIMARY KEY, author TEXT, text TEXT);`)
      .then(() =>
        console.log(`Table "comments" successfully created in db: ${DB_FILE}`)
      );
  }
  console.log(`Successfully connected to SQLite server`);

  //Add db as app local property
  app.locals.db = db;

  //Start the server
  app.listen(9000, (err) => {
    if (err) throw err;
    console.log('Example app listening on port 9000!')
  });
});


text:
/**
 *
 *  Test variables
 *	005-cast-objects-to-scalars.phpt
 *
 */

/**
 *  Set up namespace
 */
namespace TestVariables {

	/**
	 *  A sample class, with methods to cast objects to scalars
	 */
	class Obj2Scalar : public Php::Base
	{
	public:
	    /**
	     *  C++ constructor and C++ destructpr
	     */
	    Obj2Scalar() {}
	    virtual ~Obj2Scalar() {}

	    /**
	     *  Cast to a string
	     *
	     *  Note that now we use const char* as return value, and not Php::Value.
	     *  The __toString function is detected at compile time, and it does
	     *  not have a fixed signature. You can return any value that can be picked
	     *  up by a Php::Value object.
	     *
	     *  @return const char *
	     */
	    const char *__toString()
	    {
	        return "Mount Meru, also called Sumeru (Sanskrit)";
	    }

	    /**
	     *  Cast to a integer
	     *  @return long
	     */
	    long __toInteger()
	    {
	        return 27032014;
	    }

	    /**
	     *  Cast to a floating point number
	     *  @return double
	     */
	    double __toFloat()
	    {
	        return 3.14159265359;
	    }

	    /**
	     *  Cast to a boolean
	     *  @return bool
	     */
	    bool __toBool()
	    {
	        return true;
	    }
	};

/**
 *  End of namespace
 */
}


text:
sbt-project-template
====================

A project to be cloned and slightly modified to bootstrap new sbt based projects


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/church-history/pioneer#pioneer-family-775375" xml:lang="eng" locale="eng" status="publish">
  <search-meta>
      <uri-title its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">pioneer-family-775375</uri-title>
      <source>pioneer-family-775375</source>
      <publication-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</publication-type>
      <media-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-04-09">2012-04-09</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">global-search</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">media</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">images</collection>
      </collections>
      <subjects>
          <subject>Pioneers</subject>
          <subject>Families</subject>
          <subject>Pioneer Clothing</subject>
          <subject>19th Century Clothing</subject>
          <subject>Portraits</subject>
          <subject>Clotheslines</subject>
          <subject>Parents</subject>
          <subject>Mothers</subject>
          <subject>Fathers</subject>
          <subject>Children</subject>
          <subject>Cabin</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/church-history/pioneer/pioneer-family-775375-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/church-history/pioneer/pioneer-family-775375-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>267 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/church-history/pioneer/pioneer-family-775375-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>299 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/church-history/pioneer/pioneer-family-775375-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>633 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/church-history/pioneer/pioneer-family-775375-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>1.2 MB</size>
                  <path>http://media.ldscdn.org/images/media-library/church-history/pioneer/pioneer-family-775375-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
<ldse-meta its:translate="no" xmlns="http://lds.org/code/lds-edit" xmlns:its="http://www.w3.org/2005/11/its"><document id="pioneer-family-775375" locale="eng" uri="/media-library/images/church-history/pioneer#pioneer-family-775375" status="publish" site="ldsorg" source="chq" words="134" tgp="0.4685"/><created username="lds-edit" userid=""/><last-modified date="2012-05-10T12:26:23.573084-06:00" username="lds-edit" userid=""/></ldse-meta></ldswebml>


text:
import { RefObject, useCallback, useEffect } from 'react';

import { cloneEvent, isKeyboardEvent } from '@proton/shared/lib/helpers/events';
import { KeyboardKey } from '@proton/shared/lib/interfaces';
import { isValidShortcut } from '@proton/shared/lib/shortcuts/helpers';
import { editorShortcuts } from '@proton/shared/lib/shortcuts/mail';

import { IFRAME_EVENTS_LIST, ROOSTER_EDITOR_WRAPPER_ID } from '../../constants';

const PAGE_EVENTS = [KeyboardKey.PageUp, KeyboardKey.PageDown];

/**
 * Calls event.preventDefault on matched events
 * Because events occuring inside an iframe can show prompts in browsers (ex : pressing crtl+s)
 * we need some specific event management here
 */
const preventKeyboardEvents = (event: Event) => {
    if (isKeyboardEvent(event)) {
        Object.values(editorShortcuts).forEach((shortcut) => {
            if (
                isValidShortcut(shortcut, event) ||
                // Need to wait for this issue to be fixed
                // https://bugs.chromium.org/p/chromium/issues/detail?id=890248
                PAGE_EVENTS.includes(event.key as KeyboardKey)
            ) {
                event.preventDefault();
            }
        });
    }
};

const canDispatchEvent = (event: Event): boolean => {
    if (isKeyboardEvent(event)) {
        // Cancel tab keyboard event dispatch for
        // keeping native focus management behavior
        if (event.key.toLowerCase() === 'tab') {
            return false;
        }
    }

    return true;
};

/**
 * Trigger some events manually because of Iframe stopping bubbling.
 * @param iframeRef
 */
const useBubbleIframeEvents = (iframeRef: RefObject<HTMLIFrameElement>) => {
    const handleBubble = useCallback((event: Event) => {
        const canDispatch = canDispatchEvent(event);
        preventKeyboardEvents(event);

        if (canDispatch) {
            const clonedEvent = cloneEvent(event);
            iframeRef.current?.dispatchEvent(clonedEvent);
        }
    }, []);

    useEffect(() => {
        const iframeRoosterDiv = iframeRef.current?.contentDocument?.getElementById(ROOSTER_EDITOR_WRAPPER_ID);

        if (!iframeRoosterDiv) {
            return;
        }

        IFRAME_EVENTS_LIST.forEach((eventName) => {
            iframeRoosterDiv.addEventListener(eventName, handleBubble);
        });

        return () => {
            IFRAME_EVENTS_LIST.forEach((eventName) => {
                iframeRoosterDiv.removeEventListener(eventName, handleBubble);
            });
        };
    }, []);
};

export default useBubbleIframeEvents;


text:
@implementation PXSequenceExportPrompter

- initWithDocument:(NSDocument *)aDocument
{
	[super init];
	fileTemplate = [[NSString stringWithFormat:@"%@ %%f", [[aDocument displayName] stringByDeletingPathExtension]] retain];
	[NSBundle loadNibNamed:@"PXSequenceExportPrompter" owner:self];
	[self setFileType:PixenImageFileType];
	savePanel = [[NSOpenPanel savePanel] retain];
	[savePanel setCanChooseDirectories:YES];
	[savePanel setTitle:@"Choose Target Folder"];
	[savePanel setPrompt:@"Export"];
	[savePanel setCanChooseFiles:NO];
	[savePanel setCanCreateDirectories:YES];
	[savePanel setAllowsMultipleSelection:NO];
	[savePanel setAccessoryView:view];
	return self;
}

- (void)dealloc
{
	[savePanel release];
	[fileType release];
	[super dealloc];
}

- (void)setFileType:(NSString *)newFT
{
	[fileType release];
	fileType = [newFT retain];
	[self setValue:[[[self fileTemplate] stringByDeletingPathExtension] stringByAppendingString:[NSString stringWithFormat:@".%@", [[[NSDocumentController sharedDocumentController] fileExtensionsFromType:newFT] objectAtIndex:0]]] forKey:@"fileTemplate"];
}

- (NSString *)fileTemplate
{
	return fileTemplate;
}

- (void)panelDidFinish:panel returnCode:(int)code contextInfo:(void *)info
{
	if (code == NSCancelButton) { return; }
	if (NSEqualRanges([fileTemplate rangeOfString:@"%f"], NSMakeRange(NSNotFound, 0)))
		fileTemplate = [fileTemplate stringByAppendingString:@" %f"];
	[_delegate performSelector:_didEndSelector withObject:self];
}

- (void)beginSheetModalForWindow:(NSWindow *)parentWindow modalDelegate:delegate didEndSelector:(SEL)didEndSelector
{
	_delegate = delegate;
	_didEndSelector = didEndSelector;
	[savePanel beginSheetForDirectory:nil file:nil types:nil modalForWindow:parentWindow modalDelegate:self didEndSelector:@selector(panelDidFinish:returnCode:contextInfo:) contextInfo:NULL];
}

- savePanel
{
	return savePanel;
}

- (NSArray *)fileTypes
{
	return [PXCanvasDocument writableTypes];
}

@end


text:
Microsoft Live
==============

Go to:

http://msdn.microsoft.com/en-us/library/cc287659(v=MSDN.10).aspx

Under the section: **To get your client ID**

Go to the Windows Live application management site.

Sign in.

Application Name: (your application name)
Language: English

Modify your **development.ini** file to include the following:

::

    live.client_id =
    live.client_secret =
    live.scope =


text:
<!DOCTYPE html>

	<title>Toaster</title>

						×


text:
(function () {
	'use strict'

	const SAMPLE_TEXT = [
		'(fun double (n)',
		' (* n 2))',
	].join('\n')

	const inputEditor = ace.edit('input-editor')
	inputEditor.setTheme('ace/theme/monokai')
	inputEditor.setFontSize(18)
	inputEditor.setValue(SAMPLE_TEXT, 1)
	inputEditor.on('input', onInput)

	const outputEditor = ace.edit('output-editor')
	outputEditor.setTheme('ace/theme/monokai')
	outputEditor.getSession().setMode('ace/mode/javascript')
	outputEditor.getSession().setUseWrapMode(true)
	outputEditor.setReadOnly(true)
	outputEditor.setFontSize(18)

	function onInput () {
		const inputText = inputEditor.getValue()
		try {
			const tokens = espace.Tokenizer.tokenize(inputText, {
				prefixes: {
					'\'': 'quote',
					':': 'symbol',
					'@': 'set',
					'#': 'map',
				},
			})

			const tree = espace.Parser.parse(tokens)

			outputEditor.setValue(JSON.stringify(tree, undefined, 2), 1)
		} catch (ex) {
			const exceptionObject = {
				message: ex.message,
				coords: ex.coords,
			}

			outputEditor.setValue(JSON.stringify(exceptionObject, undefined, 2), 1)
		}
	}
})()