text:
Installing CitoEngine
=====================

The following guide shows installation steps on ``Ubuntu 12.04 x86_64``. Theoretically application dependencies can be fulfilled on any
linux distribution i.e. Redhat, ArchLinux, etc. In future, we will try to include installation steps for other distributions as well.
Python module dependencies are installed using `pip`_ rather than system installer, this gives us more control towards using modules of specific versions.
The following steps assume that you will be installing in ``/opt/citoengine`` directory.

.. _pip: http://www.pip-installer.org/

Installation
------------

**Install dependencies**

.. code-block:: bash

    # Installing MySQL and Python development packages
    sudo apt-get install libmysqlclient-dev python-dev python-pip git
    sudo pip install virtualenv

.. note:: If you are going to use ldap authentication, then install the following as well  ``sudo apt-get install libldap2-dev libsasl2-dev libssl-dev``

**Downloading and installing the code**

We recommend you use ``virtualenv`` for running citoengine, this will help you manage dependencies better. Download the latest build

.. code-block:: bash

    cd /tmp
    git clone https://github.com/CitoEngine/cito_engine
    cd /tmp/cito_engine
    python setup.py install
    cd /opt/
    virtualenv /opt/citoengine
    source /opt/citoengine/bin/activate
    pip install -r /tmp/cito_engine/requirements.txt

**MySQL Installation and Configuration**

.. code-block:: bash

    # Install mysql server
    sudo apt-get install mysql-server mysql-client

    # Setup mysql root password
    sudo dpkg-reconfigure mysql-server-5.5

    # Create a new database 'citoengine'
    sudo mysqladmin -uroot -p create citoengine
    # Create a new mysql user
    /usr/bin/mysql -uroot -p -e "GRANT ALL PRIVILEGES ON citoengine.* TO 'citoengine_user'@'localhost' IDENTIFIED BY 'MINISTRYOFSILLYWALKS' with GRANT OPTION"

**Setting up RabbitMQ (Optional):**

If you are planning to use RabbitMQ, the following three lines should get you started.

.. code-block:: bash

    sudo rabbitmqctl add_user citoengine_user citoengine_pass
    sudo rabbitmqctl add_vhost /citoengine_event_listener
    sudo rabbitmqctl set_permissions -p /citoengine_event_listener citoengine_user ".*" ".*" ".*"

**Edit default settings:**  Copy the sample ``/opt/citoengine/conf/citoengine.conf-example`` to ``/opt/citoengine/conf/citoengine.conf``
and edit it accordingly.

**Message Queue Configuration:**

Edit the ``DATABASE`` configuration settings and change the settings. If you are running CitoEngine on AWS,
use AWS:SQS or if running onpremise, setup RabbitMQ as your message queue. Edit either of these configuration blocks and make sure you select ``QUEUE_TYPE`` to be either ``SQS`` or ``RABBITMQ``.

.. note:: Amazon SQS does not support message sequencing i.e. it does not guarantee first in, first out for message delivery. See http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Welcome.html

**Initializing the tables and creating an admin account.**

.. code-block:: bash

    source /opt/citoengine/bin/activate
    cd /opt/citoengine/app

    # Populate the database
    python manage.py migrate

    # Update django secret (for csrf)
    # If you are using the webapp on multiple nodes behind a load balancer,
    # make sure th secret_key.py file is same on all nodes.
    sudo sh -c '/opt/citoengine/bin/create-django-secret.py > /opt/citoengine/app/settings/secret_key.py'

    # Create your first CitoEngine superuser!
    python manage.py createsuperuser

**That's it, you are done!**

.. note:: You can always validate your installation using the command ``python manage.py validate``

Starting the services
---------------------

CitoEngine is divided into two components, ``webapp`` and ``poller``. You can run these two components using the helper
scripts ``/opt/citoengine/bin/citoengine-poller.sh`` and ``/opt/citoengine/bin/citoengine-webapp.sh``. If you are on Ubuntu,
you can configure to run them as upstart services using ``/opt/citoengine/bin/upstart/configure-upstart.sh``.

**Start CitoEngine SQS Poller service**

.. code-block:: bash

    /opt/citoengine/bin/citoengine-poller.sh

**Start CitoEngine Engine**

.. code-block:: bash

    /opt/citoengine/bin/citoengine-webapp.sh

Open your browser and access http://<hostname or IP>:8000 to login to CitoEngine with the admin account you created earlier.


text:
Wie der Name es ungefähr sagt, ein Präprozessor wird aufgerufen, bevor ein Skript ausgeführt wird.
Damit kann man das Skript beispielsweise in den Debug-Modus versetzen.

## Einen Präprozessor einbinden

Ein Präprozessor wird wie ein #Kommentar eingebunden.
Achte darauf, dass du deine Kommentare ansonsten nicht aus Versehen mit einem Präprozessor-Schlüsselwort startest.

```zenscript
#debug ist mein Lieblingswort und ich würde es am allerliebsten überall als Kommentar einfügen
```

↑ Würde den Debug-Modus aktivieren, da das `#debug`-Schlüsselwort gefunden wurde. Wenn du dies möglichst verhindern möchtest, empfehlen wir dir, deine Kommentare mit `//` zu starten.

redpajama_set_name: RedPajamaGithub


text:
namespace Anycmd.ViewModel
{
    using Engine.Ac;
    using Exceptions;
    using System.Globalization;
    using Util;

    /// <summary>
    /// 为AcDomain提供扩展方法。<see cref="IAcDomain"/>
    /// </summary>
    public static class AcDomainExtension
    {
        /// <summary>
        /// 根据系统字典将字典项码翻译为字典项名
        /// </summary>
        /// <param name="acDomain"></param>
        /// <param name="codespace"></param>
        /// <param name="entityTypeCode"></param>
        /// <param name="propertyCode"></param>
        /// <param name="dicItemCode"></param>
        /// <returns></returns>
        public static string Translate(this IAcDomain acDomain, string codespace, string entityTypeCode, string propertyCode, int dicItemCode)
        {
            return Translate(acDomain, codespace, entityTypeCode, propertyCode, dicItemCode.ToString(CultureInfo.InvariantCulture));
        }

        /// <summary>
        /// 根据系统字典将字典项码翻译为字典项名
        /// </summary>
        /// <param name="acDomain"></param>
        /// <param name="codespace"></param>
        /// <param name="entityTypeCode"></param>
        /// <param name="propertyCode"></param>
        /// <param name="dicItemCode"></param>
        /// <returns></returns>
        public static string Translate(this IAcDomain acDomain, string codespace, string entityTypeCode, string propertyCode, bool dicItemCode)
        {
            return Translate(acDomain, codespace, entityTypeCode, propertyCode, dicItemCode.ToString());
        }

        /// <summary>
        /// 根据系统字典将字典项码翻译为字典项名
        /// </summary>
        /// <param name="acDomain"></param>
        /// <param name="codespace"></param>
        /// <param name="entityTypeCode"></param>
        /// <param name="propertyCode"></param>
        /// <param name="dicItemCode"></param>
        /// <returns></returns>
        public static string Translate(this IAcDomain acDomain, string codespace, string entityTypeCode, string propertyCode, string dicItemCode)
        {
            EntityTypeState entityType;
            if (!acDomain.EntityTypeSet.TryGetEntityType(new Coder(codespace, entityTypeCode), out entityType))
            {
                throw new AnycmdException(string.Format("意外的实体类型:{0}.{1}", codespace, entityTypeCode));
            }
            PropertyState property;
            if (!acDomain.EntityTypeSet.TryGetProperty(entityType, propertyCode, out property))
            {
                return dicItemCode;
            }
            if (property.DicId.HasValue)
            {
                CatalogState dicState;
                if (!acDomain.CatalogSet.TryGetCatalog(property.DicId.Value, out dicState))
                {
                    return dicItemCode;
                }
                CatalogState dicitem;
                if (acDomain.CatalogSet.TryGetCatalog(dicState.Code + "." + dicItemCode, out dicitem))
                {
                    return dicitem.Name;
                }
            }
            return dicItemCode;
        }
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta charset="utf-8" />
    <title>Grimoire dashboard (proposal)</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

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

    <link href="css/font-awesome-4.0.3/css/font-awesome.min.css" rel="stylesheet">

    <link href="css/jasny-bootstrap.min.css" rel="stylesheet" media="screen">

    <link href="css/bitergia.css" rel="stylesheet">

        Ooops ...
        <form action="contributor.html" class="navbar-form navbar-right hidden-xs" role="search" style="margin-right: 25px;">

            <input type="text" class="form-control" placeholder="company, person, issue, etc.">

          <button type="submit" class="btn btn-default"> Search</button>
        </form>

 It seems something has gone bad!

Sorry, it might be our fault

It seems that the web page you are looking for is not here...

            <button type="button" class="btn btn-success"> Try going back</button>
            <button type="button" class="btn btn-info"> Try projects site map</button>
            <button type="button" class="btn btn-info"> Leave us a message</button>

            © 2012-2014


text:
'use strict';

export function poop () {
    console.log('In the litter box I go!');
}
// export default function () {
export function meow () {
    console.log('Hey. Wake up!');
}

export default {
    meow: meow,
    poop: poop
};


text:
require File.expand_path('../fixtures/classes.rb', __FILE__)

describe "Rubinius::MonoInlineCache#ip" do
  before :each do
    MonoInlineCacheSpec::Bar.new.call_site_test
    @mono_inline_cache = MonoInlineCacheSpec::Bar::CallSiteTest.call_sites[0]
  end

  it "sets the correct ip for the call" do
    @mono_inline_cache.ip.should == 1
  end

end


text:
`<taaabs-base-overview>` is a graphical element that load and display each base of a ktbs.

Example:

    <taaabs-base-overview ktbs-url="https://localhost:3000/ktbs/" language="{{i18n}}">
    </taaabs-base-overview>

Source files: taaabs-base-overview

@demo demo/index.html


text:
package com.uvasoftware.scanii.models;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.time.Instant;
import java.util.Map;
import java.util.Set;

public class ScaniiAccountInfo extends ScaniiResult {
  @JsonProperty("name")
  private String name;
  @JsonProperty("balance")
  private long balance;
  @JsonProperty("starting_balance")
  private long startingBalance;
  @JsonProperty("billing_email")
  private String billingEmail;
  @JsonProperty("subscription")
  private String subscription;
  @JsonProperty("creation_date")
  private Instant creationDate;
  @JsonProperty("modification_date")
  private Instant modificationDate;
  @JsonProperty("users")
  private Map<String, User> users;
  @JsonProperty("keys")
  private Map<String, ApiKey> keys;

  public String getName() {
    return name;
  }

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

  public long getBalance() {
    return balance;
  }

  public void setBalance(long balance) {
    this.balance = balance;
  }

  public long getStartingBalance() {
    return startingBalance;
  }

  public void setStartingBalance(long startingBalance) {
    this.startingBalance = startingBalance;
  }

  public String getBillingEmail() {
    return billingEmail;
  }

  public void setBillingEmail(String billingEmail) {
    this.billingEmail = billingEmail;
  }

  public String getSubscription() {
    return subscription;
  }

  public void setSubscription(String subscription) {
    this.subscription = subscription;
  }

  public Instant getCreationDate() {
    return creationDate;
  }

  public void setCreationDate(Instant creationDate) {
    this.creationDate = creationDate;
  }

  public Instant getModificationDate() {
    return modificationDate;
  }

  public void setModificationDate(Instant modificationDate) {
    this.modificationDate = modificationDate;
  }

  public Map<String, User> getUsers() {
    return users;
  }

  public void setUsers(Map<String, User> users) {
    this.users = users;
  }

  public Map<String, ApiKey> getKeys() {
    return keys;
  }

  public void setKeys(Map<String, ApiKey> keys) {
    this.keys = keys;
  }

  @Override
  public String toString() {
    return "ScaniiAccountInfo{" +
      "name='" + name + '\'' +
      ", balance=" + balance +
      ", startingBalance=" + startingBalance +
      ", billingEmail='" + billingEmail + '\'' +
      ", subscription='" + subscription + '\'' +
      ", creationDate=" + creationDate +
      ", modificationDate=" + modificationDate +
      ", users=" + users +
      ", keys=" + keys +
      '}';
  }

  private static class User {
    @JsonProperty("creation_date")
    private Instant creationDate;
    @JsonProperty("last_login_date")
    private Instant lastLoginDate;

    public Instant getCreationDate() {
      return creationDate;
    }

    public void setCreationDate(Instant creationDate) {
      this.creationDate = creationDate;
    }

    public Instant getLastLoginDate() {
      return lastLoginDate;
    }

    public void setLastLoginDate(Instant lastLoginDate) {
      this.lastLoginDate = lastLoginDate;
    }
  }

  private static class ApiKey {
    @JsonProperty("active")
    private boolean active;
    @JsonProperty("creation_date")
    private Instant creationDate;
    @JsonProperty("last_seen_date")
    private Instant lastSeenDate;
    @JsonProperty("detection_categories_enabled")
    private Set<String> detectionCategoriesEnabled;
    @JsonProperty("tags")
    private Set<String> tags;

    public boolean isActive() {
      return active;
    }

    public void setActive(boolean active) {
      this.active = active;
    }

    public Instant getCreationDate() {
      return creationDate;
    }

    public void setCreationDate(Instant creationDate) {
      this.creationDate = creationDate;
    }

    public Instant getLastSeenDate() {
      return lastSeenDate;
    }

    public void setLastSeenDate(Instant lastSeenDate) {
      this.lastSeenDate = lastSeenDate;
    }

    public Set<String> getDetectionCategoriesEnabled() {
      return detectionCategoriesEnabled;
    }

    public void setDetectionCategoriesEnabled(Set<String> detectionCategoriesEnabled) {
      this.detectionCategoriesEnabled = detectionCategoriesEnabled;
    }

    public Set<String> getTags() {
      return tags;
    }

    public void setTags(Set<String> tags) {
      this.tags = tags;
    }
  }
}


text:
@implementation NSDateFormatter (JSONAPIDateFormatter)

+ (instancetype)RFC3339DateFormatter
{
  static NSDateFormatter *dateFormatter = nil;

  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier: @"en_US_POSIX"];

    [dateFormatter setLocale: enUSPOSIXLocale];
    [dateFormatter setDateFormat: @"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'"];
    [dateFormatter setTimeZone: [NSTimeZone timeZoneForSecondsFromGMT: 0]];
  });

  return dateFormatter;
}

@end


text:
package org.apache.zookeeper.test;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooDefs.Ids;
import org.junit.Assert;
import org.junit.Test;

public class DisconnectedWatcherTest extends ClientBase {
    protected static final Logger LOG = Logger.getLogger(WatcherTest.class);
    final int TIMEOUT = 5000;

    private class MyWatcher extends CountdownWatcher {
        LinkedBlockingQueue<WatchedEvent> events =
            new LinkedBlockingQueue<WatchedEvent>();

        public void process(WatchedEvent event) {
            super.process(event);
            if (event.getType() != Event.EventType.None) {
                try {
                    events.put(event);
                } catch (InterruptedException e) {
                    LOG.warn("ignoring interrupt during event.put");
                }
            }
        }
    }

    // @see jira issue ZOOKEEPER-961

    @Test
    public void testChildWatcherAutoResetWithChroot() throws Exception {
        ZooKeeper zk1 = createClient();

        zk1.create("/ch1", null, Ids.OPEN_ACL_UNSAFE,
                    CreateMode.PERSISTENT);

        MyWatcher watcher = new MyWatcher();
        ZooKeeper zk2 = createClient(watcher, hostPort + "/ch1");
        zk2.getChildren("/", true );

        // this call shouldn't trigger any error or watch
        zk1.create("/youdontmatter1", null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);

        // this should trigger the watch
        zk1.create("/ch1/youshouldmatter1", null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        WatchedEvent e = watcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
        Assert.assertNotNull(e);
        Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
        Assert.assertEquals("/", e.getPath());

        MyWatcher childWatcher = new MyWatcher();
        zk2.getChildren("/", childWatcher);

        stopServer();
        watcher.waitForDisconnected(3000);
        startServer();
        watcher.waitForConnected(3000);

        // this should trigger the watch
        zk1.create("/ch1/youshouldmatter2", null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        e = childWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
        Assert.assertNotNull(e);
        Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
        Assert.assertEquals("/", e.getPath());
    }

    @Test
    public void testDefaultWatcherAutoResetWithChroot() throws Exception {
        ZooKeeper zk1 = createClient();

        zk1.create("/ch1", null, Ids.OPEN_ACL_UNSAFE,
                    CreateMode.PERSISTENT);

        MyWatcher watcher = new MyWatcher();
        ZooKeeper zk2 = createClient(watcher, hostPort + "/ch1");
        zk2.getChildren("/", true );

        // this call shouldn't trigger any error or watch
        zk1.create("/youdontmatter1", null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);

        // this should trigger the watch
        zk1.create("/ch1/youshouldmatter1", null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        WatchedEvent e = watcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
        Assert.assertNotNull(e);
        Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
        Assert.assertEquals("/", e.getPath());

        zk2.getChildren("/", true );

        stopServer();
        watcher.waitForDisconnected(3000);
        startServer();
        watcher.waitForConnected(3000);

        // this should trigger the watch
        zk1.create("/ch1/youshouldmatter2", null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        e = watcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
        Assert.assertNotNull(e);
        Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
        Assert.assertEquals("/", e.getPath());
    }

    @Test
    public void testDeepChildWatcherAutoResetWithChroot() throws Exception {
        ZooKeeper zk1 = createClient();

        zk1.create("/ch1", null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        zk1.create("/ch1/here", null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        zk1.create("/ch1/here/we", null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        zk1.create("/ch1/here/we/are", null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);

        MyWatcher watcher = new MyWatcher();
        ZooKeeper zk2 = createClient(watcher, hostPort + "/ch1/here/we");
        zk2.getChildren("/are", true );

        // this should trigger the watch
        zk1.create("/ch1/here/we/are/now", null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        WatchedEvent e = watcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
        Assert.assertNotNull(e);
        Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
        Assert.assertEquals("/are", e.getPath());

        MyWatcher childWatcher = new MyWatcher();
        zk2.getChildren("/are", childWatcher);

        stopServer();
        watcher.waitForDisconnected(3000);
        startServer();
        watcher.waitForConnected(3000);

        // this should trigger the watch
        zk1.create("/ch1/here/we/are/again", null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        e = childWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
        Assert.assertNotNull(e);
        Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
        Assert.assertEquals("/are", e.getPath());
    }
}


text:
<?php

/*
 * This file is part of Sulu.
 *
 * (c) Sulu GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Bundle\ArticleBundle\DependencyInjection;

use Sulu\Bundle\ArticleBundle\Document\ArticlePageViewObject;
use Sulu\Bundle\ArticleBundle\Document\ArticleViewDocument;
use Sulu\Bundle\ArticleBundle\Domain\Model\Article;
use Sulu\Bundle\ArticleBundle\Domain\Model\ArticleDimensionContent;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * Initializes configuration tree for article-bundle.
 */
class Configuration implements ConfigurationInterface
{
    public const ARTICLE_STORAGE_PHPCR = 'phpcr';
    public const ARTICLE_STORAGE_EXPERIMENTAL = 'experimental';

    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('sulu_article');
        $rootNode = $treeBuilder->getRootNode();

        $rootNode
            ->children()
                ->enumNode('storage')
                    ->values([self::ARTICLE_STORAGE_PHPCR, self::ARTICLE_STORAGE_EXPERIMENTAL])
                    ->defaultValue(self::ARTICLE_STORAGE_PHPCR)
                ->end()
                ->arrayNode('objects')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->arrayNode('article')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('model')->defaultValue(Article::class)->end()
                            ->end()
                        ->end()
                        ->arrayNode('article_content')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('model')->defaultValue(ArticleDimensionContent::class)->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
                ->scalarNode('index_name')->end()
                ->arrayNode('hosts')
                    ->prototype('scalar')->end()
                ->end()
                ->arrayNode('default_main_webspace')
                    ->useAttributeAsKey('locale')
                    ->beforeNormalization()
                        ->ifString()
                        ->then(function($v) {
                            return ['default' => $v];
                        })
                    ->end()
                    ->prototype('scalar')->end()
                ->end()
                ->arrayNode('default_additional_webspaces')
                    ->beforeNormalization()
                        ->ifTrue(function($v) {
                            return count(array_filter(array_keys($v), 'is_string')) <= 0;
                        })
                        ->then(function($v) {
                            return ['default' => $v];
                        })
                    ->end()
                    ->prototype('array')->useAttributeAsKey('locale')->prototype('scalar')->end()->end()
                    ->defaultValue([])
                ->end()
                ->arrayNode('smart_content')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->integerNode('default_limit')->defaultValue(100)->end()
                    ->end()
                ->end()
                ->arrayNode('documents')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->arrayNode('article')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('view')->defaultValue(ArticleViewDocument::class)->end()
                            ->end()
                        ->end()
                        ->arrayNode('article_page')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('view')->defaultValue(ArticlePageViewObject::class)->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('types')
                    ->useAttributeAsKey('name')
                    ->normalizeKeys(false)
                    ->prototype('array')
                        ->children()
                            ->scalarNode('translation_key')->end()
                        ->end()
                    ->end()
                ->end()
                ->scalarNode('display_tab_all')->defaultTrue()->info('Display tab \'all\' in list view')->end()
                ->scalarNode('default_author')->defaultTrue()->info('Set default author if none isset')->end()
                ->arrayNode('search_fields')
                    ->prototype('scalar')->end()->defaultValue([
                        'title',
                        'excerpt.title',
                        'excerpt.description',
                        'excerpt.seo.title',
                        'excerpt.seo.description',
                        'excerpt.seo.keywords',
                        'teaser_description',
                    ])
                ->end()
            ->end();

        return $treeBuilder;
    }
}


text:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.views.generic.simple import direct_to_template
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

from django.contrib import admin
from django.contrib.auth.views import login, logout

from cellcounter.main.views import new_count, images_by_cell_type, ListCellTypesView, similar_images, thumbnail, page

admin.autodiscover()

urlpatterns = patterns('',

    url(r'^$', direct_to_template, {'template': 'main/index.html'},
            name="index"),

    url(r'^count/$', new_count, name="count_home"),
    url(r'^count/new/$', new_count, name="new_count"),
    url(r'^discover/$', direct_to_template, {'template': 'main/discover.html'}, name="discover"),
    url(r'^about/$', direct_to_template, {'template': 'main/about.html'}, name="about"),

    url(r'^images/celltype/(?P<cell_type>\w+)/$', images_by_cell_type, name="images_by_cell_type"),
    url(r'^images/similar/(?P<cell_image_pk>\d+)/$', similar_images, name="images_by_similar_cell"),
    url(r'^images/thumbnail/(?P<cell_image_pk>\d+)/$', thumbnail, name="thumbnail"),
    url(r'^images/page/(?P<cell_image_pk>\d+)/$', page, name="page"),

    url(r'^api/cell_types/$', ListCellTypesView.as_view(), name="cell_types"),

    url(r'^login/$', login, {'template_name': 'main/login.html'}, name='login'),
    url(r'^logout/$', logout, {'next_page': '/'}, name='logout'),

    url(r'^accounts/', include('cellcounter.accounts.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^terms$', direct_to_template, {'template': 'main/terms.html'},
            name="terms"),
    url(r'^privacy$', direct_to_template, {'template': 'main/privacy.html'},
            name="privacy"),
)

urlpatterns += staticfiles_urlpatterns()
urlpatterns += url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL.strip("/"), 'django.views.static.serve',
        {'document_root': settings.MEDIA_ROOT}),
urlpatterns += url(r'^%s(?P<path>.*)$' % settings.STATIC_URL.strip("/"), 'django.views.static.serve',
        {'document_root': settings.STATIC_ROOT}),


text:
    {{error.message}}

<form class="form" name="thingForm">

        Name
        <input required ng-model="thing.name" id="name" name="name" class="form-control" />

        Price
        <input type="number" ng-model="thing.price" id="price" name="price" class="form-control" />

    <button ng-disabled="!thingForm.$valid" class="btn btn-primary" ng-click="save()">Save</button>
</form>


text:
<?php

namespace AppBundle\Form\Report;

use AppBundle\Entity\Report\MoneyTransaction;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type as FormTypes;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

class MoneyTransactionType extends AbstractType
{
    /**
     * @var AuthorizationCheckerInterface
     */
    private $authorizationChecker;

    /**
     * @var int
     */
    private $step;

    /**
     * @var string in/out
     */
    private $type;

    /**
     * @var string
     */
    private $selectedCategory;

    /**
     * @return array where keys and values are the categoriesID. e.g. [broadband=>null, fees=>null]
     */
    private function getCategories()
    {
        $ret = [];

        foreach (MoneyTransaction::$categories as $cat) {
            $categoryId = $cat[0];
            $type = $cat[3];
            // filter by user roles (if specified)
            $allowedRoles = isset($cat[4]) ? $cat[4] : null;
            $isCategoryAllowedForThisRole = $allowedRoles === null || $this->authorizationChecker->isGranted($allowedRoles);
            // filter by
            if ($type === $this->type && $isCategoryAllowedForThisRole) {
                $ret[$categoryId] = $categoryId;
            }
        }

        return $ret;
    }

    /**
     * @return bool
     */
    private function isDescriptionMandatory()
    {
        foreach (MoneyTransaction::$categories as $row) {
            $categoryId = $row[0];
            $hasDetails = $row[1];
            if ($categoryId == $this->selectedCategory) {
                return $hasDetails;
            }
        }
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->authorizationChecker = $options['authChecker'];
        $this->step = (int) $options['step'];
        $this->type = $options['type'];
        $this->selectedCategory = $options['selectedCategory'];

        $builder->add('id', FormTypes\HiddenType::class);

        if ($this->step === 1) {
            $builder->add('category', FormTypes\ChoiceType::class, [
                'choices'  => $this->getCategories(),
                'expanded' => true,
            ]);
        }

        if ($this->step === 2) {
            $builder->add('description', FormTypes\TextareaType::class, [
                'required' => $this->isDescriptionMandatory(),
            ]);

            $builder->add('amount', FormTypes\NumberType::class, [
                'scale'       => 2,
                'grouping'        => true,
                'error_bubbling'  => false, // keep (and show) the error (Default behaviour). if true, error is lost
                'invalid_message' => 'moneyTransaction.form.amount.type',
            ]);

            $reportType = $options['report']->getType();

            if (!empty($options['report']->getBankAccountOptions()) && $options['report']->canLinkToBankAccounts())
            {
                $builder->add('bankAccountId', FormTypes\ChoiceType::class, [
                    'choices' => $options['report']->getBankAccountOptions(),
                    'placeholder' => 'Please select',
                    'label' => 'form.bankAccount.money' . ucfirst($this->type) . '.label'
                ]);
            }
        }

        $builder->add('save', FormTypes\SubmitType::class);
    }

    public function getBlockPrefix()
    {
        return 'account';
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'selectedCategory'          => null,
            'translation_domain'        => 'report-money-transaction',
            'choice_translation_domain' => 'report-money-transaction',
            'validation_groups'         => function () {
                $validationGroups = [];
                if ($this->step === 1) {
                    $validationGroups[] = 'transaction-category';
                }
                if ($this->step === 2) {
                    $validationGroups[] = 'transaction-amount';
                    if ($this->isDescriptionMandatory()) {
                        $validationGroups[] = 'transaction-description';
                    }
                }

                return $validationGroups;
            },
        ])
        ->setRequired(['report', 'step', 'type', 'authChecker'])
        ->setAllowedTypes('authChecker', AuthorizationCheckerInterface::class);
        ;
    }
}


text:
<?php
if ( ! class_exists( 'WP_List_Table' ) ) {
	require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}

/**
 * Class LanguagesTable
 */
class LanguagesTable extends WP_List_Table {

	var $data = array();

	var $table_fields = array();

	var $found_data = array();

	var $_column_headers = array();

	/**
	 *  Constructor.
	 */
	public function __construct() {

		parent::__construct( array(
			'singular' => __( 'item', 'wpglobus' ),
			// singular name of the listed records
			'plural'   => __( 'items', 'wpglobus' ),
			// plural name of the listed records
			'ajax'     => true
			// does this table support ajax?
		) );

		$this->get_data();

		$this->display_table();

	}

	/**
	 * Fill out table_fields and data arrays
	 * @return void
	 */
	function get_data() {

		$config = WPGlobus::Config();

		$this->table_fields = array(
			'wpglobus_code'             => array(
				'caption'  => __( 'Code', 'wpglobus' ),
				'sortable' => true,
				'order'    => 'asc',
				'actions'  => array(
					'edit'   => array(
						'action'  => 'edit',
						'caption' => __( 'Edit', 'wpglobus' ),
						'ajaxify' => false
					),
					'delete' => array(
						'action'  => 'delete',
						'caption' => __( 'Delete', 'wpglobus' ),
						'ajaxify' => false
					)
				)
			),
			'wpglobus_file'             => array(
				'caption'  => __( 'File', 'wpglobus' ),
				'sortable' => false,
				'order'    => 'desc'
			),
			'wpglobus_flag'             => array(
				'caption'  => __( 'Flag', 'wpglobus' ),
				'sortable' => false,
				'order'    => 'desc'
			),
			'wpglobus_locale'           => array(
				'caption'  => __( 'Locale', 'wpglobus' ),
				'sortable' => true,
				'order'    => 'desc'
			),
			'wpglobus_language_name'    => array(
				'caption'  => __( 'Language name', 'wpglobus' ),
				'sortable' => false,
				'order'    => 'desc'
			),
			'wpglobus_en_language_name' => array(
				'caption'  => __( 'English language name', 'wpglobus' ),
				'sortable' => true
			)
		);

		foreach ( $config->language_name as $code => $name ) {

			$row['wpglobus_ID']               = $code;
			$row['wpglobus_file']             = $config->flag[ $code ];
			$row['wpglobus_flag']             =
				'flags_url . $config->flag[ $code ] . '" />';
			$row['wpglobus_locale']           = $config->locale[ $code ];
			$row['wpglobus_code']             = $code;
			$row['wpglobus_language_name']    = $name;
			$row['wpglobus_en_language_name'] = $config->en_language_name[ $code ];

			$this->data[] = $row;

		}

	}

	function no_items() {
		_e( 'No items found', 'wpglobus' );
	}

	function display_table() {

		$this->prepare_items();
		?>

			<a id="wpglobus_add_language"
			   href="<?php admin_url(); ?>admin.php?page=<?php echo WPGlobus::LANGUAGE_EDIT_PAGE; ?>&action=add"
			   class="button button-primary"><?php esc_html_e( 'Add new Language', 'wpglobus' ); ?>

			<?php $this->prepare_items(); ?>

				<form method="post">
					<?php $this->display(); ?>
				</form>

    <?php

	}

	/**
	 * Prepares the list of items for displaying.
	 * @access public
	 * @return void
	 */
	function prepare_items() {

		$columns               = $this->get_columns();
		$hidden                = array();
		$sortable              = $this->get_sortable_columns();
		$this->_column_headers = array(
			$columns,
			$hidden,
			$sortable
		);

		/**
		 * Optional. You can handle your bulk actions however you see fit. In this
		 * case, we'll handle them within our package just to keep things clean.
		 */
		$this->process_bulk_action();

		/**
		 * You can handle your row actions
		 */
		$this->process_row_action();

		usort( $this->data, array(
			$this,
			'usort_reorder'
		) );

		$per_page     = 1000;
		$current_page = $this->get_pagenum();
		$total_items  = count( $this->data );

		// only necessary because we have sample data
		$this->found_data = array_slice( $this->data, ( ( $current_page - 1 ) * $per_page ), $per_page );

		/**
		 * REQUIRED. We also have to register our pagination options & calculations.
		 */
		$this->set_pagination_args( array(
			'total_items' => $total_items,
			//WE have to calculate the total number of items
			'per_page'    => $per_page,
			//WE have to determine how many items to show on a page
			'total_pages' => ceil( $total_items / $per_page )
			//WE have to calculate the total number of pages
		) );

		/** @var  WP_List_table class */
		$this->items = $this->found_data;

	}

	/**
	 * @return array
	 */
	function get_columns() {

		$columns = array();

		foreach ( $this->table_fields as $field => $attrs ) {
			$columns[ $field ] = $attrs['caption'];
		}

		return $columns;

	}

	/**
	 * Get a list of sortable columns. The format is:
	 * 'internal-name' => 'orderby'
	 * or
	 * 'internal-name' => array( 'orderby', true )
	 * The second format will make the initial sorting order be descending
	 * @since  3.1.0
	 * @access protected
	 * @return array
	 */
	function get_sortable_columns() {
		$sortable_columns = array();
		foreach ( $this->table_fields as $field => $attrs ) {
			if ( $attrs['sortable'] ) {
				$sortable_columns[ $field ] = array(
					$field,
					false
				);
			}
		}

		return $sortable_columns;
	}

	function process_bulk_action() {
	}

	function process_row_action() {
	}

	/**
	 * User's defined function
	 * @since    0.1
	 *
	 * @param $a
	 * @param $b
	 *
	 * @internal param $
	 * @return int
	 */
	function usort_reorder( $a, $b ) {
		// If no sort, get the default
		$i     = 0;
		$field = $default_field = 'source';

		foreach ( $this->table_fields as $field => $attrs ) {
			$default_field = ( $i == 0 ) ? $field : $default_field;
			if ( isset( $attrs['order'] ) ) {
				break;
			}
			$i ++;
		}
		$field   = ( isset( $attrs['order'] ) ) ? $field : $default_field;
		$orderby = ( ! empty( $_GET['orderby'] ) ) ? $_GET['orderby'] : $field;

		// If no order, default to asc
		if ( ! empty( $_GET['order'] ) ) {
			$order = $_GET['order'];
		} else {
			$order = ( isset( $attrs['order'] ) ) ? $attrs['order'] : 'asc';
		}

		// Determine sort order
		$result = strcmp( $a[ $orderby ], $b[ $orderby ] );

		// Send final sort direction to usort
		return ( $order === 'asc' ) ? $result : - $result;
	}

	/**
	 * Define function for add item actions by name 'column_flag'
	 * @since 1.0.0
	 *
	 * @param  $item array
	 *
	 * @return string
	 */
	function column_wpglobus_flag( $item ) {
		return $item['wpglobus_flag'];
	}

	/**
	 * Define function for add item actions by name 'column_locale'
	 * @since 1.0.0
	 *
	 * @param  $item array
	 *
	 * @return string
	 */
	function column_wpglobus_locale( $item ) {
		return $item['wpglobus_locale'];
	}

	/**
	 * Define function for add item actions by name 'column_code'
	 * @since 1.0.0
	 *
	 * @param  $item array
	 *
	 * @return string
	 */
	function column_wpglobus_code( $item ) {

		if ( ! empty( $this->table_fields['wpglobus_code']['actions'] ) ) {

			$config = WPGlobus::Config();
			$actions = array();

			foreach ( $this->table_fields['wpglobus_code']['actions'] as $action => $data ) {
				/** add actions for language code */
				$class = $data['ajaxify'] ? 'class="ajaxify"' : '';

				switch ( $action ) {
					case 'edit' :
						$actions['edit'] =
							sprintf( '%3s', $class, admin_url() . 'admin.php?page=' . WPGlobus::LANGUAGE_EDIT_PAGE . '&lang=' . $item['wpglobus_code'] . '&action=edit', $data['caption'] );
						break;
					case 'delete' :
						if ( $item['wpglobus_code'] == $config->default_language ) {
							$actions['delete'] =
								sprintf( '%2s', $class, __( 'Default language', 'wpglobus' ) );
						} else {
							$actions['delete'] =
								sprintf( '%3s', $class, admin_url() . 'admin.php?page=' . WPGlobus::LANGUAGE_EDIT_PAGE . '&lang=' . $item['wpglobus_code'] . '&action=delete', $data['caption'] );
						}
						break;
				}

			}

			return sprintf( '%1s %2s', $item['wpglobus_code'], $this->row_actions( $actions ) );

		} else {

			return $item['wpglobus_code'];

		}

	}

	/**
	 * Define function for add item actions by name 'column_default'
	 * @since 1.0.0
	 *
	 * @param  $item        array
	 * @param  $column_name string
	 *
	 * @return string
	 */
	function column_default( $item, $column_name ) {

		if ( isset( $this->table_fields[ $column_name ] ) ) {
			return $item[ $column_name ];
		} else {
			return print_r( $item, true ); //Show the whole array for troubleshooting purposes
		}

	}

	/**
	 * Define function for add item actions by name 'column_cb'
	 * @since 1.0.0
	 *
	 * @param  $item array
	 *
	 * @return string
	 */
	function column_cb( $item ) {
		return sprintf(
			'<input type="checkbox" name="item[]" value="%s" />', $item['ID']
		);
	}

	/**
	 * Generate the table navigation above or below the table
	 * @since  3.1.0
	 * @access protected
	 *
	 * @param string $which
	 */
	function display_tablenav( $which ) {
		?>

		<div class="tablenav <?php echo esc_attr( $which ); ?>">

				<?php $this->bulk_actions(); ?>

			<?php
			$this->extra_tablenav( $which );
			$this->pagination( $which );
			?>

	<?php

	}

}

# --- EOF


text:
using namespace std;
void DisplayRules();
void GetPlayerNumbers(int*);
void GetWinningNumbers(int*);
int FindWinningCombo(int*,int*);
bool NumberMatches(int, int*);
bool NumberMatches2(int, int*);
int DisplayPrize(int);
int main()
{char userinput1;
int total=0,prize=0;
const int COLNUM=6;
const int cost=2;
cout<<"Welcome to the Powerball Lottery Simulator!\nPress t for the tutorials or s to start the program"<<endl;
cin>>userinput1;
while (userinput1 == 't'||userinput1 =='T')
	{DisplayRules();
	cout<<"Do you want to start playing?If so , please enter s"<<endl;
	cin>>userinput1;
	}
while (userinput1=='s'||userinput1=='S')
	{int playerNumber[COLNUM]={0,0,0,0,0,0};
	int *playerNumberPointer;
	playerNumberPointer= &playerNumber[0];
	int winningNumber[COLNUM]={0,0,0,0,0,0};
	int *winningNumberPointer;
	winningNumberPointer=&winningNumber[0];
	GetPlayerNumbers(playerNumberPointer);
	srand(time(NULL));
	GetWinningNumbers(winningNumberPointer);
	prize=DisplayPrize(FindWinningCombo(playerNumberPointer,winningNumberPointer));
	total= total+prize-cost;
	cout<<"This is your current winning: $"<<total<<endl;
	cout<<"Do you want to play again?Press S to keep playing or Q to quit the program!"<<endl;
	cin>>userinput1;
	}
return 0;
}
void DisplayRules()
	{cout<<"Powerball is a combined large jackpot game and a cash game. Every Wednesday and Saturday night at 10:59 p.m. Eastern Time, we draw five white balls out of a    drum with 59 balls and one red ball out of a drum with 35 red balls. Draw sales cut off at least 59 minutes before the draw. Check for local cut-off time.\n" <<endl;
	cout<<"Players win by matching one of the 9 Ways to Win. The jackpot (won by matching  all five white balls in any order and the red Powerball) is either an annuitized prize paid out over 29 years (30 payments) or a lump sum payment. Each ticket  costs $2. If the winner chooses the annuity, the annual payment will be         increased each year by the percentage set out in the Powerball game rules.\n"<<endl;
	cout<<"The second prize (won by matching five white balls in any order) is $1,000,000  paid in cash and any time you match the red Powerball, you win. The overall odds of winning a prize in the game are approximately 1 in 32.\n"<<endl;
	return;
	}
void GetPlayerNumbers(int *playerNumberPointer)
	{for (int i=0;i<=4;i++)
		{cout<<"Please enter your ticket number "<<i+1<<" : ";
		cin>> *(playerNumberPointer + i);
		if(*(playerNumberPointer + i)>59||*(playerNumberPointer + i)<1)
			{cout<<"Please enter only numbers in the range of 1 to 59"<<endl;
			i--;
			continue;
			}
		if (NumberMatches(*(playerNumberPointer+0),playerNumberPointer))
			{cout<<"This is a dupplicate of your first number."<<endl;
			 cout<<"Please enter another number for ticket number "<<i+1<<endl;
			i--;
			continue;
			}
		if (NumberMatches(*(playerNumberPointer+1),playerNumberPointer))
			{cout<<"This is a dupplicate of your second number."<<endl;
			cout<<"Please enter another number for ticket number "<<i+1<<endl;
			i--;
			continue;
			}
		 if (NumberMatches(*(playerNumberPointer+2),playerNumberPointer))
			{cout<<"This is a dupplicate of your third number."<<endl;
			cout<<"Please enter another number for ticket number "<<i+1<<endl;
			i--;
			continue;
			}
		 if (NumberMatches(*(playerNumberPointer+3),playerNumberPointer))
			{cout<<"This is a dupplicate of your fourth number."<<endl;
			cout<<"Please enter another number for ticket number "<<i+1<<endl;
			i--;
			continue;
			}
		}
	for (int i=5;i<6;i++)
		{cout<<"Please enter your ticket number "<<i+1<<" : ";
		cin>> *(playerNumberPointer + i);
		if (*(playerNumberPointer + i)>35||*(playerNumberPointer + i)<1)
			{cout<<"Please enter only numbers in the range from 1 to 35"<<endl;
			i--;
			continue;
			}
		}
	for (int i=0;i<6;i++)
		{cout<<"Your ticket number "<<i+1<<" is "<<*(playerNumberPointer + i)<<endl;
		}
	}
void GetWinningNumbers(int *winningNumberPointer)
	{for (int i=0;i<=4;i++)
		{*(winningNumberPointer + i)=((rand()%59)+1);

		if (NumberMatches(*(winningNumberPointer+0),winningNumberPointer))
			{i--;
			continue;
			}
		if (NumberMatches(*(winningNumberPointer+1),winningNumberPointer))
			{i--;
			continue;
			}
		if (NumberMatches(*(winningNumberPointer+2),winningNumberPointer))
			{i--;
			continue;
			}
		if (NumberMatches(*(winningNumberPointer+3),winningNumberPointer))
			{i--;
			continue;
			}
		if (NumberMatches(*(winningNumberPointer+4),winningNumberPointer))
			{i--;
			continue;
			}
		}
	if (*(winningNumberPointer+4)>0)
		{cout<<"First winning number is "<<*(winningNumberPointer)<<endl;
		cout<<"Second winning number is "<<*(winningNumberPointer+1)<<endl;
		cout<<"Third winning number is "<<*(winningNumberPointer+2)<<endl;
		cout<<"Fourth winning number is "<<*(winningNumberPointer+3)<<endl;
		cout<<"Fifth winning number is "<<*(winningNumberPointer+4)<<endl;}
	for ( int i=5; i<6;i++)
		{*(winningNumberPointer + i)=((rand()%35)+1);
		cout<<"Sixth winning number is "<<*(winningNumberPointer + i)<<endl;
		}
	}
int FindWinningCombo(int *playerNumberPointer,int *winningNumberPointer)
{int prizeNumber;
int counter1=0;
		if (NumberMatches2(*(playerNumberPointer+0),winningNumberPointer))
		{counter1++;
		}
		if (NumberMatches2(*(playerNumberPointer+1),winningNumberPointer))
		{counter1++;
		}
		if (NumberMatches2(*(playerNumberPointer+2),winningNumberPointer))
		{counter1++;
		}
		if (NumberMatches2(*(playerNumberPointer+3),winningNumberPointer))
		{counter1++;
		}
		if (NumberMatches2(*(playerNumberPointer+4),winningNumberPointer))
		{counter1++;
		}
		if (*(playerNumberPointer+5)==*(winningNumberPointer+5)&&counter1==5)
		{prizeNumber=9;
		return prizeNumber;
		}
		if (counter1==5)
		{prizeNumber=8;
		return prizeNumber;
		}
		if (*(playerNumberPointer+5)==*(winningNumberPointer+5)&&counter1==4)
		{prizeNumber=7;
		return prizeNumber;
		}
		if (counter1==4)
		{prizeNumber=6;
		return prizeNumber;
		}
		if (*(playerNumberPointer+5)==*(winningNumberPointer+5)&&counter1==3)
		{prizeNumber=5;
		return prizeNumber;
		}
		if (counter1==3)
		{prizeNumber=4;
		return prizeNumber;
		}
		if (*(playerNumberPointer+5)==*(winningNumberPointer+5)&&counter1==2)
		{prizeNumber=3;
		return prizeNumber;
		}
		if (*(playerNumberPointer+5)==*(winningNumberPointer+5)&&counter1==1)
		{prizeNumber=2;
		return prizeNumber;
		}
		if (*(playerNumberPointer+5)==*(winningNumberPointer+5))
		{prizeNumber=1;
		return prizeNumber;
		}
		else
		prizeNumber=0;
		return prizeNumber;
}
bool NumberMatches(int playerNumber, int *playerNumberPointer)
{int counter=0;
	if (*(playerNumberPointer)==playerNumber&& playerNumber!=0)
		{counter++;
			if (counter ==2)
				{return true;
				}
		}
	if (*(playerNumberPointer+1)==playerNumber&& playerNumber!=0)
		{counter++;
			if (counter ==2)
				{return true;
				}
			}
	if (*(playerNumberPointer+2)==playerNumber&& playerNumber!=0)
		{counter++;
			if (counter ==2)
				{return true;
				}
		}
	if (*(playerNumberPointer+3)==playerNumber&& playerNumber!=0)
		{counter++;
			if (counter ==2)
				{return true;
				}
		}
	if (*(playerNumberPointer+4)==playerNumber&& playerNumber!=0)
		{counter++;
			if (counter ==2)
				{return true;
				}
		}
	if (*(playerNumberPointer+5)==playerNumber&& playerNumber!=0)
		{counter++;
			if (counter ==2)
				{return true;
				}
		}
	else
		return false;
}
bool NumberMatches2(int playerNumber, int *playerNumberPointer)
{	if (*(playerNumberPointer)==playerNumber)
		{return true;
		}
	if (*(playerNumberPointer+1)==playerNumber)
		{return true;
		}
	if (*(playerNumberPointer+2)==playerNumber)
		{return true;
		}
	if (*(playerNumberPointer+3)==playerNumber)
		{return true;
		}
	if (*(playerNumberPointer+4)==playerNumber)
		{return true;
		}
	else
		return false;
}
int DisplayPrize(int x)
{int prize;
switch (x)
	{case 9:
		prize= 80000000;
		cout<<"Congratulations!You won the jackpot!"<<endl;
		cout<<"The odd of winning this prize is 1 in 175,223,510.00"<<endl;
		return prize;
	break;
 	case 8:
 		prize=1000000;
		cout<<"Congratulations!You won $1,000,000!"<<endl;
		cout<<"The odd of winning this prize is 1 in 5,153,632.65"<<endl;
		return prize;
	break;
	case 7:
		prize=10000;
		cout<<"Congratulations!You won $10,000!"<<endl;
		cout<<"The odd of winning this prize is 1 in 648,975.96"<<endl;
		return prize;
	break;
		case 6:
		prize=100;
		cout<<"Congratulations!You won $100!"<<endl;
		cout<<"The odd of winning this prize is 1 in 19,087.53"<<endl;
		return prize;
	break;
	case 5:
		prize=100;
		cout<<"Congratulations!You won $100!"<<endl;
		cout<<"The odd of winning this prize is 1 in 12,087.53"<<endl;
		return prize;
	break;
	case 4:
		prize=7;
		cout<<"Congratulations!You won $7!"<<endl;
		cout<<"The odd of winning this prize is 1 in 360.14"<<endl;
		return prize;
	break;
	case 3:
		prize=7;
		cout<<"Congratulations!You won $7!"<<endl;
		cout<<"The odd of winning this prize is 1 in 706.43"<<endl;
		return prize;
	break;
	case 2:
		prize=4;
		cout<<"Congratulations!You won $4!"<<endl;
		cout<<"The odd of winning this prize is 1 in 110.81"<<endl;
		return prize;
		break;
	case 1:
		prize=4;
		cout<<"Congratulations!You won $4!"<<endl;
		cout<<"The odd of winning this prize is 1 in 55.41"<<endl;
		return prize;
	break;
	case 0:
		prize=0;
		cout<<"Thank you for playing! Good luck next time!"	<<endl;
		return prize;
		break;
	}
}


text:
<?php
	echo file_get_contents('data.json');
?>


text:
package com.dayuan.mapper;

import java.util.List;

public interface BusInsuranceGuaranteeMapper<T> extends BaseMapper<T> {

	/**
	 * 保存BusInsuranceGuarantee
	 * @return 影响记录数
	 * */
	public int addT(T t);

	/**
	 * 更新BusInsuranceGuarantee
	 * @return 影响记录数
	 * */
	public int updateT(T t);

	/**
	 *根据bid查询BusInsuranceGuarantee
	 *@return list
	 * */
	public List<T> queryBybid(Object id);

	/**
	 * 根据bid删除BusInsuranceGuarantee
	 * @return int
	 * */
	public int deleteBybid(Object id);

}


text:
@implementation UIDetailVC
- (IBAction)changeMode:(id)sender {
    if (self.splitViewController.displayMode == 3) {
        [self.splitViewController setPreferredDisplayMode:UISplitViewControllerDisplayModeAutomatic];
    }else{
        [self.splitViewController setPreferredDisplayMode:self.splitViewController.displayMode +1];
    }

}
- (IBAction)fullView:(id)sender {
    JRSplitVC *JRSplit =(JRSplitVC*) self.splitViewController;
    if (!self.navigationItem.leftBarButtonItem) {
        [JRSplit insertDisplayModeButtonAnimated:YES];
    }else{
        [JRSplit extractDisplayModeButtonAnimated:YES];
    }

}

@end


text:
==========================
Scrapyrt (Scrapy realtime)
==========================

.. image:: https://travis-ci.org/scrapinghub/scrapyrt.svg?branch=master
    :target: https://travis-ci.org/scrapinghub/scrapyrt

HTTP server which provides API for scheduling Scrapy spiders and
making requests with spiders.

Allows you to easily add HTTP API to your existing Scrapy project. All Scrapy project
components (e.g. middleware, pipelines, extensions) are supported out of the box. You
simply run Scrapyrt in Scrapy project directory and it starts HTTP server allowing you
to schedule your spiders and get spider output in JSON format.

Documentation
=============

Documentation is available here: http://scrapyrt.readthedocs.org/en/latest/index.html

Support
=======

Open source support is provided here in Github. Please `create a question
issue`_ (ie. issue with "question" label).

Commercial support is also available by `Scrapinghub`_.

.. _create a question issue: https://github.com/scrapinghub/splash/issues/new?labels=question
.. _Scrapinghub: http://scrapinghub.com


text:
package org.apereo.cas.support.saml.idp.metadata.jpa;

import org.apereo.cas.configuration.model.support.saml.idp.metadata.JpaSamlMetadataProperties;
import org.apereo.cas.support.saml.idp.metadata.jpa.generic.JpaSamlIdPMetadataDocument;
import org.apereo.cas.support.saml.idp.metadata.jpa.mysql.MySQLSamlIdPMetadataDocument;
import org.apereo.cas.support.saml.idp.metadata.jpa.oracle.OracleSamlIdPMetadataDocument;
import org.apereo.cas.support.saml.idp.metadata.jpa.postgres.PostgresSamlIdPMetadataDocument;
import org.apereo.cas.support.saml.services.idp.metadata.SamlIdPMetadataDocument;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;

/**
 * This is {@link JpaSamlIdPMetadataDocumentFactory}.
 *
 * @author Misagh Moayyed
 * @since 6.2.0
 */
@RequiredArgsConstructor
@Getter
public class JpaSamlIdPMetadataDocumentFactory {
    private final JpaSamlMetadataProperties properties;

    /**
     * New instance of saml metadata document.
     *
     * @return the saml metadata document
     */
    @SneakyThrows
    public SamlIdPMetadataDocument newInstance() {
        return getType().getDeclaredConstructor().newInstance();
    }

    private boolean isOracle() {
        return properties.getDialect().contains("Oracle");
    }

    private boolean isMySql() {
        return properties.getDialect().contains("MySQL");
    }

    private boolean isPostgres() {
        return properties.getUrl().contains("postgresql");
    }

    /**
     * Gets type.
     *
     * @return the type
     */
    public Class<? extends SamlIdPMetadataDocument> getType() {
        if (isOracle()) {
            return OracleSamlIdPMetadataDocument.class;
        }
        if (isMySql()) {
            return MySQLSamlIdPMetadataDocument.class;
        }
        if (isPostgres()) {
            return PostgresSamlIdPMetadataDocument.class;
        }
        return JpaSamlIdPMetadataDocument.class;
    }
}


text:
package org.innovateuk.ifs.project.resource;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.innovateuk.ifs.address.resource.AddressResource;
import org.innovateuk.ifs.project.document.resource.ProjectDocumentResource;

import javax.validation.constraints.Digits;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ProjectResource {
    private static final int MAX_DURATION_IN_MONTHS_DIGITS = 2;

    private Long id;
    private long application;
    private long competition;
    private String competitionName;
    private LocalDate targetStartDate;
    private AddressResource address;
    private String name;
    private ZonedDateTime documentsSubmittedDate;
    private ZonedDateTime offerSubmittedDate;
    private List<Long> projectUsers;
    private Long projectMonitoringOfficer;
    private Long monitoringOfficerUser;
    private Long financeReviewer;
    private Long signedGrantOfferLetter;
    private Long grantOfferLetter;
    private Long additionalContractFile;
    private String grantOfferLetterRejectionReason;
    private ApprovalType otherDocumentsApproved;
    private ZonedDateTime spendProfileSubmittedDate;
    private ZonedDateTime processLastModifiedDate;
    private ProjectState projectState;
    private boolean collaborativeProject;
    private List<ProjectDocumentResource> projectDocuments = new ArrayList<>();
    private boolean spendProfileGenerated;
    private boolean useDocusignForGrantOfferLetter;

    @Digits(integer = MAX_DURATION_IN_MONTHS_DIGITS, fraction = 0, message = "{validation.application.details.duration.in.months.max.digits}")
    private Long durationInMonths;

    @JsonIgnore
    public boolean isOfferSubmitted() {
        return offerSubmittedDate != null;
    }

    @JsonIgnore
    public boolean isWithdrawn() {
        return projectState.equals(ProjectState.WITHDRAWN);
    }

    @JsonIgnore
    public boolean isCompleted() {
        return projectState.isComplete();
    }

    public Long getId() {
        return id;
    }

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

    public LocalDate getTargetStartDate() {
        return targetStartDate;
    }

    public void setTargetStartDate(LocalDate targetStartDate) {
        this.targetStartDate = targetStartDate;
    }

    public AddressResource getAddress() {
        return address;
    }

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

    public Long getDurationInMonths() {
        return durationInMonths;
    }

    public void setDurationInMonths(Long durationInMonths) {
        this.durationInMonths = durationInMonths;
    }

    public String getName() {
        return name;
    }

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

    public List<Long> getProjectUsers() {
        return projectUsers;
    }

    public void setProjectUsers(List<Long> projectUsers) {
        this.projectUsers = projectUsers;
    }

    public long getApplication() {
        return application;
    }

    public void setApplication(long application) {
        this.application = application;
    }

    public long getCompetition() {
        return competition;
    }

    public void setCompetition(long competition) {
        this.competition = competition;
    }

    public String getCompetitionName() {
        return competitionName;
    }

    public void setCompetitionName(String competitionName) {
        this.competitionName = competitionName;
    }

    public ZonedDateTime getDocumentsSubmittedDate() {
        return documentsSubmittedDate;
    }

    public void setDocumentsSubmittedDate(ZonedDateTime documentsSubmittedDate) {
        this.documentsSubmittedDate = documentsSubmittedDate;
    }

    public ZonedDateTime getOfferSubmittedDate() {
        return offerSubmittedDate;
    }

    public void setOfferSubmittedDate(ZonedDateTime offerSubmittedDate) {
        this.offerSubmittedDate = offerSubmittedDate;
    }

    public Long getSignedGrantOfferLetter() {
        return signedGrantOfferLetter;
    }

    public void setSignedGrantOfferLetter(Long signedGrantOfferLetter) {
        this.signedGrantOfferLetter = signedGrantOfferLetter;
    }

    public Long getAdditionalContractFile() {
        return additionalContractFile;
    }

    public void setAdditionalContractFile(Long additionalContractFile) {
        this.additionalContractFile = additionalContractFile;
    }

    public Long getGrantOfferLetter() {
        return grantOfferLetter;
    }

    public void setGrantOfferLetter(Long grantOfferLetter) {
        this.grantOfferLetter = grantOfferLetter;
    }

    public String getGrantOfferLetterRejectionReason() {
        return grantOfferLetterRejectionReason;
    }

    public void setGrantOfferLetterRejectionReason(String grantOfferLetterRejectionReason) {
        this.grantOfferLetterRejectionReason = grantOfferLetterRejectionReason;
    }

    public ApprovalType getOtherDocumentsApproved() {
        return otherDocumentsApproved;
    }

    public void setOtherDocumentsApproved(ApprovalType otherDocumentsApproved) {
        this.otherDocumentsApproved = otherDocumentsApproved;
    }

    public ZonedDateTime getSpendProfileSubmittedDate() {
        return spendProfileSubmittedDate;
    }

    public void setSpendProfileSubmittedDate(ZonedDateTime spendProfileSubmittedDate) {
        this.spendProfileSubmittedDate = spendProfileSubmittedDate;
    }

    public ProjectState getProjectState() {
        return projectState;
    }

    public void setProjectState(ProjectState projectState) {
        this.projectState = projectState;
    }

    public List<ProjectDocumentResource> getProjectDocuments() {
        return projectDocuments;
    }

    public void setProjectDocuments(List<ProjectDocumentResource> projectDocuments) {
        this.projectDocuments = projectDocuments;
    }

    public List<ProjectDocumentResource> getActiveProjectDocuments() {
        return projectDocuments.stream().filter(document -> document.getCompetitionDocument().isEnabled()).collect(Collectors.toList());
    }

    public Long getProjectMonitoringOfficer() {
        return projectMonitoringOfficer;
    }

    public void setProjectMonitoringOfficer(Long projectMonitoringOfficer) {
        this.projectMonitoringOfficer = projectMonitoringOfficer;
    }

    public Long getMonitoringOfficerUser() {
        return monitoringOfficerUser;
    }

    public void setMonitoringOfficerUser(Long monitoringOfficerUser) {
        this.monitoringOfficerUser = monitoringOfficerUser;
    }

    public Long getFinanceReviewer() {
        return financeReviewer;
    }

    public void setFinanceReviewer(Long financeReviewer) {
        this.financeReviewer = financeReviewer;
    }

    public ZonedDateTime getProcessLastModifiedDate() {
        return processLastModifiedDate;
    }

    public void setProcessLastModifiedDate(ZonedDateTime processLastModifiedDate) {
        this.processLastModifiedDate = processLastModifiedDate;
    }

    public boolean isSpendProfileGenerated() {
        return spendProfileGenerated;
    }

    public void setSpendProfileGenerated(boolean spendProfileGenerated) {
        this.spendProfileGenerated = spendProfileGenerated;
    }

    public boolean isCollaborativeProject() {
        return collaborativeProject;
    }

    public void setCollaborativeProject(boolean collaborativeProject) {
        this.collaborativeProject = collaborativeProject;
    }

    public boolean isUseDocusignForGrantOfferLetter() {
        return useDocusignForGrantOfferLetter;
    }

    public void setUseDocusignForGrantOfferLetter(boolean useDocusignForGrantOfferLetter) {
        this.useDocusignForGrantOfferLetter = useDocusignForGrantOfferLetter;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        ProjectResource that = (ProjectResource) o;

        return new EqualsBuilder()
                .append(application, that.application)
                .append(competition, that.competition)
                .append(id, that.id)
                .append(targetStartDate, that.targetStartDate)
                .append(address, that.address)
                .append(name, that.name)
                .append(documentsSubmittedDate, that.documentsSubmittedDate)
                .append(offerSubmittedDate, that.offerSubmittedDate)
                .append(projectUsers, that.projectUsers)
                .append(projectMonitoringOfficer, that.projectMonitoringOfficer)
                .append(monitoringOfficerUser, that.monitoringOfficerUser)
                .append(financeReviewer, that.financeReviewer)
                .append(signedGrantOfferLetter, that.signedGrantOfferLetter)
                .append(grantOfferLetter, that.grantOfferLetter)
                .append(additionalContractFile, that.additionalContractFile)
                .append(grantOfferLetterRejectionReason, that.grantOfferLetterRejectionReason)
                .append(otherDocumentsApproved, that.otherDocumentsApproved)
                .append(spendProfileSubmittedDate, that.spendProfileSubmittedDate)
                .append(projectState, that.projectState)
                .append(projectDocuments, that.projectDocuments)
                .append(durationInMonths, that.durationInMonths)
                .append(processLastModifiedDate, that.processLastModifiedDate)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(id)
                .append(application)
                .append(competition)
                .append(targetStartDate)
                .append(address)
                .append(name)
                .append(documentsSubmittedDate)
                .append(offerSubmittedDate)
                .append(projectUsers)
                .append(projectMonitoringOfficer)
                .append(monitoringOfficerUser)
                .append(financeReviewer)
                .append(signedGrantOfferLetter)
                .append(grantOfferLetter)
                .append(additionalContractFile)
                .append(grantOfferLetterRejectionReason)
                .append(otherDocumentsApproved)
                .append(spendProfileSubmittedDate)
                .append(projectState)
                .append(projectDocuments)
                .append(durationInMonths)
                .append(processLastModifiedDate)
                .toHashCode();
    }
}


text:
<p id="frame<?PHP echo $object; ?>Bar" class="pathBar">
<?PHP
for ($i=0; $i<sizeof($categoryPath); $i++) {
	if ($i > 0) echo " » ";
	echo '' . $categoryPath[$i]['name'] . "\n";
	if ($i == sizeof($categoryPath)-1) echo '' . $categoryPath[$i]['id'] . "\n";
}
?>

Subcategories:

	<?PHP
	if ($parentId) echo '
Parent category
';
	for ($i=0; $i<sizeof($subcategories); $i++) {
		echo '
' . $subcategories[$i]['name'] . '('
			. $subcategories[$i]['amount'] . ')
';
	}
	?>


text:
package com.thingtrack.konekti.service.api;

import java.util.List;

import com.thingtrack.konekti.domain.Location;
import com.thingtrack.konekti.domain.Organization;

/**
 * @author Thingtrack S.L.
 *
 */
public interface LocationService {
	public List<Location> getAll() throws Exception;
	public Location get( Integer locationId ) throws Exception;
	public Location getByName( String name ) throws Exception;
	public Location save(Location location) throws Exception;
	public void delete(Location location) throws Exception;
	public Location createEntity(Organization organization) throws Exception;
	public List<Location> getAllByOrganization(Organization organization) throws Exception;
}


text:
function ImageUploadMarkdown (files) {
  var that = this

  this.init = function () {
    this.$textarea = $('.js-markdown-image-upload')

    this.addUploadPlaceholders()
    for (var i = 0; i < files.length; i++) {
      this.handleFileUpload(files[i])
    }
  }

  this.addUploadPlaceholders = function () {
    var placeholders = []
    for (var i = 0; i < files.length; i++) {
      var fileName = files[i].name
      placeholders.push(this.placeholderValue(fileName))
    }

    var selectionStart = this.$textarea[0].selectionStart
    var uploadsPlaceholder = placeholders.join('\r\n')
    this.$textarea.val(
      [this.$textarea.val().slice(0, selectionStart), uploadsPlaceholder, this.$textarea.val().slice(selectionStart)].join('')
    )
  }

  this.replaceImageMarkdownPlaceholder = function (newValue, fileName) {
    var oldPlaceholder = this.placeholderValue(fileName)
    this.$textarea.val(
      this.$textarea.val().replace(oldPlaceholder, newValue)
    )
  }

  this.placeholderValue = function (fileName) {
    return '![Uploading ' + fileName + '...]()'
  }

  this.handleFileUpload = function (file) {
    var formData = new FormData()
    formData.append('format', 'js')
    formData.append('file', file)

    formData.append('authenticity_token', $('meta[name="csrf-token"]').attr('content'))

    var request = new XMLHttpRequest()
    request.open('POST', '/uploads')

    request.onloadend = (function (fileName) {
      return function (e) {
        if (e.currentTarget.status == 201) { // eslint-disable-line eqeqeq
          var filePath = e.currentTarget.response
          that.replaceImageMarkdownPlaceholder('![' + fileName + '](' + filePath + ')', fileName)
        } else {
          that.replaceImageMarkdownPlaceholder('', fileName)
          window.alert('File upload failure\n\n' + e.currentTarget.response)
        }
        that.$textarea.keyup()
      }
    }(file.name))

    request.send(formData)
  }

  return this
}

$(document).on('click', '.js-markdown-file-input-trigger', function () {
  $('.js-markdown-file-input').click()
})

$(document).on('change', '.js-markdown-file-input', function (e) {
  ImageUploadMarkdown(e.target.files).init()
})

$(document).on('drop', '.js-markdown-image-upload', function (e) {
  e.preventDefault()
  ImageUploadMarkdown(e.originalEvent.dataTransfer.files).init()
})


text:
package metadslx.core;

class MetaNullExpressionImpl extends metadslx.core.ModelObject implements metadslx.core.MetaNullExpression {
    static {
        metadslx.core.MetaDescriptor.staticInit();
    }

	@Override
    public metadslx.core.MetaModel mMetaModel() {
        return metadslx.core.MetaInstance.Meta;
    }

	@Override
    public metadslx.core.MetaClass mMetaClass() {
        return metadslx.core.MetaInstance.MetaNullExpression;
    }

    public MetaNullExpressionImpl() {
        this.mLazySet(metadslx.core.MetaDescriptor.MetaExpression.NoTypeErrorProperty, metadslx.core.Lazy.create(() -> ModelCompilerContext.current().getTypeProvider().typeCheck((ModelObject)((MetaExpression)this)), true));
        this.mLazySet(metadslx.core.MetaDescriptor.MetaTypedElement.TypeProperty, metadslx.core.Lazy.create(() -> 	MetaInstance.Any	, true));
        metadslx.core.MetaImplementationProvider.implementation().MetaNullExpression(this);
        if (!this.mIsSet(metadslx.core.MetaDescriptor.MetaExpression.NoTypeErrorProperty)) throw new ModelException("Readonly property Meta.MetaExpression.NoTypeErrorProperty was not set in MetaNullExpression_MetaNullExpression().");
        this.mMakeDefault();
    }

    public boolean getNoTypeError() {
        Object result = this.mGet(metadslx.core.MetaDescriptor.MetaExpression.NoTypeErrorProperty);
        if (result != null) return (boolean)result;
        else return (boolean)false;
    }

    public metadslx.core.MetaType getExpectedType() {
        Object result = this.mGet(metadslx.core.MetaDescriptor.MetaExpression.ExpectedTypeProperty);
        if (result != null) return (metadslx.core.MetaType)result;
        else return (metadslx.core.MetaType)null;
    }

    public metadslx.core.MetaType getType() {
        Object result = this.mGet(metadslx.core.MetaDescriptor.MetaTypedElement.TypeProperty);
        if (result != null) return (metadslx.core.MetaType)result;
        else return (metadslx.core.MetaType)null;
    }

    public void setType(metadslx.core.MetaType value) {
        this.mSet(metadslx.core.MetaDescriptor.MetaTypedElement.TypeProperty, value);
    }
}


text:
/**
 * This is a helper library for synchronously writing logs to any transport.
 */

import {Logging} from '.';
import {Entry, LABELS_KEY, LogEntry, StructuredJson} from './entry';
import {Writable} from 'stream';
import {populateInstrumentationInfo} from './utils/instrumentation';
import {
  LogSeverityFunctions,
  assignSeverityToEntries,
  snakecaseKeys,
  formatLogName,
  WriteOptions,
} from './utils/log-common';

export interface LogSyncOptions {
  // The flag indicating if "message" field should be used to store structured,
  // non-text data inside jsonPayload field. By default this value is true
  useMessageField?: boolean;
}

/**
 * A logSync is a named collection of entries in structured log format. In Cloud
 * Logging, structured logs refer to log entries that use the jsonPayload field
 * to add structure to their payloads. In most GCP environments, like GKE and
 * Cloud Functions, structured logs written to process.stdout are automatically
 * picked up and formatted by logging agents.
 *
 * Recommended for Serverless environment logging, especially where async log
 * calls made by the `Log` class can be dropped by the CPU.
 *
 * See {@link https://cloud.google.com/logging/docs/structured-logging|Structured Logging}
 *
 * @class
 *
 * @param {Logging} logging {@link Logging} instance.
 * @param {string} name Name of the logSync.
 * @param {Writable} [transport] transport A custom writable transport stream.
 *     Default: process.stdout.
 *
 * @example
 * ```
 * const {Logging} = require('@google-cloud/logging');
 * const logging = new Logging();
 * const log = logging.logSync('mylog');
 * ```
 */
class LogSync implements LogSeverityFunctions {
  formattedName_: string;
  logging: Logging;
  name: string;
  transport: Writable;
  useMessageField_: boolean;

  // not projectId, formattedname is expected
  constructor(
    logging: Logging,
    name: string,
    transport?: Writable,
    options?: LogSyncOptions
  ) {
    options = options || {};
    this.formattedName_ = formatLogName(logging.projectId, name);
    this.logging = logging;
    /**
     * @name Log#name
     * @type {string}
     */
    this.name = this.formattedName_.split('/').pop()!;
    // Default to writing to stdout
    this.transport = transport || process.stdout;
    this.useMessageField_ = options.useMessageField ?? true;
  }

  /**
   * Write a log entry with a severity of "ALERT".
   *
   * This is a simple wrapper around {@link LogSync#write}. All arguments are
   * the same as documented there.
   *
   * @param {Entry|Entry[]} entry A log entry, or array of entries, to write.
   * @param {?WriteOptions} [options] Write options
   * @example
   * ```
   * const {Logging} = require('@google-cloud/logging');
   * const logging = new Logging();
   * const log = logging.logSync('my-log');
   *
   * const entry = log.entry('gce_instance', {
   *   instance: 'my_instance'
   * });
   *
   * log.alert(entry);
   * ```
   */
  alert(entry: Entry | Entry[], options?: WriteOptions) {
    this.write(
      assignSeverityToEntries(entry, 'ALERT'),
      options! as WriteOptions
    );
  }

  /**
   * Write a log entry with a severity of "CRITICAL".
   *
   * This is a simple wrapper around {@link LogSync#write}. All arguments are
   * the same as documented there.
   *
   * @param {Entry|Entry[]} entry A log entry, or array of entries, to write.
   * @param {?WriteOptions} [options] Write options
   * @example
   * ```
   * const {Logging} = require('@google-cloud/logging');
   * const logging = new Logging();
   * const log = logging.logSync('my-log');
   *
   * const entry = log.entry('gce_instance', {
   *   instance: 'my_instance'
   * });
   *
   * log.critical(entry);
   * ```
   */
  critical(entry: Entry | Entry[], options?: WriteOptions) {
    this.write(
      assignSeverityToEntries(entry, 'CRITICAL'),
      options! as WriteOptions
    );
  }

  /**
   * Write a log entry with a severity of "DEBUG".
   *
   * This is a simple wrapper around {@link LogSync#write}. All arguments are
   * the same as documented there.
   *
   * @param {Entry|Entry[]} entry A log entry, or array of entries, to write.
   * @param {?WriteOptions} [options] Write options
   * @example
   * ```
   * const {Logging} = require('@google-cloud/logging');
   * const logging = new Logging();
   * const log = logging.logSync('my-log');
   *
   * const entry = log.entry('gce_instance', {
   *   instance: 'my_instance'
   * });
   *
   * log.debug(entry);
   * ```
   */
  debug(entry: Entry | Entry[], options?: WriteOptions) {
    this.write(
      assignSeverityToEntries(entry, 'DEBUG'),
      options! as WriteOptions
    );
  }

  /**
   * Write a log entry with a severity of "EMERGENCY".
   *
   * This is a simple wrapper around {@link LogSync#write}. All arguments are
   * the same as documented there.
   *
   * @param {Entry|Entry[]} entry A log entry, or array of entries, to write.
   * @param {?WriteOptions} [options] Write options
   * @example
   * ```
   * const {Logging} = require('@google-cloud/logging');
   * const logging = new Logging();
   * const log = logging.logSync('my-log');
   *
   * const entry = log.entry('gce_instance', {
   *   instance: 'my_instance'
   * });
   *
   * log.emergency(entry);
   * ```
   */
  emergency(entry: Entry | Entry[], options?: WriteOptions) {
    this.write(
      assignSeverityToEntries(entry, 'EMERGENCY'),
      options as WriteOptions
    );
  }

  // TODO(future): dedupe entry code across LogSync & Log classes.
  /**
   * Create an entry object for this log.
   *
   * Using this method will not itself do any logging.
   *
   * See {@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry|LogEntry JSON representation}
   *
   * @param {?object} metadata See a
   *     [LogEntry
   * Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry).
   * @param {object|string} data The data to use as the value for this log
   *     entry.
   * @returns {Entry}
   *
   * @example
   * ```
   * const {Logging} = require('@google-cloud/logging');
   * const logging = new Logging();
   * const log = logging.logSync('my-log');
   *
   * const metadata = {
   *   resource: {
   *     type: 'gce_instance',
   *     labels: {
   *       zone: 'global',
   *       instance_id: '3'
   *     }
   *   }
   * };
   *
   * const entry = log.entry(metadata, {
   *   delegate: 'my_username'
   * });
   * ```
   */
  entry(metadata?: LogEntry): Entry;
  entry(data?: string | {}): Entry;
  entry(metadata?: LogEntry, data?: string | {}): Entry;
  entry(metadataOrData?: LogEntry | string | {}, data?: string | {}) {
    let metadata: LogEntry;
    if (
      !data &&
      metadataOrData !== null &&
      Object.prototype.hasOwnProperty.call(metadataOrData, 'httpRequest')
    ) {
      // If user logs entry(metadata.httpRequest)
      metadata = metadataOrData as LogEntry;
      data = {};
    } else if (!data) {
      // If user logs entry(message)
      data = metadataOrData as string | {};
      metadata = {};
    } else {
      // If user logs entry(metadata, message)
      metadata = metadataOrData as LogEntry;
    }
    return this.logging.entry(metadata, data);
  }

  /**
   * Write a log entry with a severity of "ERROR".
   *
   * This is a simple wrapper around {@link LogSync#write}. All arguments are
   * the same as documented there.
   *
   * @param {Entry|Entry[]} entry A log entry, or array of entries, to write.
   * @param {?WriteOptions} [options] Write options
   * @example
   * ```
   * const {Logging} = require('@google-cloud/logging');
   * const logging = new Logging();
   * const log = logging.logSync('my-log');
   *
   * const entry = log.entry('gce_instance', {
   *   instance: 'my_instance'
   * });
   *
   * log.error(entry);
   * ```
   */
  error(entry: Entry | Entry[], options?: WriteOptions) {
    this.write(
      assignSeverityToEntries(entry, 'ERROR'),
      options! as WriteOptions
    );
  }

  /**
   * Write a log entry with a severity of "INFO".
   *
   * This is a simple wrapper around {@link LogSync#write}. All arguments are
   * the same as documented there.
   *
   * @param {Entry|Entry[]} entry A log entry, or array of entries, to write.
   * @param {?WriteOptions} [options] Write options
   * @example
   * ```
   * const {Logging} = require('@google-cloud/logging');
   * const logging = new Logging();
   * const log = logging.logSync('my-log');
   *
   * const entry = log.entry('gce_instance', {
   *   instance: 'my_instance'
   * });
   *
   * log.info(entry);
   * ```
   */
  info(entry: Entry | Entry[], options?: WriteOptions) {
    this.write(
      assignSeverityToEntries(entry, 'INFO'),
      options! as WriteOptions
    );
  }

  /**
   * Write a log entry with a severity of "NOTICE".
   *
   * This is a simple wrapper around {@link LogSync#write}. All arguments are
   * the same as documented there.
   *
   * @param {Entry|Entry[]} entry A log entry, or array of entries, to write.
   * @param {?WriteOptions} [options] Write options
   * @example
   * ```
   * const {Logging} = require('@google-cloud/logging');
   * const logging = new Logging();
   * const log = logging.logSync('my-log');
   *
   * const entry = log.entry('gce_instance', {
   *   instance: 'my_instance'
   * });
   *
   * log.notice(entry);
   * ```
   */
  notice(entry: Entry | Entry[], options?: WriteOptions) {
    this.write(
      assignSeverityToEntries(entry, 'NOTICE'),
      options! as WriteOptions
    );
  }

  /**
   * Write a log entry with a severity of "WARNING".
   *
   * This is a simple wrapper around {@link LogSync#write}. All arguments are
   * the same as documented there.
   *
   * @param {Entry|Entry[]} entry A log entry, or array of entries, to write.
   * @param {?WriteOptions} [options] Write options
   * @example
   * ```
   * const {Logging} = require('@google-cloud/logging');
   * const logging = new Logging();
   * const log = logging.logSync('my-log');
   *
   * const entry = log.entry('gce_instance', {
   *   instance: 'my_instance'
   * });
   *
   * log.warning(entry);
   * ```
   */
  warning(entry: Entry | Entry[], options?: WriteOptions) {
    this.write(
      assignSeverityToEntries(entry, 'WARNING'),
      options as WriteOptions
    );
  }

  /**
   * Write log entries to a custom transport (default: process.stdout).
   *
   * @param {Entry|Entry[]} entry A log entry, or array of entries, to write.
   * @param {?WriteOptions} [options] Write options
   *
   * @example
   * ```
   * const entry = log.entry('gce_instance', {
   *   instance: 'my_instance'
   * });
   *
   * log.write(entry);
   *
   * //-
   * // You may also pass multiple log entries to write.
   * //-
   * const secondEntry = log.entry('compute.googleapis.com', {
   *   user: 'my_username'
   * });
   *
   * log.write([entry, secondEntry]);
   *
   * //-
   * // To save some steps, you can also pass in plain values as your entries.
   * // Note, however, that you must provide a configuration object to specify
   * // the resource.
   * //-
   * const entries = [
   *   {
   *     user: 'my_username'
   *   },
   *   {
   *     home: process.env.HOME
   *   }
   * ];
   *
   * const options = {
   *   resource: 'compute.googleapis.com'
   * };
   *
   * log.write(entries, options);
   *
   * log.write(entries);
   * });
   * ```
   */
  write(entry: Entry | Entry[], opts?: WriteOptions) {
    const options = opts ? (opts as WriteOptions) : {};
    // We expect projectId and resource to be set before this fn is called...
    let structuredEntries: StructuredJson[];
    this.formattedName_ = formatLogName(this.logging.projectId, this.name);
    try {
      // Make sure to add instrumentation info
      structuredEntries = populateInstrumentationInfo(entry)[0].map(entry => {
        if (!(entry instanceof Entry)) {
          entry = this.entry(entry);
        }
        return entry.toStructuredJSON(
          this.logging.projectId,
          this.useMessageField_
        );
      });
      for (const entry of structuredEntries) {
        entry.logName = this.formattedName_;
        entry.resource =
          snakecaseKeys(options.resource?.labels) ||
          entry.resource ||
          this.logging.detectedResource;
        entry[LABELS_KEY] = options.labels || entry[LABELS_KEY];
        this.transport.write(JSON.stringify(entry) + '\n');
      }
    } catch (err) {
      // Ignore errors (client libraries do not panic).
    }
  }
}

/**
 * Reference to the {@link LogSync} class.
 * @name module:@google-cloud/logging.LogSync
 * @see LogSync
 */
export {LogSync};


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.EditAndContinue.Contracts;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.EditAndContinue
{
    /// <summary>
    /// Facade used to call remote <see cref="IRemoteEditAndContinueService"/> methods.
    /// Encapsulates all RPC logic as well as dispatching to the local service if the remote service is disabled.
    /// THe facade is useful for targeted testing of serialization/deserialization of EnC service calls.
    /// </summary>
    internal readonly partial struct RemoteEditAndContinueServiceProxy
    {
        [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteEditAndContinueService)), Shared]
        internal sealed class CallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteEditAndContinueService.ICallback
        {
            [ImportingConstructor]
            [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
            public CallbackDispatcher()
            {
            }

            public ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(RemoteServiceCallbackId callbackId, DocumentId? documentId, string filePath, CancellationToken cancellationToken)
                => ((ActiveStatementSpanProviderCallback)GetCallback(callbackId)).GetSpansAsync(documentId, filePath, cancellationToken);

            public ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)
                => ((EditSessionCallback)GetCallback(callbackId)).GetActiveStatementsAsync(cancellationToken);

            public ValueTask<ManagedHotReloadAvailability> GetAvailabilityAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken)
                => ((EditSessionCallback)GetCallback(callbackId)).GetAvailabilityAsync(mvid, cancellationToken);

            public ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)
                => ((EditSessionCallback)GetCallback(callbackId)).GetCapabilitiesAsync(cancellationToken);

            public ValueTask PrepareModuleForUpdateAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken)
                => ((EditSessionCallback)GetCallback(callbackId)).PrepareModuleForUpdateAsync(mvid, cancellationToken);
        }

        private sealed class EditSessionCallback
        {
            private readonly IManagedHotReloadService _debuggerService;

            public EditSessionCallback(IManagedHotReloadService debuggerService)
            {
                _debuggerService = debuggerService;
            }

            public async ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken)
            {
                try
                {
                    return await _debuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false);
                }
                catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
                {
                    return ImmutableArray<ManagedActiveStatementDebugInfo>.Empty;
                }
            }

            public async ValueTask<ManagedHotReloadAvailability> GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken)
            {
                try
                {
                    return await _debuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
                {
                    return new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.InternalError, e.Message);
                }
            }

            public async ValueTask PrepareModuleForUpdateAsync(Guid mvid, CancellationToken cancellationToken)
            {
                try
                {
                    await _debuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
                {
                    // nop
                }
            }

            public async ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken)
            {
                try
                {
                    return await _debuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false);
                }
                catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
                {
                    return ImmutableArray<string>.Empty;
                }
            }
        }

        public readonly Workspace Workspace;

        public RemoteEditAndContinueServiceProxy(Workspace workspace)
        {
            Workspace = workspace;
        }

        private IEditAndContinueWorkspaceService GetLocalService()
            => Workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>();

        public async ValueTask<RemoteDebuggingSessionProxy?> StartDebuggingSessionAsync(
            Solution solution,
            IManagedHotReloadService debuggerService,
            ImmutableArray<DocumentId> captureMatchingDocuments,
            bool captureAllMatchingDocuments,
            bool reportDiagnostics,
            CancellationToken cancellationToken)
        {
            var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false);
            if (client == null)
            {
                var sessionId = await GetLocalService().StartDebuggingSessionAsync(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false);
                return new RemoteDebuggingSessionProxy(Workspace, LocalConnection.Instance, sessionId);
            }

            // need to keep the providers alive until the edit session ends:
            var connection = client.CreateConnection<IRemoteEditAndContinueService>(
                callbackTarget: new EditSessionCallback(debuggerService));

            var sessionIdOpt = await connection.TryInvokeAsync(
                solution,
                async (service, solutionInfo, callbackId, cancellationToken) => await service.StartDebuggingSessionAsync(solutionInfo, callbackId, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false),
                cancellationToken).ConfigureAwait(false);

            if (sessionIdOpt.HasValue)
            {
                return new RemoteDebuggingSessionProxy(Workspace, connection, sessionIdOpt.Value);
            }

            connection.Dispose();
            return null;
        }

        public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, Document designTimeDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken)
        {
            var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false);
            if (client == null)
            {
                var diagnostics = await GetLocalService().GetDocumentDiagnosticsAsync(document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false);

                if (designTimeDocument != document)
                {
                    diagnostics = diagnostics.SelectAsArray(diagnostic => RemapLocation(designTimeDocument, DiagnosticData.Create(diagnostic, document.Project)));
                }

                return diagnostics;
            }

            var diagnosticData = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DiagnosticData>>(
                document.Project.Solution,
                (service, solutionInfo, callbackId, cancellationToken) => service.GetDocumentDiagnosticsAsync(solutionInfo, callbackId, document.Id, cancellationToken),
                callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider),
                cancellationToken).ConfigureAwait(false);

            if (!diagnosticData.HasValue)
            {
                return ImmutableArray<Diagnostic>.Empty;
            }

            var project = document.Project;

            using var _ = ArrayBuilder<Diagnostic>.GetInstance(out var result);
            foreach (var data in diagnosticData.Value)
            {
                Debug.Assert(data.DataLocation != null);

                Diagnostic diagnostic;

                // Workaround for solution crawler not supporting mapped locations to make Razor work.
                // We pretend the diagnostic is in the original document, but use the mapped line span.
                // Razor will ignore the column (which will be off because #line directives can't currently map columns) and only use the line number.
                if (designTimeDocument != document)
                {
                    diagnostic = RemapLocation(designTimeDocument, data);
                }
                else
                {
                    diagnostic = await data.ToDiagnosticAsync(document.Project, cancellationToken).ConfigureAwait(false);
                }

                result.Add(diagnostic);
            }

            return result.ToImmutable();
        }

        private static Diagnostic RemapLocation(Document designTimeDocument, DiagnosticData data)
        {
            Debug.Assert(data.DataLocation != null);
            Debug.Assert(designTimeDocument.FilePath != null);

            // If the location in the generated document is in a scope of user-visible #line mapping use the mapped span,
            // otherwise (if it's hidden) display the diagnostic at the start of the file.
            var span = data.DataLocation.IsMapped ? data.DataLocation.GetFileLinePositionSpan().Span : default;
            var location = Location.Create(designTimeDocument.FilePath, textSpan: default, span);

            return data.ToDiagnostic(location, ImmutableArray<Location>.Empty);
        }

        public async ValueTask OnSourceFileUpdatedAsync(Document document, CancellationToken cancellationToken)
        {
            var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false);
            if (client == null)
            {
                GetLocalService().OnSourceFileUpdated(document);
                return;
            }

            await client.TryInvokeAsync<IRemoteEditAndContinueService>(
               document.Project.Solution,
               (service, solutionInfo, cancellationToken) => service.OnSourceFileUpdatedAsync(solutionInfo, document.Id, cancellationToken),
               cancellationToken).ConfigureAwait(false);
        }

        private sealed class LocalConnection : IDisposable
        {
            public static readonly LocalConnection Instance = new();

            public void Dispose()
            {
            }
        }
    }
}


text:
using System;
using Hyena;

namespace FSpot.Query
{
	public class DateRange : IQueryCondition
	{
		public DateTime Start { get; private set; }

		public DateTime End { get; private set; }

		public DateRange (DateTime start, DateTime end)
		{
			Start = start;
			End = end;
		}

		public DateRange (int year, int month)
		{
			Start = new DateTime (year, month, 1);
			End = new DateTime (month < 12 ? year : year + 1, month < 12 ? month + 1 : 1, 1);
		}

		public string SqlClause ()
		{
			return string.Format (" photos.time >= {0} AND photos.time <= {1} ",
					DateTimeUtil.FromDateTime (Start),
					DateTimeUtil.FromDateTime (End));
		}
	}
}


text:
// ReSharper disable InconsistentNaming
// ReSharper disable IdentifierTypo

namespace OpenCvSharp.XPhoto;

/// <summary>
/// various inpainting algorithms
/// </summary>
public enum InpaintTypes
{
    /// <summary>
    /// This algorithm searches for dominant correspondences(transformations) of image patches
    /// and tries to seamlessly fill-in the area to be inpainted using this transformations inpaint
    /// </summary>
    SHIFTMAP = 0,

    /// <summary>
    /// Performs Frequency Selective Reconstruction (FSR).
    /// One of the two quality profiles BEST and FAST can be chosen, depending on the time available for reconstruction.
    /// See @cite GenserPCS2018 and @cite SeilerTIP2015 for details.
    ///
    /// The algorithm may be utilized for the following areas of application:
    /// 1. %Error Concealment (Inpainting).
    /// The sampling mask indicates the missing pixels of the distorted input
    /// image to be reconstructed.
    /// 2. Non-Regular Sampling.
    /// For more information on how to choose a good sampling mask, please review
    /// @cite GroscheICIP2018 and @cite GroscheIST2018.
    ///
    /// 1-channel grayscale or 3-channel BGR image are accepted.
    ///
    /// Conventional accepted ranges:
    /// - 0-255 for CV_8U
    /// - 0-65535 for CV_16U
    /// - 0-1 for CV_32F/CV_64F.
    /// </summary>
    FSR_BEST = 1,

    /// <summary>
    /// See #INPAINT_FSR_BEST
    /// </summary>
    FSR_FAST = 2
}