text:
//
// WinSocket.cpp for Winsocket in
//
// Made by mognetworkhrabi Alexandre
// Login   <alexmog@epitech.net>
//
// Started on  Thu Jun  5 19:54:04 2014 mognetworkhrabi Alexandre
// Last update Tue Nov 25 16:48:25 2014 Moghrabi Alexandre
//

#include "mognetwork/OS.hh"

#ifdef OS_WINDOWS

#include <iostream>
#include "mognetwork/OsSocket.hh"
#include <cstring>

namespace mognetwork
{
  sockaddr_in OsSocket::createAddress(UINT32 address, unsigned short port)
  {
    sockaddr_in addr;
    std::memset(&addr, 0, sizeof(addr));
    addr.sin_addr.s_addr = htonl(address);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    return (addr);
  }

  SocketFD OsSocket::notValid()
  {
    return (INVALID_SOCKET);
  }

  void OsSocket::close(SocketFD socket)
  {
    closesocket(socket);
  }

  Socket::Status OsSocket::getErrorStatus()
  {
    switch (WSAGetLastError())
      {
      case WSAEWOULDBLOCK :  return (Socket::Nok);
      case WSAEALREADY :     return (Socket::Nok);
      case WSAECONNABORTED : return (Socket::Disconnected);
      case WSAECONNRESET :   return (Socket::Disconnected);
      case WSAETIMEDOUT :    return (Socket::Disconnected);
      case WSAENETRESET :    return (Socket::Disconnected);
      case WSAENOTCONN :     return (Socket::Disconnected);
      case WSAEISCONN :      return (Socket::Ok);
      default :              return (Socket::Error);
      }
  }

  // Windows needs an initialisation to use socket
  // So we are going to create a class that does it automaticly.
  // Thanks to the SFML sources for the help.
  struct LibNetInit
  {
	  LibNetInit()
	  {
		  WSADATA init;
		  WSAStartup(MAKEWORD(2, 2), &init);
	  }

	  ~LibNetInit()
	  {
		  WSACleanup();
	  }
  };
  LibNetInit globalLibNetInit;
} // namespace mognetwork
#endif /* OS_WINDOWS */


text:
Rather simple PHP archive utility for backing up directories
----------------------------------------------------------
Simple script that recursively loops through a directory and adds all files to a ZIP archive. A few error catches are included as well.

Requirements
------------------
 - PHP (version 5 or better)
 - SPL (usually bundled in PHP5)
 - ZipArchive (another normal extension in PHP5)

Usage
------------------
Plop the archiver.php in or near the directory you want archived. Modify the three parameters as needed...
 - directory = the directory you want to archive, relative to archiver.php
 - ignore_file_list = any files that you want to ignore
 - archive_name = what you want the archived file named

Possible Future Enhancements
------------------
 - wildcard matching for ignore list (pending need)
 - options of what to do with the archived file (mail, curl, etc)

Changelog
------------------
v1.0 (2013-09-28)
 - initial release

------------------
 - Project at GitHub [jacobemerck/archiver](https://github.com/jacobemerick/archiver)
 - Jacob Emerick [@jpemeric](http://twitter.com/jpemeric) [jacobemerick.com](http://home.jacobemerick.com/)
 - Blog post explaining details [archiving a directory](http://blog.jacobemerick.com/web-development/archiving-a-directory/)

redpajama_set_name: RedPajamaGithub


text:
package com.github.ruediste.rise.sample.db;

import static java.util.stream.Collectors.toList;

import java.util.List;
import java.util.Optional;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import com.github.ruediste.rise.test.PageObject;

public class TodoPO extends PageObject {

    private WebElement addName;

    private WebElement addButton = lazy(byDataTestName(TodoController.class, x -> x.add()));

    @FindBy(css = "[data-test-name=itemList]>div")
    private List<WebElement> todos;

    public TodoPO addTodo(String name) {
        addName.clear();
        addName.sendKeys(name);
        addButton.click();
        return this;
    }

    public Optional<TodoItemPO> getTodo(String name) {
        return getTodos().stream().filter(i -> i.getName().equals(name)).findFirst();
    }

    public List<TodoItemPO> getTodos() {
        return todos.stream().map(e -> pageObject(TodoItemPO.class, e)).collect(toList());
    }
}


text:
/* filecntl.h - Definitions to set file descriptors to close-on-exec. */

/* Copyright (C) 1993 Free Software Foundation, Inc.

   This file is part of GNU Bash, the Bourne Again SHell.

   Bash is free software; you can redistribute it and/or modify it under
   the terms of the GNU General Public License as published by the Free
   Software Foundation; either version 2, or (at your option) any later
   version.

   Bash is distributed in the hope that it will be useful, but WITHOUT ANY
   WARRANTY; without even the implied warranty of MERCHANTABILITY or
   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   for more details.

   You should have received a copy of the GNU General Public License along
   with Bash; see the file COPYING.  If not, write to the Free Software
   Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */

#if !defined (_FILECNTL_H_)
#define _FILECNTL_H_

#include <fcntl.h>

/* Definitions to set file descriptors to close-on-exec, the Posix way. */
#if !defined (FD_CLOEXEC)
#define FD_CLOEXEC     1
#endif

#define FD_NCLOEXEC    0

#define SET_CLOSE_ON_EXEC(fd)  (fcntl ((fd), F_SETFD, FD_CLOEXEC))
#define SET_OPEN_ON_EXEC(fd)   (fcntl ((fd), F_SETFD, FD_NCLOEXEC))

/* How to open a file in non-blocking mode, the Posix.1 way. */
#if !defined (O_NONBLOCK)
#  if defined (O_NDELAY)
#    define O_NONBLOCK O_NDELAY
#  else
#    define O_NONBLOCK 0
#  endif
#endif

#endif /* ! _FILECNTL_H_ */


text:
This directory contains an example application that uses interpol.

## Setup

Ensure the gems are all installed:

```
bundle install
```

## Run the tests

Interpol provides support for generating tests in either Test::Unit or RSpec.
This example app includes both. The endpoint definition contains an example
with a fat-fingered attribute name in order to demonstrate what failures
from generated interpol tests look like.

Run the RSpec tests:

```
$ rake spec

API Examples
  show_contact (v 1.0) has valid data for example 1
  show_contact (v 1.0) has valid data for example 2
  show_contact (v 1.0) has valid data for example 3 (FAILED - 1)

Failures:

  1) API Examples show_contact (v 1.0) has valid data for example 3
     Failure/Error: define_test(description) { example.validate! }
     Interpol::ValidationError:
       Found 2 error(s) when validating against endpoint show_contact (v. 1.0). Errors:
         - The property '#/' did not contain a required property of 'date_of_birth' in schema 393a88cb-bc93-529f-a9da-fe00de85e0d9#
         - The property '#/' contains additional properties ["date_of_brith"] outside of the schema when none are allowed in schema 393a88cb-bc93-529f-a9da-fe00de85e0d9#.

       Data:
       {"first_name"=>"Jack", "last_name"=>"Brown", "date_of_brith"=>"1981-08-03", "gender"=>"male"}
     # /Users/myron/code/interpol/lib/interpol/endpoint.rb:97:in `validate_data!'
     # /Users/myron/code/interpol/lib/interpol/endpoint.rb:129:in `validate!'
     # /Users/myron/code/interpol/lib/interpol/test_helper.rb:22:in `block (2 levels) in define_interpol_example_tests'

Finished in 0.01537 seconds
3 examples, 1 failure
```

Run the Test::Unit tests:

```
$ rake test
Run options:

# Running tests:

..E

Finished tests in 0.014566s, 205.9591 tests/s, 0.0000 assertions/s.

  1) Error:
test_show_contact_v_1_0_has_valid_data_for_example_3(APIExamplesTest):
Interpol::ValidationError: Found 2 error(s) when validating against endpoint show_contact (v. 1.0). Errors:
  - The property '#/' did not contain a required property of 'date_of_birth' in schema 393a88cb-bc93-529f-a9da-fe00de85e0d9#
  - The property '#/' contains additional properties ["date_of_brith"] outside of the schema when none are allowed in schema 393a88cb-bc93-529f-a9da-fe00de85e0d9#.

Data:
{"first_name"=>"Jack", "last_name"=>"Brown", "date_of_brith"=>"1981-08-03", "gender"=>"male"}
    /Users/myron/code/interpol/lib/interpol/endpoint.rb:97:in `validate_data!'
    /Users/myron/code/interpol/lib/interpol/endpoint.rb:129:in `validate!'
    /Users/myron/code/interpol/lib/interpol/test_helper.rb:22:in `block (2 levels) in define_interpol_example_tests'

3 tests, 0 assertions, 0 failures, 1 errors, 0 skips
```

## Run the stub app

`stub_app.config.ru` contains the stub app, generated from the endpoint definition.

```
rake boot_stub_app
```

Let's hit this with curl:

```
$ curl -is localhost:3100/contacts/17

HTTP/1.1 200 OK
X-Frame-Options: sameorigin
X-Xss-Protection: 1; mode=block
Content-Type: application/json;charset=utf-8
Content-Length: 84
Server: WEBrick/1.3.1 (Ruby/1.9.3/2012-02-16)
Date: Thu, 05 Apr 2012 18:07:34 GMT
Connection: Keep-Alive

{"first_name":"John","last_name":"Doe","date_of_birth":"1979-05-23","gender":"male"}
```

## Run the real app with the ResponseSchemaValidator middleware

`app.rb` contains an implementation of the "real app" using sinatra.
Let's start it:

```
rake boot_app
```

In your browser, go to `http://localhost:4567/contacts/good` (which
should render valid JSON) and `http://localhost:4567/contacts/bad`
(which should render a validation error).

## Run the documentation app

`documentation_app.config.ru` contains the documentation app,
generated from the endpoint definition. Let's start it:

```
rake boot_doc_app
```

Then visit `localhost:3200/` in your web browser.


text:
package com.vaadin.tests.server.component.slider;

import org.junit.Test;

import com.vaadin.shared.ui.slider.SliderOrientation;
import com.vaadin.tests.design.DeclarativeTestBase;
import com.vaadin.ui.Slider;

/**
 * Tests declarative support for implementations of {@link Slider}.
 *
 * @since
 * @author Vaadin Ltd
 */
public class SliderDeclarativeTest extends DeclarativeTestBase<Slider> {

    @Test
    public void testDefault() {
        String design = "<vaadin-slider>";

        Slider expected = new Slider();

        testRead(design, expected);
        testWrite(design, expected);
    }

    @Test
    public void testHorizontal() {
        String design = "<vaadin-slider min=10 max=20 resolution=1 value=12.3>";

        Slider expected = new Slider();
        expected.setMin(10.0);
        expected.setMax(20.0);
        expected.setResolution(1);
        expected.setValue(12.3);

        testRead(design, expected);
        testWrite(design, expected);
    }

    @Test
    public void testVertical() {
        String design = "<vaadin-slider vertical>";

        Slider expected = new Slider();
        expected.setOrientation(SliderOrientation.VERTICAL);

        testRead(design, expected);
        testWrite(design, expected);
    }

    @Test
    public void testReadOnlyValue() {
        String design = "<vaadin-slider readonly min=10 max=20 resolution=1 value=12.3>";

        Slider expected = new Slider();
        expected.setMin(10.0);
        expected.setMax(20.0);
        expected.setResolution(1);
        expected.setValue(12.3);
        expected.setReadOnly(true);

        testRead(design, expected);
        testWrite(design, expected);
    }
}


text:
package org.ovirt.engine.ui.uicommonweb.models.hosts;

import org.ovirt.engine.core.common.businessentities.ServerCpu;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.IntegerCompat;
import org.ovirt.engine.core.compat.PropertyChangedEventArgs;
import org.ovirt.engine.core.compat.RefObject;
import org.ovirt.engine.core.compat.StringFormat;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.Model;
import org.ovirt.engine.ui.uicommonweb.models.clusters.ClusterModel;
import org.ovirt.engine.ui.uicommonweb.models.datacenters.DataCenterModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.LocalStorageModel;
import org.ovirt.engine.ui.uicommonweb.validation.IValidation;
import org.ovirt.engine.ui.uicommonweb.validation.RegexValidation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@SuppressWarnings("unused")
public class ConfigureLocalStorageModel extends Model {

    private LocalStorageModel privateStorage;

    public LocalStorageModel getStorage() {
        return privateStorage;
    }

    private void setStorage(LocalStorageModel value) {
        privateStorage = value;
    }

    private DataCenterModel privateDataCenter;

    public DataCenterModel getDataCenter() {
        return privateDataCenter;
    }

    private void setDataCenter(DataCenterModel value) {
        privateDataCenter = value;
    }

    private ClusterModel privateCluster;

    public ClusterModel getCluster() {
        return privateCluster;
    }

    private void setCluster(ClusterModel value) {
        privateCluster = value;
    }

    private EntityModel privateFormattedStorageName;

    public EntityModel getFormattedStorageName() {
        return privateFormattedStorageName;
    }

    private void setFormattedStorageName(EntityModel value) {
        privateFormattedStorageName = value;
    }

    private storage_pool candidateDataCenter;

    public storage_pool getCandidateDataCenter() {
        return candidateDataCenter;
    }

    public void setCandidateDataCenter(storage_pool value) {
        candidateDataCenter = value;
    }

    private VDSGroup candidateCluster;

    public VDSGroup getCandidateCluster() {
        return candidateCluster;
    }

    public void setCandidateCluster(VDSGroup value) {
        candidateCluster = value;
    }

    private String privateCommonName;

    private String getCommonName() {
        return privateCommonName;
    }

    private void setCommonName(String value) {
        privateCommonName = value;
    }

    private boolean isGeneralTabValid;

    public boolean getIsGeneralTabValid() {
        return isGeneralTabValid;
    }

    public void setIsGeneralTabValid(boolean value) {

        if (isGeneralTabValid != value) {
            isGeneralTabValid = value;
            OnPropertyChanged(new PropertyChangedEventArgs("IsGeneralTabValid"));
        }
    }

    private String frontendHash = getHashName() + new Date();

    public ConfigureLocalStorageModel() {

        setStorage(new LocalStorageModel());

        setDataCenter(new DataCenterModel());
        getDataCenter().getVersion().getSelectedItemChangedEvent().addListener(this);

        setCluster(new ClusterModel());
        getCluster().Init(false);

        setFormattedStorageName(new EntityModel());

        // Subscribe to the Frontend events.
        Frontend.getQueryStartedEvent().addListener(this);
        Frontend.getQueryCompleteEvent().addListener(this);
        Frontend.Subscribe(new VdcQueryType[] {
            VdcQueryType.Search,
            VdcQueryType.GetVdsGroupsByStoragePoolId,
            VdcQueryType.GetAllVdsGroups,
            VdcQueryType.GetVdsGroupById,
            VdcQueryType.GetStoragePoolById,
        });

        // Set the storage type to be Local.
        ListModel storageTypeListModel = getDataCenter().getStorageTypeList();

        for (StorageType item : (ArrayList<StorageType>) storageTypeListModel.getItems()) {
            if (item == StorageType.LOCALFS) {
                storageTypeListModel.setSelectedItem(item);
                break;
            }
        }

        setIsGeneralTabValid(true);
    }

    @Override
    public void eventRaised(Event ev, Object sender, EventArgs args) {
        super.eventRaised(ev, sender, args);

        if (ev.equals(ListModel.SelectedItemChangedEventDefinition) && sender == getDataCenter().getVersion()) {
            DataCenterVersion_SelectedItemChanged();
        } else if (ev.equals(Frontend.QueryStartedEventDefinition) && StringHelper.stringsEqual(Frontend.getCurrentContext(), frontendHash)) {
            Frontend_QueryStarted();
        } else if (ev.equals(Frontend.QueryCompleteEventDefinition) && StringHelper.stringsEqual(Frontend.getCurrentContext(), frontendHash)) {
            Frontend_QueryComplete();
        }
    }

    private void DataCenterVersion_SelectedItemChanged() {
        Version version = (Version) getDataCenter().getVersion().getSelectedItem();

        // Keep in sync version for data center and cluster.
        getCluster().getVersion().setSelectedItem(version);
    }

    public boolean Validate() {

        RegexValidation validation = new RegexValidation();
        validation.setExpression("^[A-Za-z0-9_-]+$");
        validation.setMessage("Name can contain only 'A-Z', 'a-z', '0-9', '_' or '-' characters.");
        getFormattedStorageName().ValidateEntity(new IValidation[] {validation});

        if (getFormattedStorageName().getEntity() != null
            && Linq.FirstOrDefault(context.storageList, new Linq.StorageNamePredicate((String) getFormattedStorageName().getEntity())) != null) {

            getFormattedStorageName().setIsValid(false);
            getFormattedStorageName().getInvalidityReasons().add("Name must be unique.");
        }

        boolean isStorageValid = getStorage().Validate() && getFormattedStorageName().getIsValid();
        boolean isDataCenterValid = true;
        if (getCandidateDataCenter() == null) {
            isDataCenterValid = getDataCenter().Validate();
        }
        boolean isClusterValid = true;
        if (getCandidateCluster() == null) {
            isClusterValid = getCluster().Validate(false);
        }

        setIsGeneralTabValid(isStorageValid && isDataCenterValid && isClusterValid);

        return isStorageValid && isDataCenterValid && isClusterValid;
    }

    private void SetDefaultNames8() {

        VDS host = context.host;
        ArrayList<storage_pool> dataCenters = context.dataCenterList;
        ArrayList<VDSGroup> clusters = context.clusterList;

        setCommonName(StringFormat.format("%1$s-Local", host.getvds_name().replace('.', '-')));

        storage_pool candidate = null;

        // Check if current settings suitable for local setup (in case just SD creation failed - re-using the same setup)
        boolean useCurrentSettings = false;
        if (host.getstorage_pool_id() != null) {

            storage_pool tempCandidate = context.hostDataCenter;
            if (IsLocalDataCenterEmpty(tempCandidate)) {

                candidate = tempCandidate;
                useCurrentSettings = true;
            } else {

                if (tempCandidate != null && tempCandidate.getstorage_pool_type() == StorageType.LOCALFS) {
                    setMessage("Note: Local Storage is already configured for this Host. The Host belongs to " + host.getstorage_pool_name() + " with local Storage Domain. If OK is clicked - this Host will be moved to a new Data Center, and a new Local Storage Domain will be created. Hit Cancel to abort the operation.");
                }
            }
        }

        // Check if there is other DC suitable for re-use
        if (candidate == null) {
            for (storage_pool dataCenter : dataCenters) {

                // Need to check if the new DC is without host.
                if (IsLocalDataCenterEmpty(dataCenter) && context.localStorageHostByDataCenterMap.get(dataCenter) == null) {
                    candidate = dataCenter;
                    break;
                }
            }
        }

        ArrayList<String> names;

        // In case we found a suitable candidate for re-use:
        if (candidate != null) {

            getDataCenter().setDataCenterId(candidate.getId());
            getDataCenter().getName().setEntity(candidate.getname());
            getDataCenter().getDescription().setEntity(candidate.getdescription());

            Version version = candidate.getcompatibility_version();
            getDataCenter().getVersion().setSelectedItem(version);
            getCluster().getVersion().setSelectedItem(version);

            setCandidateDataCenter(candidate);

            // If we use current settings there is no need to create cluster.
            if (useCurrentSettings) {

                getCluster().setClusterId(host.getvds_group_id().getValue());
                getCluster().getName().setEntity(host.getvds_group_name());

                VDSGroup cluster = context.hostCluster;
                if (cluster != null) {

                    getCluster().getDescription().setEntity(cluster.getdescription());

                    ServerCpu cpu = new ServerCpu();
                    cpu.setCpuName(cluster.getcpu_name());

                    getCluster().getCPU().setSelectedItem(cpu);
                }

                setCandidateCluster(cluster);
            }
            // Use different cluster
            else {

                // Check the DC cluster list (for re-use)
                clusters = context.clusterListByDataCenterMap.get(candidate);

                // No clusters available - pick up new name.
                if (clusters == null || clusters.isEmpty()) {

                    names = new ArrayList<String>();

                    ArrayList<VDSGroup> listClusters = context.clusterList;
                    for (VDSGroup cluster : listClusters) {
                        names.add(cluster.getname());
                    }

                    getCluster().getName().setEntity(AvailableName(names));
                } else {

                    // Use the DC cluster.
                    VDSGroup cluster = Linq.FirstOrDefault(clusters);

                    getCluster().setClusterId(cluster.getId());
                    getCluster().getName().setEntity(cluster.getname());
                    getCluster().getDescription().setEntity(cluster.getdescription());

                    cluster = Linq.FirstOrDefault(context.clusterList, new Linq.ClusterPredicate(getCluster().getClusterId().getValue()));
                    if (cluster != null) {

                        ServerCpu cpu = new ServerCpu();
                        cpu.setCpuName(cluster.getcpu_name());

                        getCluster().getCPU().setSelectedItem(cpu);
                    }

                    setCandidateCluster(cluster);
                }
            }
        } else {

            // Didn't found DC to re-use, so we select new names.
            names = new ArrayList<String>();

            for (storage_pool dataCenter : dataCenters) {
                names.add(dataCenter.getname());
            }

            getDataCenter().getName().setEntity(AvailableName(names));

            // Choose a Data Center version corresponding to the host.
            if (!StringHelper.isNullOrEmpty(host.getsupported_cluster_levels())) {

                // The supported_cluster_levels are sorted.
                String[] array = host.getsupported_cluster_levels().split("[,]", -1);
                Version maxVersion = null;

                for (int i = 0; i < array.length; i++) {

                    Version vdsVersion = new Version(array[i]);

                    for (Version version : (List<Version>) getDataCenter().getVersion().getItems()) {

                        if (version.equals(vdsVersion) && version.compareTo(maxVersion) > 0) {
                            maxVersion = version;
                        }
                    }
                }

                if (maxVersion != null) {
                    getDataCenter().getVersion().setSelectedItem(maxVersion);
                    getCluster().getVersion().setSelectedItem(maxVersion);
                }
            }

            names = new ArrayList<String>();
            if (clusters == null) {
                clusters = context.clusterList;
            }

            for (VDSGroup cluster : clusters) {
                names.add(cluster.getname());
            }
            getCluster().getName().setEntity(AvailableName(names));
        }

        // Choose default CPU name to match host.
        if (host.getCpuName() != null && getCluster().getCPU().getSelectedItem() != null) {
            getCluster().getCPU().setSelectedItem(Linq.FirstOrDefault((List<ServerCpu>) getCluster().getCPU().getItems(), new Linq.ServerCpuPredicate(host.getCpuName().getCpuName())));
        }

        // Always choose a available storage name.
        ArrayList<storage_domains> storages = context.storageList;
        names = new ArrayList<String>();

        for (storage_domains storageDomain : storages) {
            names.add(storageDomain.getstorage_name());
        }
        getFormattedStorageName().setEntity(AvailableName(names));
    }

    private void SetDefaultNames7() {

        // Get all clusters.
        AsyncDataProvider.GetStorageDomainList(new AsyncQuery(this,
            new INewAsyncCallback() {
                @Override
                public void OnSuccess(Object target, Object returnValue) {

                    context.storageList = (ArrayList<storage_domains>) returnValue;
                    SetDefaultNames8();
                }
            },
            frontendHash));
    }

    public void SetDefaultNames6() {

        // Fill map of local storage host by data center.

        context.clusterListByDataCenterMap = new HashMap<storage_pool, ArrayList<VDSGroup>>();

        AsyncIterator<storage_pool> iterator = new AsyncIterator<storage_pool>(context.dataCenterList);

        iterator.setComplete(
            new AsyncIteratorComplete<storage_pool>() {
                @Override
                public void run(storage_pool item, Object value) {

                    SetDefaultNames7();
                }
            });

        iterator.Iterate(
            new AsyncIteratorFunc<storage_pool>() {
                @Override
                public void run(storage_pool item, AsyncIteratorCallback callback) {

                    AsyncDataProvider.GetClusterList(callback.getAsyncQuery(), item.getId());
                }
            },
            new AsyncIteratorPredicate<storage_pool>() {
                @Override
                public boolean match(storage_pool item, Object value) {

                    context.clusterListByDataCenterMap.put(item, (ArrayList<VDSGroup>) value);
                    return false;
                }
            },
            frontendHash
        );
    }

    public void SetDefaultNames5() {

        // Fill map of local storage host by data center.

        context.localStorageHostByDataCenterMap = new HashMap<storage_pool, VDS>();

        AsyncIterator<storage_pool> iterator = new AsyncIterator<storage_pool>(context.dataCenterList);

        iterator.setComplete(
            new AsyncIteratorComplete<storage_pool>() {
                @Override
                public void run(storage_pool item, Object value) {

                    SetDefaultNames6();
                }
            });

        iterator.Iterate(
            new AsyncIteratorFunc<storage_pool>() {
                @Override
                public void run(storage_pool item, AsyncIteratorCallback callback) {

                    AsyncDataProvider.GetLocalStorageHost(callback.getAsyncQuery(), item.getname());
                }
            },
            new AsyncIteratorPredicate<storage_pool>() {
                @Override
                public boolean match(storage_pool item, Object value) {

                    context.localStorageHostByDataCenterMap.put(item, (VDS) value);
                    return false;
                }
            },
            frontendHash
        );
    }

    public void SetDefaultNames4() {

        // Get data centers containing 'local' in name.
        AsyncDataProvider.GetDataCenterListByName(new AsyncQuery(null,
            new INewAsyncCallback() {
                @Override
                public void OnSuccess(Object target, Object returnValue) {

                    context.dataCenterList = (ArrayList<storage_pool>) returnValue;
                    SetDefaultNames5();
                }
            },
            frontendHash),
            getCommonName() + "*");
    }

    public void SetDefaultNames3() {

        // Get all clusters.
        AsyncDataProvider.GetClusterList(new AsyncQuery(this,
            new INewAsyncCallback() {
                @Override
                public void OnSuccess(Object target, Object returnValue) {

                    context.clusterList = (ArrayList<VDSGroup>) returnValue;
                    SetDefaultNames4();
                }
            },
            frontendHash));
    }

    public void SetDefaultNames2() {

        VDS host = context.host;

        // Get cluster of the host.
        if (host.getvds_group_id() != null) {
            AsyncDataProvider.GetClusterById(new AsyncQuery(this,
                new INewAsyncCallback() {
                    @Override
                    public void OnSuccess(Object target, Object returnValue) {

                        context.hostCluster = (VDSGroup) returnValue;
                        SetDefaultNames3();
                    }
                },
                frontendHash),
                host.getvds_group_id());
        } else {
            SetDefaultNames3();
        }
    }

    public void SetDefaultNames1() {

        VDS host = context.host;

        // Get data center of the host.
        if (host.getstorage_pool_id() != null) {
            AsyncDataProvider.GetDataCenterById(new AsyncQuery(this,
                new INewAsyncCallback() {
                    @Override
                    public void OnSuccess(Object target, Object returnValue) {

                        context.hostDataCenter = (storage_pool) returnValue;
                        SetDefaultNames2();
                    }
                },
                frontendHash),
                host.getstorage_pool_id());
        } else {
            SetDefaultNames2();
        }
    }

    public void SetDefaultNames(VDS host) {

        context.host = host;

        setCommonName(StringFormat.format("%1$s-Local", host.getvds_name().replace('.', '-')));

        SetDefaultNames1();

        //        String message = null;
        //
        //        setCommonName(StringFormat.format("%1$s-Local", host.getvds_name().replace('.', '-')));
        //        storage_pool candidate = null;
        //
        //        //Select all possible DCs
        //        VdcQueryReturnValue returnValue = Frontend.RunQuery(VdcQueryType.Search, new SearchParameters(StringFormat.format("DataCenter: name=%1$s", getCommonName() + "*"), SearchType.StoragePool));
        //
        //        java.util.ArrayList<storage_pool> dataCenterList = new java.util.ArrayList<storage_pool>();
        //        java.util.ArrayList<VDSGroup> clusterList = null;
        //        if (returnValue != null && returnValue.getSucceeded() && returnValue.getReturnValue() != null)
        //        {
        //            dataCenterList = Linq.<storage_pool>Cast((java.util.ArrayList<IVdcQueryable>)returnValue.getReturnValue());
        //        }
        //        //Check if current settings suitable for local setup (in case just SD creation failed - re-using the same setup)
        //        boolean useCurrentSettings = false;
        //        if (host.getstorage_pool_id() != null)
        //        {
        //            storage_pool tempCandidate = DataProvider.GetDataCenterById(host.getstorage_pool_id());
        //            if (IsLocalDataCenterEmpty(tempCandidate))
        //            {
        //                candidate = tempCandidate;
        //                useCurrentSettings = true;
        //            }
        //            else
        //            {
        //                if (tempCandidate != null && tempCandidate.getstorage_pool_type() == StorageType.LOCALFS)
        //                {
        //                    message = "Note: Local Storage is already configured for this Host. The Host belongs to " + host.getstorage_pool_name() + " with local Storage Domain. If OK is clicked - this Host will be moved to a new Data Center, and a new Local Storage Domain will be created. Hit Cancel to abort the operation.";
        //                }
        //            }
        //        }
        //
        //        //Check if there is other DC suitable for re-use
        //        if (candidate == null)
        //        {
        //            for (storage_pool dataCenter : dataCenterList)
        //            {
        //                //Need to check if the new DC is without host.
        //                if (IsLocalDataCenterEmpty(dataCenter) && DataProvider.GetLocalStorageHost(dataCenter.getname()) == null)
        //                {
        //                    candidate = dataCenter;
        //                    break;
        //                }
        //            }
        //        }
        //        java.util.ArrayList<String> listNames = new java.util.ArrayList<String>();
        //        //In case we found a suitable candidate for re-use:
        //        if(candidate != null)
        //        {
        //            getDataCenter().setDataCenterId(candidate.getId());
        //            getDataCenter().getName().setEntity(candidate.getname());
        //            getDataCenter().getDescription().setEntity(candidate.getdescription());
        //            Version compVersion = candidate.getcompatibility_version();
        //            getDataCenter().getVersion().setSelectedItem(compVersion);
        //            getCluster().getVersion().setSelectedItem(compVersion);
        //            setDontCreateDataCenter(true);
        //            //If we use current settings there is no need to create cluster.
        //            if (useCurrentSettings)
        //            {
        //                getCluster().setClusterId(host.getvds_group_id().getValue());
        //                getCluster().getName().setEntity(host.getvds_group_name());
        //                VDSGroup cluster = DataProvider.GetClusterById(host.getvds_group_id().getValue());
        //                if(cluster != null)
        //                {
        //                    getCluster().getDescription().setEntity(cluster.getdescription());
        //                    ServerCpu tempVar = new ServerCpu();
        //                    tempVar.setCpuName(cluster.getcpu_name());
        //                    getCluster().getCPU().setSelectedItem(tempVar);
        //                }
        //                setDontCreateCluster(true);
        //                setDontChangeHostCluster(true);
        //            }
        //            //Use different cluster
        //            else
        //            {
        //                //Check the DC cluster list (for re-use)
        //                clusterList = DataProvider.GetClusterList(candidate.getId());
        //                //No clusters available - pick up new name.
        //                if(clusterList.isEmpty())
        //                {
        //                    java.util.ArrayList<VDSGroup> listClusters = DataProvider.GetClusterList();
        //                    listNames = new java.util.ArrayList<String>();
        //                    for (VDSGroup cluster : listClusters)
        //                    {
        //                        listNames.add(cluster.getname());
        //                    }
        //                    getCluster().getName().setEntity(AvailableName(listNames));
        //                }
        //                else
        //                {
        //                    //Use the DC cluster.
        //                    getCluster().setClusterId(clusterList.get(0).getID());
        //                    getCluster().getName().setEntity(clusterList.get(0).getname());
        //                    getCluster().getDescription().setEntity(clusterList.get(0).getdescription());
        //                    VDSGroup cluster = DataProvider.GetClusterById(getCluster().getClusterId().getValue());
        //                    if (cluster != null)
        //                    {
        //                        ServerCpu tempVar2 = new ServerCpu();
        //                        tempVar2.setCpuName(cluster.getcpu_name());
        //                        getCluster().getCPU().setSelectedItem(tempVar2);
        //                    }
        //                    setDontCreateCluster(true);
        //                    if (host.getvds_group_id().getValue().equals(getCluster().getClusterId()))
        //                    {
        //                        setDontChangeHostCluster(true);
        //                    }
        //                }
        //            }
        //        }
        //        else
        //        {
        //            //Didn't found DC to re-use, so we select new names:
        //            listNames = new java.util.ArrayList<String>();
        //            for (storage_pool storagePool : dataCenterList)
        //            {
        //                listNames.add(storagePool.getname());
        //            }
        //            getDataCenter().getName().setEntity(AvailableName(listNames));
        //
        //            //Choose a Data Center version corresponding to the host.
        //            if (!StringHelper.isNullOrEmpty(host.getsupported_cluster_levels()))
        //            {
        //                //The supported_cluster_levels are sorted.
        //                String[] array = host.getsupported_cluster_levels().split("[,]", -1);
        //                Version maxVersion = null;
        //
        //                for (int i = 0; i < array.length; i++)
        //                {
        //                    Version vdsVersion = new Version(array[i]);
        //                    for (Version version : (java.util.List<Version>)getDataCenter().getVersion().getItems())
        //                    {
        //                        if (version.equals(vdsVersion) && version.compareTo(maxVersion) > 0)
        //                        {
        //                            maxVersion = version;
        //                        }
        //                    }
        //                }
        //                if (maxVersion != null)
        //                {
        //                    getDataCenter().getVersion().setSelectedItem(maxVersion);
        //                    getCluster().getVersion().setSelectedItem(maxVersion);
        //                }
        //            }
        //
        //            listNames = new java.util.ArrayList<String>();
        //            if (clusterList == null)
        //            {
        //                clusterList = DataProvider.GetClusterList();
        //            }
        //
        //            for (VDSGroup cluster : clusterList)
        //            {
        //                listNames.add(cluster.getname());
        //            }
        //            getCluster().getName().setEntity(AvailableName(listNames));
        //        }
        //
        //        //Choose default CPU name to match host.
        //        if (host.getCpuName() != null && getCluster().getCPU().getSelectedItem() != null)
        //        {
        //            getCluster().getCPU().setSelectedItem(Linq.FirstOrDefault((java.util.List<ServerCpu>)getCluster().getCPU().getItems(), new Linq.ServerCpuPredicate(host.getCpuName().getCpuName())));
        //        }
        //
        //        //Always choose a available storage name.
        //        java.util.ArrayList<storage_domains> listStorageDomains = DataProvider.GetStorageDomainList();
        //        listNames = new java.util.ArrayList<String>();
        //        for (storage_domains storageDomain : listStorageDomains)
        //        {
        //            listNames.add(storageDomain.getstorage_name());
        //        }
        //        getFormattedStorageName().setEntity(AvailableName(listNames));
        //
        //
        //        return message;
    }

    private boolean IsLocalDataCenterEmpty(storage_pool dataCenter) {

        if (dataCenter != null && dataCenter.getstorage_pool_type() == StorageType.LOCALFS
            && dataCenter.getstatus() == StoragePoolStatus.Uninitialized) {
            return true;
        }
        return false;
    }

    private String AvailableName(ArrayList<String> list) {

        String commonName = getCommonName();
        ArrayList<Integer> notAvailableNumberList = new ArrayList<Integer>();

        String temp;
        for (String str : list) {

            temp = str.replace(getCommonName(), "");
            if (StringHelper.isNullOrEmpty(temp)) {
                temp = "0";
            }

            int tempInt = 0;

            RefObject<Integer> tempRef_tempInt = new RefObject<Integer>(tempInt);
            boolean tempVar = IntegerCompat.TryParse(temp, tempRef_tempInt);
            tempInt = tempRef_tempInt.argvalue;
            if (tempVar) {
                notAvailableNumberList.add(tempInt);
            }
        }

        Collections.sort(notAvailableNumberList);
        int i;
        for (i = 0; i < notAvailableNumberList.size(); i++) {
            if (notAvailableNumberList.get(i) == i) {
                continue;
            }
            break;
        }

        if (i > 0) {
            commonName = getCommonName() + (new Integer(i)).toString();
        }

        return commonName;
    }

    private int queryCounter;

    private void Frontend_QueryStarted() {
        queryCounter++;
        if (getProgress() == null) {
            StartProgress(null);
        }
    }

    private void Frontend_QueryComplete() {
        queryCounter--;
        if (queryCounter == 0) {
            StopProgress();
        }
    }

    private final Context context = new Context();

    public final class Context {

        public VDS host;
        public storage_pool hostDataCenter;
        public VDSGroup hostCluster;
        public storage_pool candidate;
        public ArrayList<storage_pool> dataCenterList;
        public ArrayList<VDSGroup> clusterList;
        public ArrayList<storage_domains> storageList;
        public HashMap<storage_pool, VDS> localStorageHostByDataCenterMap;
        public HashMap<storage_pool, ArrayList<VDSGroup>> clusterListByDataCenterMap;
    }
}


text:
'use strict';

angular
    .module('hawk')
    .factory('materialDefinitionUpdater', ['viewModel', function (viewModel) {
        var materialDefinitionUpdater = this;

        materialDefinitionUpdater.getAllMaterialDefinitions = function (materialDefinitions) {
            viewModel.allMaterialDefinitions = materialDefinitions;
        };

        materialDefinitionUpdater.getMaterialDefinitionById = function (materialDefinition) {
            return materialDefinition;
        };

        materialDefinitionUpdater.addMaterialDefinition = function (materialDefinition) {
            viewModel.allMaterialDefinitions.push(materialDefinition);
        };

        materialDefinitionUpdater.updateMaterialDefinition = function (materialDefinition) {
            viewModel.allMaterialDefinitions.forEach(function (currentMaterial, materialIndex, array) {
                if(currentMaterial.id == materialDefinition.id){
                    viewModel.allMaterialDefinitions[materialIndex] = materialDefinition;
                }
            });
        };

        materialDefinitionUpdater.deleteMaterialDefinition = function (materialDefinition) {

        };

        return materialDefinitionUpdater;
    }]);


text:
describe ParseFiles do

  let(:service_list) { ParseFiles.parse_services_file(SERVICES) }
  let(:services) { Services.new }
  let(:groups) { Groups.new }

  describe '.parse_services_file' do
    context "valid services file" do
      it "should return an array with fourteen elements" do
        expect(service_list.size).to eq 14
      end

      it "should contain something" do
        fields = service_list[10]
        expect(fields[0]).to eq '0353392988'
        expect(fields[1]).to eq 'Unknown'
        expect(fields[2]).to start_with '15 Violet Grove'
        expect(fields[3]).to be nil
      end
    end

    context "empty services file" do
      it "should return an empty array" do
        expect(ParseFiles.parse_services_file(EMPTY)).to be_empty
      end
    end

    context "invalid services file" do
      it "should return an empty array" do
        expect(ParseFiles.parse_services_file(INVALID)).to be_empty
      end
    end

    context "missing services file" do
      it "should throw an exception" do
        expect { ParseFiles.parse_services_file(MISSING) }.to raise_error IOError
      end
    end
  end

  describe ".map_services" do
    before :each do
      ParseFiles.map_services(groups,services,service_list)
    end

    it "should create 3 groups" do
      expect(groups.size).to eq 3
    end

    it "should create 14 services" do
      expect(services.size).to eq 14
    end
  end

  describe ".parse_bill_file" do
    let(:call_type) { CallType.new }

    before :each do
      call_type.load(CALL_TYPES)
      @invoice_date = ParseFiles.parse_bill_file(services,call_type,BILLS)
    end

    it "returns invoice date" do
      expect(@invoice_date).to eq '20130619'
    end

    it "collates services" do
      service = services.service('0455553125')
      expect(service.service_summaries.size).to eq 2
      expect(service.call_details.size).to eq 147
    end

    context "missing bill file" do
      it "should throw an exception" do
        expect { ParseFiles.parse_bill_file(services,call_type,MISSING) }.to raise_error IOError
      end
    end

    context "invalid bill file" do
      it "should throw an exception" do
        expect { ParseFiles.parse_bill_file(services,call_type,INVALID) }.to raise_error ArgumentError
      end
    end
  end

end


text:
package ch.frontg8.view;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import ch.frontg8.R;
import ch.frontg8.lib.crypto.KeystoreHandler;
import ch.frontg8.lib.crypto.LibCrypto;

public class AboutMeActivity extends AppCompatActivity {
    private final static int WHITE = 0xFFFFFFFF;
    private final static int BLACK = 0xFF000000;
    private final static int WIDTH = 400;
    private final static int HEIGHT = 400;
    private String publicKey = null;
    private boolean showAsText = false;

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

        final TextView textViewMyPublicKey = (TextView) findViewById(R.id.editTextMyPublicKey);
        publicKey = new String(LibCrypto.getMyPublicKeyBytes(new KeystoreHandler(this), this));
        textViewMyPublicKey.setText(publicKey);
        textViewMyPublicKey.setVisibility(View.GONE);

        Button buttonCopyToClipboard = (Button) findViewById(R.id.buttonCopyToClipboard);
        final Button buttonShowText = (Button) findViewById(R.id.buttonShowText);
        final ImageView imageView = (ImageView) findViewById(R.id.myImage);

        try {
            Bitmap bitmap = encodeAsBitmap(publicKey);
            imageView.setImageBitmap(bitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }

        buttonCopyToClipboard.setOnClickListener(new AdapterView.OnClickListener() {
            public void onClick(View view) {
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("label", publicKey);
                clipboard.setPrimaryClip(clip);
            }
        });

        buttonShowText.setOnClickListener(new AdapterView.OnClickListener() {
            public void onClick(View view) {
                if (!showAsText) {
                    textViewMyPublicKey.setVisibility(View.VISIBLE);
                    imageView.setVisibility(View.GONE);
                    buttonShowText.setText(R.string.AboutActivity_ButtonShowAsQrCode);
                    showAsText = true;
                } else {
                    textViewMyPublicKey.setVisibility(View.GONE);
                    imageView.setVisibility(View.VISIBLE);
                    buttonShowText.setText(R.string.AboutActivity_ButtonShowAsText);
                    showAsText = false;
                }
            }
        });

    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        return id == R.id.action_settings || super.onOptionsItemSelected(item);

    }

    private Bitmap encodeAsBitmap(String str) throws WriterException {
        BitMatrix result;

        try {
            result = new MultiFormatWriter().encode(str,
                    BarcodeFormat.QR_CODE, WIDTH, HEIGHT, null);
        } catch (IllegalArgumentException iae) {
            // Unsupported format
            return null;
        }

        int w = result.getWidth();
        int h = result.getHeight();
        int[] pixels = new int[w * h];
        for (int y = 0; y < h; y++) {
            int offset = y * w;
            for (int x = 0; x < w; x++) {
                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, w, 0, 0, w, h);
        return bitmap;
    }

}


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

<title>YAML | Example "menu_shiny_buttons"</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

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

				Skip to the navigation.
				Skip to the content.

				Login | Contact | Imprint

Example | Beispiel "menu_shiny_buttons"

			YAML • (X)HTML/CSS Framework

Button 1

Button 2

Button 3

Button 4

Button 5

Column  #col1

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam malesuada   suscipit pede. Nullam ipsum lacus, varius vel, nonummy in, consequat ut, neque.

Lorem ipsum ...

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam malesuada   suscipit pede. Nullam ipsum lacus, varius vel, nonummy in, consequat ut, neque.   Vivamus viverra. Duis dolor arcu, lacinia sit amet, sollicitudin sed, aliquet   vel, quam. Pellentesque molestie laoreet tortor. Aenean quam. Pellentesque magna   metus, venenatis sit amet, congue nec, dictum in, est. Aliquam nibh.

Column  #col2

Integer condimentum, justo a venenatis vulputate, enim pede porttitor eros, non   pretium lorem orci id tortor. Nulla a ligula. Mauris nulla arcu, luctus vel,   consequat non, luctus eu, nisi. Mauris volutpat, nunc eget pretium blandit,   ligula quam commodo nisl, ac fermentum nibh pede et nulla. In condimentum   bibendum nisi. Vestibulum risus.

Nullam placerat varius nibh. Quisque tellus   sapien, placerat sed, aliquam sit amet, scelerisque sit amet, nisi. Pellentesque   eget leo vitae felis laoreet dictum. Duis pellentesque porttitor sapien. Fusce   leo. Nulla leo. Donec mattis, justo nec gravida euismod, massa mi posuere   mauris.

Column  #col3

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam malesuada   suscipit pede. Nullam ipsum lacus, varius vel, nonummy in, consequat ut, neque.   Vivamus viverra. Duis dolor arcu, lacinia sit amet, sollicitudin sed, aliquet   vel, quam. Pellentesque molestie laoreet tortor. Aenean quam. Pellentesque magna   metus.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam malesuada   suscipit pede. Nullam ipsum lacus, varius vel, nonummy in, consequat ut, neque.   Vivamus viverra. Duis dolor arcu, lacinia sit amet, sollicitudin sed, aliquet   vel, quam. Pellentesque molestie laoreet tortor. Aenean quam. Pellentesque magna   metus, venenatis sit amet, congue nec, dictum in, est. Aliquam nibh. Integer   congue nisl in mauris. Ut risus diam, ornare eget, interdum id, tincidunt at,   eros.

Nulla vitae mauris. Phasellus vel ligula quis dolor bibendum egestas. Duis a   massa ut orci varius placerat. Sed leo nulla, tempor nec, commodo in, fringilla   vel, nibh. Cras nibh. Pellentesque venenatis felis. Cum sociis natoque penatibus   et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum fringilla   gravida nunc. Mauris neque. Cras gravida metus eget sapien. Sed faucibus, turpis   ut pretium hendrerit, turpis mauris scelerisque tellus, vel convallis metus   massa in neque.

Footer with copyright notice and status information

Layout based on YAML


text:
layout: page
title: "About"
description: "写一段好代码,降低世界碳排量!"
header-img: "img/common/about-bg.jpg"
---

<select onchange= "onLanChange(this.options[this.options.selectedIndex].value)">
    <option value="0" selected> 中文 Chinese </option>
    <option value="1"> 英语 English </option>
</select>

        写一段好代码,降低世界碳排量。

我叫戴伟来。

曾经是一个工科学生,主攻网络工程。

也担任过摇滚乐队队长,是一个吉他手、贝斯手。

现在成了一名高颜值iOS开发工程师,是团队负责人、技术狂热爱好者。

未来将会是。。。待续

        Good code change the world.

This is David Day.

Majoring in Network Engineering during college education

I was leader of a rock band,being the guitar&bass player.

Now I'm a good-looking iOS developer,group leader and a zealous fan of tech.

In the coming days,I will…

{% if site.duoshuo_username %}

<input id="dsUser" type="hidden" value="{{site.duoshuo_username}}"  />

{% endif %}


text:
namespace Nethereum.BlockchainProcessing.BlockStorage.Entities
{
    public interface ITransactionView
    {
        string AddressFrom { get; }
        string AddressTo { get;  }
        string BlockHash { get;  }
        string BlockNumber { get;  }
        string CumulativeGasUsed { get;  }
        string Error { get;  }
        bool Failed { get;  }
        bool FailedCreateContract { get;  }
        string Gas { get;  }
        string GasPrice { get;  }
        string GasUsed { get;  }
        string Hash { get;  }
        bool HasLog { get;  }
        bool HasVmStack { get;  }
        string Input { get;  }
        string NewContractAddress { get;  }
        string Nonce { get;  }
        string ReceiptHash { get;  }
        string TimeStamp { get;  }
        string TransactionIndex { get;  }
        string Value { get;  }
        string MaxFeePerGas { get; }
        string MaxPriorityFeePerGas { get; }

    }
}


text:
Chapel and Python Examples
==========================

The code snippets throughout the documentation are kept here. Test should be
written for all snippets. For Chapel tests, add .good files (and any other
files) and `start_test` (from Chapel project) will run them. For Python tests,
add to the test case in `test_all_python.py`. `py.test` will then run the
tests.


text:
/* --- hide elements not used in print view --- */
body * { visibility: hidden; }
div#credentials * {visibility: visible; }
div#credentials { border:1px solid #FFF; }
#wl { text-align:left; }
#printCredentials,
#printWelcome { display:none; }


text:
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2019 The Advanced Technology Coin and Eternity Group
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "splashscreen.h"

#include "guiutil.h"
#include "networkstyle.h"

#include "clientversion.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "version.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif

#include <QApplication>
#include <QCloseEvent>
#include <QDesktopWidget>
#include <QPainter>

SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle) :
    QWidget(0, f), curAlignment(0)
{

    // transparent background
    setAttribute(Qt::WA_TranslucentBackground);
    setStyleSheet("background:transparent;");

    // no window decorations
    setWindowFlags(Qt::FramelessWindowHint);

    // set reference point, paddings
    int paddingLeft             = 14;
    int paddingTop              = 470;
    int titleVersionVSpace      = 17;
    int titleCopyrightVSpace    = 32;

    float fontFactor            = 1.0;

    // define text to place
    QString titleText       = tr("Arc Core");
    QString versionText     = QString(tr("Version %1")).arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightTextBtc   = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers"));
    QString copyrightTextArc   = QChar(0xA9)+QString(" %1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Advanced Technology Coin and Eternity Group"));
    QString titleAddText    = networkStyle->getTitleAddText();
    // networkstyle.cpp can't (yet) read themes, so we do it here to get the correct Splash-screen
    QString splashScreenPath = ":/images/" + GUIUtil::getThemeName() + "/splash";
    if(GetBoolArg("-regtest", false))
        splashScreenPath = ":/images/" + GUIUtil::getThemeName() + "/splash_testnet";
    if(GetBoolArg("-testnet", false))
        splashScreenPath = ":/images/" + GUIUtil::getThemeName() + "/splash_testnet";

    QString font = QApplication::font().toString();

    // load the bitmap for writing some text over it
    pixmap = QPixmap(splashScreenPath);

    QPainter pixPaint(&pixmap);
    pixPaint.setPen(QColor(100,100,100));

    // check font size and drawing with
    pixPaint.setFont(QFont(font, 28*fontFactor));
    QFontMetrics fm = pixPaint.fontMetrics();
    int titleTextWidth  = fm.width(titleText);
    if(titleTextWidth > 160) {
        // strange font rendering, Arial probably not found
        fontFactor = 0.75;
    }

    pixPaint.setFont(QFont(font, 28*fontFactor));
    fm = pixPaint.fontMetrics();
    titleTextWidth  = fm.width(titleText);
    pixPaint.drawText(paddingLeft,paddingTop,titleText);

    pixPaint.setFont(QFont(font, 15*fontFactor));
    pixPaint.drawText(paddingLeft,paddingTop+titleVersionVSpace,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 10*fontFactor));
    pixPaint.drawText(paddingLeft,paddingTop+titleCopyrightVSpace,copyrightTextBtc);
    pixPaint.drawText(paddingLeft,paddingTop+titleCopyrightVSpace+12,copyrightTextArc);

    // draw additional text if special network
    if(!titleAddText.isEmpty()) {
        QFont boldFont = QFont(font, 10*fontFactor);
        boldFont.setWeight(QFont::Bold);
        pixPaint.setFont(boldFont);
        fm = pixPaint.fontMetrics();
        int titleAddTextWidth  = fm.width(titleAddText);
        pixPaint.drawText(pixmap.width()-titleAddTextWidth-10,pixmap.height()-25,titleAddText);
    }

    pixPaint.end();

    // Resize window and move to center of desktop, disallow resizing
    QRect r(QPoint(), pixmap.size());
    resize(r.size());
    setFixedSize(r.size());
    move(QApplication::desktop()->screenGeometry().center() - r.center());

    subscribeToCoreSignals();
    installEventFilter(this);
}

SplashScreen::~SplashScreen()
{
    unsubscribeFromCoreSignals();
}

bool SplashScreen::eventFilter(QObject * obj, QEvent * ev) {
    if (ev->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(ev);
        if(keyEvent->text()[0] == 'q' && breakAction != nullptr) {
            breakAction();
        }
    }
    return QObject::eventFilter(obj, ev);
}

void SplashScreen::slotFinish(QWidget *mainWin)
{
    Q_UNUSED(mainWin);

    /* If the window is minimized, hide() will be ignored. */
    /* Make sure we de-minimize the splashscreen window before hiding */
    if (isMinimized())
        showNormal();
    hide();
    deleteLater(); // No more need for this
}

static void InitMessage(SplashScreen *splash, const std::string &message)
{
    QMetaObject::invokeMethod(splash, "showMessage",
        Qt::QueuedConnection,
        Q_ARG(QString, QString::fromStdString(message)),
        Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter),
        Q_ARG(QColor, QColor(55,55,55)));
}

static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress)
{
    InitMessage(splash, title + strprintf("%d", nProgress) + "%");
}

void SplashScreen::setBreakAction(const std::function<void(void)> &action)
{
    breakAction = action;
}

static void SetProgressBreakAction(SplashScreen *splash, const std::function<void(void)> &action)
{
    QMetaObject::invokeMethod(splash, "setBreakAction",
        Qt::QueuedConnection,
        Q_ARG(std::function<void(void)>, action));
}

#ifdef ENABLE_WALLET
static void ConnectWallet(SplashScreen *splash, CWallet* wallet)
{
    wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2));
}
#endif

void SplashScreen::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1));
    uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
    uiInterface.SetProgressBreakAction.connect(boost::bind(SetProgressBreakAction, this, _1));
#ifdef ENABLE_WALLET
    uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1));
#endif
}

void SplashScreen::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1));
    uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
#ifdef ENABLE_WALLET
    if(pwalletMain)
        pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
#endif
}

void SplashScreen::showMessage(const QString &message, int alignment, const QColor &color)
{
    curMessage = message;
    curAlignment = alignment;
    curColor = color;
    update();
}

void SplashScreen::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(0, 0, pixmap);
    QRect r = rect().adjusted(5, 5, -5, -5);
    painter.setPen(curColor);
    painter.drawText(r, curAlignment, curMessage);
}

void SplashScreen::closeEvent(QCloseEvent *event)
{
    StartShutdown(); // allows an "emergency" shutdown during startup
    event->ignore();
}


text:
package example;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import example.RoughHttpServer.Response;

public class ServerTimingExample {

	public static void main(final String[] args) throws Exception {
		final RoughHttpServer httpServer = new RoughHttpServer(request -> {
			System.out.println(request.getRequestLine());
			final Map<String, String> headers = new HashMap<>();
			headers.put("Server-Timing", "app;dur=1.2;desc=Application, db;dur=3.4");
			headers.put("Content-Type", "text/html; charset=UTF-8");
			final String entity = "
Hello, world!
";
			return new Response(200, "OK", headers, entity);
		});
		httpServer.start();
		TimeUnit.HOURS.sleep(1);
	}
}


text:
import networkx as nx

from bokeh.io import show, output_file
from bokeh.models import Plot, Range1d, MultiLine, Circle, HoverTool, TapTool, BoxSelectTool
from bokeh.models.graphs import from_networkx, NodesAndLinkedEdges, EdgesAndLinkedNodes
from bokeh.palettes import Spectral4

G=nx.karate_club_graph()

plot = Plot(plot_width=400, plot_height=400,
            x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
plot.title.text = "Graph Interaction Demonstration"

plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())

graph_renderer = from_networkx(G, nx.circular_layout, scale=1, center=(0,0))

graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])

graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5)
graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = EdgesAndLinkedNodes()

plot.renderers.append(graph_renderer)

output_file("interactive_graphs.html")
show(plot)


text:
package io.milton.http;

import io.milton.http.exceptions.BadRequestException;

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

import io.milton.http.exceptions.ConflictException;
import io.milton.http.exceptions.NotAuthorizedException;
import io.milton.http.exceptions.NotFoundException;
import io.milton.http.webdav.DefaultUserAgentHelper;
import java.io.IOException;

public class StandardFilter implements Filter {

	private Logger log = LoggerFactory.getLogger(StandardFilter.class);
	public static final String INTERNAL_SERVER_ERROR_HTML = "
Internal Server Error (500)
";

	public StandardFilter() {
	}

	@Override
	public void process(FilterChain chain, Request request, Response response) {
		HttpManager manager = chain.getHttpManager();
		try {
			Request.Method method = request.getMethod();

			Handler handler = manager.getMethodHandler(method);
			if (handler == null) {
				log.warn("No method handler for: " + method + " Please check that dav level 2 protocol support is enabled");
				manager.getResponseHandler().respondMethodNotImplemented(null, response, request);
			} else {
				if (log.isTraceEnabled()) {
					log.trace("delegate to method handler: " + handler.getClass().getCanonicalName());
				}
				handler.process(manager, request, response);
				if (response.getEntity() != null) {
					manager.sendResponseEntity(response);
				} else {
					log.debug("No response entity to send to client for method: " + request.getMethod());
				}

			}

		} catch (BadRequestException ex) {
			log.warn("BadRequestException: " + ex.getReason(), ex);
			manager.getResponseHandler().respondBadRequest(ex.getResource(), response, request);
		} catch (ConflictException ex) {
			log.warn("conflictException: ", ex);
			manager.getResponseHandler().respondConflict(ex.getResource(), response, request, INTERNAL_SERVER_ERROR_HTML);
		} catch (NotAuthorizedException ex) {
			log.warn("NotAuthorizedException", ex);
			manager.getResponseHandler().respondUnauthorised(ex.getResource(), response, request);
		} catch (IOException ex) {
			if (ex.getMessage().contains("Could not get file content")) {
				manager.getResponseHandler().respondConflict(null, response, request, "Could not get file content. Perhaps no replicas are available");
			} else {
				response.sendError(Response.Status.SC_INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR_HTML);
			}
		} catch (Throwable e) {
			if (e instanceof NotFoundException) {
				response.sendError(Response.Status.SC_CONFLICT, "Physical resource not found");
			} else {
				// Looks like in some cases we can be left with a connection in an indeterminate state
				// due to the content length not being equal to the content length header, so
				// fall back on the udnerlying connection provider to manage the error
				log.warn("exception sending content", e);
				response.sendError(Response.Status.SC_INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR_HTML);
			}
		} finally {
			//manager.closeResponse(response);
		}
	}
}


text:
import Chord from './Chord';
import Collection from './Collection';
import Cluster from './Cluster';
import Grid from './Grid';
// import ForceSimulation from './ForceSimulation';
import Pack from './Pack';
import Partition from './Partition';
import Pie from './Pie';
import Stack from './Stack';
import Tree from './Tree';
import Treemap from './Treemap';
// import Voronoi from './Voronoi';

export {
  Chord,
  Collection,
  Cluster,
  Grid,
  Pack,
  Partition,
  Pie,
  Stack,
  Tree,
  Treemap,
};


text:
class TripsController < ApplicationController
  before_action :set_trip, only: [:show, :update, :destroy, :edit]

  def index
    if current_user
      @created_trips = current_user.created_trips
      @joined_trips = current_user.trips
    else
      @trips = Trip.order(:start_at).limit(25)
    end
  end

  def new
    @trip = Trip.new
  end

  def create
    @trip = Trip.new(trip_params)
    @trip.user_id = current_user.id
    p @trip
    if @trip.save
      redirect_to  @trip
    else
      redirect_to '/'
    end
  end

  private
    def set_trip
      @trip = Trip.find(params[:id])
    end

    def trip_params
      params.require(:trip).permit(:origin_id, :destination_id, :start_at, :end_at)
    end
end


text:
class SearchSerializer < ActiveModel::Serializer
  embed :ids, include: true

  attributes :id, :name
  has_one :list_item
end


text:
<?php namespace Tartan\Signature\Exceptions;

class SignatureVersionException extends SignatureException
{

}


text:
<?php

namespace DNA\DNARaygun;

use SilverStripe\Raygun\RaygunHandler as SSRaygunHandler;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Injector\Factory;
use Raygun4php\RaygunClient;
use SilverStripe\Control\Director;

class RaygunHandler extends SSRaygunHandler {

    use Configurable;

    private static $app_name = 'DEFAULT';
    /**
     * @param array $record
     * @param array $tags
     * @param array $customData
     * @param int|float $timestamp
     */
    protected function writeError(array $record, array $tags = array(), array $customData = array(), $timestamp = null)
    {

        if (Director::isDev()) {
            return false;
        }

        $message = sprintf("[%s] %s",
            self::config()->app_name,
            $record['message']
        );

        $context = $record['context'];

        $this->client->SendError(
            0,
            $message,
            $context['file'],
            $context['line'],
            $tags,
            $customData,
            $timestamp
        );
    }

    /**
     * @param array $record
     * @param array $tags
     * @param array $customData
     * @param int|float $timestamp
     */
    protected function writeException(array $record, array $tags = array(), array $customData = array(), $timestamp = null)
    {
        if (Director::isDev()) {
            return false;
        }

        $exception = $record['context']['exception'];

        $message = array();
        $message['errstr'] = $exception->getMessage();
        $message['errno'] = $exception->getCode();
        $message['errcontext'] = $exception->getTrace();
        $message['errfile'] = $exception->getFile();
        $message['errline'] = $exception->getLine();
        $message['errstr'] = sprintf("[%s] %s",
            self::config()->app_name,
            $message['errstr']
        );

        $reportedException = new ReportedException($message);

        $this->client->SendException($reportedException, $tags, $customData, $timestamp);
    }

}


text:
test_description='Tests rebase performance'
. ./perf-lib.sh

test_perf_default_repo

test_expect_success 'setup rebasing on top of a lot of changes' '
	git checkout -f -b base &&
	git checkout -b to-rebase &&
	git checkout -b upstream &&
	for i in $(seq 100)
	do
		# simulate huge diffs
		echo change$i >unrelated-file$i &&
		seq 1000 >>unrelated-file$i &&
		git add unrelated-file$i &&
		test_tick &&
		git commit -m commit$i unrelated-file$i &&
		echo change$i >unrelated-file$i &&
		seq 1000 | tac >>unrelated-file$i &&
		git add unrelated-file$i &&
		test_tick &&
		git commit -m commit$i-reverse unrelated-file$i ||
		break
	done &&
	git checkout to-rebase &&
	test_commit our-patch interesting-file
'

test_perf 'rebase on top of a lot of unrelated changes' '
	git rebase --onto upstream HEAD^ &&
	git rebase --onto base HEAD^
'

test_expect_success 'setup rebasing many changes without split-index' '
	git config core.splitIndex false &&
	git checkout -b upstream2 to-rebase &&
	git checkout -b to-rebase2 upstream
'

test_perf 'rebase a lot of unrelated changes without split-index' '
	git rebase --onto upstream2 base &&
	git rebase --onto base upstream2
'

test_expect_success 'setup rebasing many changes with split-index' '
	git config core.splitIndex true
'

test_perf 'rebase a lot of unrelated changes with split-index' '
	git rebase --onto upstream2 base &&
	git rebase --onto base upstream2
'

test_done


text:
package simpleserver.command;

import static simpleserver.lang.Translations.t;
import simpleserver.Server;
import simpleserver.Time;

public abstract class TimeCommand extends AbstractCommand {
  public TimeCommand() {
    super("time [set] [number|day|night|unfreeze] [freeze]", "Set or freeze time");
  }

  private void usage() {
    info(t("Usage:") + " " + commandPrefix() +
        "time 0-23999|day|night|unfreeze [freeze]");
  }

  public void execute(Server server, String message) {
    Time time = server.time;
    String[] arguments = extractArguments(message);

    if (arguments.length == 0) {
      long servertime = time.get();
      long realtime = (servertime + 6000) % 24000;
      tCaptionedInfo("Current time", "%d:%d (%d)", realtime / 1000,
                     (realtime % 1000) * 6 / 100, servertime % 24000);
    } else if (arguments.length >= 1) {
      int arg = 0;
      if (arguments[arg].equals("set")) {
        arg++;
      }
      String argument = arguments[arg];
      long value;

      if (argument.equals("add")) {
        tError("This is not the standard time command.");
        usage();
        return;
      } else if (argument.equals("unfreeze")) {
        time.unfreeze();
        tInfo("Time unfrozen");
        return;
      } else if (argument.equals("freeze")) {
        time.freeze();
        tInfo("Time frozen");
        return;
      } else {
        try {
          value = time.parse(argument);
        } catch (NumberFormatException e) {
          tError("Invalid argument!");
          usage();
          return;
        }
      }

      arg++;
      if (time.unfreeze()) {
        tInfo("Time unfrozen");
      }

      if (arguments.length <= arg) {
        time.set(value);
        tInfo("Time set");
      } else {
        argument = arguments[arg];

        if (argument.equals("freeze")) {
          time.freeze(value);
          tInfo("Time frozen");
        } else {
          tError("Optional 2nd argument must be %s!", "freeze");
        }
      }
    }
  }

  protected abstract void error(String message);

  protected abstract void tError(String message);

  protected abstract void tError(String message, Object... args);

  protected abstract void info(String message);

  protected abstract void tInfo(String message);

  protected abstract void captionedInfo(String caption, String message, Object... args);

  protected abstract void tCaptionedInfo(String caption, String message, Object... args);
}


text:
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read().replace('.. :changelog:', '')

requirements = [
    'jsonschema',
    'werkzeug',
    'strict_rfc3339',
    'six',
    'future'
]

test_requirements = [
    'flask',
    'pytest',
    'mock',
    'enum34',
    'hypothesis',
    'pytest-xdist',
    'sphinx_rtd_theme'
]

setup(
    name='spectastic',
    version='0.3.1',
    description="Request and response validation compatible with swagger.",
    long_description=readme + '\n\n' + history,
    author="Jacob Straszynski",
    author_email='jacob.straszynski@planet.com',
    url='https://github.com/planetlabs/spectastic',
    packages=[
        'spectastic',
    ],
    package_dir={'spectastic':
                 'spectastic'},
    include_package_data=True,
    install_requires=requirements,
    license="Apache 2",
    zip_safe=False,
    keywords='spectastic',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
    test_suite='tests',
    tests_require=test_requirements
)


text:
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var helper = function(root) {
    if (root === null) return 0;
    if (root.left === null && root.right === null) return 1;
    var left = helper(root.left);
    var right = helper(root.right);
    if (left != -1 && right != -1) {
        var diff = left > right ? left - right : right - left;
        if (diff <= 1) {
            return 1 + (left > right ? left : right);
        }
    }
    return -1;
};

var isBalanced = function(root) {
    return helper(root) != -1;
};


text:
<?php
/**
 * Description of Sluggify
 *
 * @author Sarjono Mukti Aji <me@simukti.net>
 */
namespace Simukti\Utility;

class Sluggify
{
    /**
     * @param   string $string String to sluggify
     * @param   string $separator sluggify separator
     * @return  string Sluggified string
     */
    public static function create($string, $separator = '-')
    {
        $string = iconv('utf-8', 'ascii//translit', $string);
        $string = strtolower($string);
        $string = preg_replace('#[^a-z0-9\-]#', $separator, $string);
        $string = preg_replace('#-{2,}#', $separator, $string);
        $string = trim($string, $separator);

        return $string;
    }
}


text:
/*
 * Camel EndpointConfiguration generated by camel-api-component-maven-plugin
 */
package org.apache.camel.component.twilio;

import org.apache.camel.spi.ApiMethod;
import org.apache.camel.spi.ApiParam;
import org.apache.camel.spi.ApiParams;
import org.apache.camel.spi.Configurer;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriParams;

/**
 * Camel endpoint configuration for {@link com.twilio.rest.api.v2010.account.Notification}.
 */
@ApiParams(apiName = "notification",
           description = "",
           apiMethods = {@ApiMethod(methodName = "fetcher", description="Create a NotificationFetcher to execute fetch", signatures={"com.twilio.rest.api.v2010.account.NotificationFetcher fetcher(String pathSid)", "com.twilio.rest.api.v2010.account.NotificationFetcher fetcher(String pathAccountSid, String pathSid)"}), @ApiMethod(methodName = "reader", description="Create a NotificationReader to execute read", signatures={"com.twilio.rest.api.v2010.account.NotificationReader reader()", "com.twilio.rest.api.v2010.account.NotificationReader reader(String pathAccountSid)"}), }, aliases = {"^creator$=create", "^deleter$=delete", "^fetcher$=fetch", "^reader$=read", "^updater$=update"})
@UriParams
@Configurer(extended = true)
public final class NotificationEndpointConfiguration extends TwilioConfiguration {
    @UriParam
    @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "fetcher", description="The SID of the Account that created the resource to fetch"), @ApiMethod(methodName = "reader", description="The SID of the Account that created the resources to read")})
    private String pathAccountSid;
    @UriParam
    @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "fetcher", description="The unique string that identifies the resource")})
    private String pathSid;

    public String getPathAccountSid() {
        return pathAccountSid;
    }

    public void setPathAccountSid(String pathAccountSid) {
        this.pathAccountSid = pathAccountSid;
    }

    public String getPathSid() {
        return pathSid;
    }

    public void setPathSid(String pathSid) {
        this.pathSid = pathSid;
    }
}


text:
create class test_class(col1 integer, col2 varchar(20));
create class test_class1(col1 integer, col2 varchar(20));
create trigger test_trigger
  before statement delete on test_class
  execute delete from test_class1 where col2='nhn';

insert into test_class values(999,'nhn');
insert into test_class values(888,'nhn');
insert into test_class1 values(999,'nhn');
insert into test_class1 values(888,'nhn');
delete from test_class where col1 = 999;
delete from test_class where col1 = 888;
select * from test_class1;

call login('dba') on class db_user;
select owner, name,decode(action_type,  1,'INSERT or UPDATE or DELETE or CALL or EVALUATE',
                                          2,'REJECT',
                                          3,'INVALIDATE_TRANSCATION',
                                          4,'PRINT',
                                          'unknown Action_type')as action_type
from   db_trigger
where  name = 'test_trigger';

drop trigger test_trigger;
drop class test_class;
drop class test_class1;

--+ holdcas off;


text:
package org.eclipse.jnosql.diana.query.method;

import jakarta.nosql.query.Condition;
import jakarta.nosql.query.Operator;
import jakarta.nosql.query.QueryValue;

final class MethodCondition implements Condition {

    private final String name;

    private final Operator operator;

    private final QueryValue<?> value;

    MethodCondition(String name, Operator operator) {
        this.name = name;
        this.operator = operator;
        this.value = new MethodParamQueryValue(name);
    }

    MethodCondition(String name, Operator operator, QueryValue<?> value) {
        this.name = name;
        this.operator = operator;
        this.value = value;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public Operator getOperator() {
        return operator;
    }

    @Override
    public QueryValue<?> getValue() {
        return value;
    }

    @Override
    public String toString() {
        return name + " " + operator + " " + value;
    }
}


text:
/**
 * This file contains functions used for displaying the familiar detail dialog
 */

function showCardDetailDialog(cardInfo) {
    currentCard = cardInfo;
    currentSkillIndex = 0;
    var elem = document.getElementById("card-detail-figure");
    var src = cardInfo.image;

    if (elem.src == src) {
        $("#card-detail-loading-figure").css("visibility", "hidden");
        $("#card-detail-figure").css("visibility", "visible");
    } else {
        elem.onload = function () {
            $("#card-detail-loading-figure").css("visibility", "hidden");
            $("#card-detail-figure").css("visibility", "visible");
        }
    }

    $("#card-detail-loading-figure").css("visibility", "visible");
    $("#card-detail-figure").css("visibility", "hidden");
    showDialog("card-detail-dialog");
    elem.src = cardInfo.image;

    // $("#card-detail-figure-rarity").removeClass();
    // $("#card-detail-figure-rarity").addClass(getRarityClassName(cardInfo.rarity, cardInfo.evolution, cardInfo.maxEvolution));
    $(".card-detail-name").text(unescape(cardInfo.name));
    updateSkillDisplay();
    $(".card-detail-default-action-name").text(unescape(cardInfo.standardAction.name));
    $(".card-detail-default-action-description").text(unescape(cardInfo.standardAction.comment));
    $(".card-detail-max-hp").text(cardInfo.hp);
    $(".card-detail-max-atk").text(cardInfo.atk);
    $(".card-detail-max-def").text(cardInfo.def);
    $(".card-detail-max-wis").text(cardInfo.wis);
    $(".card-detail-max-agi").text(cardInfo.agi);
    // $(".card-detail-growth-type").text(getGrowthName(cardInfo.growthType));
    // $(".card-detail-value").text(cardInfo.price);
    $(".card-detail-current-hp").text(cardInfo.hp + "/" + cardInfo.hp);
}

function showCardDetailDialogById(id) {
    var cardMan = CardManager.getInstance();
    var card = cardMan.getCardById(id);

    showCardDetailDialog(cardMan.getCardInfoForDialog(card));
}

function hideCardDetailDialog() {
    hideDialog("card-detail-dialog");
    $(".arrow-left").css("visibility", "hidden");
    $(".arrow-right").css("visibility", "hidden");
    $("#card-detail-loading-figure").css("visibility", "hidden");
    $("#card-detail-figure").css("visibility", "hidden");
}

function updateSkillDisplay() {
    // reset, otherwise if the below if is not executed we'll still show stale text (e.g. of the previous fam)
    $(".card-detail-skill-name").text("");
    $(".card-detail-skill-description").text("");
    if (currentCard.skills[currentSkillIndex]) {
        $(".card-detail-skill-name").text(unescape(currentCard.skills[currentSkillIndex].name));
        $(".card-detail-skill-description").text(unescape(currentCard.skills[currentSkillIndex].comment));
    }
    $(".arrow-left").css("visibility", "hidden");
    $(".arrow-right").css("visibility", "hidden");
    if (currentCard.skills[currentSkillIndex + 1] && currentCard.skills[currentSkillIndex + 1].name) {
        $(".arrow-right").css("visibility", "visible");
    }
    if (currentCard.skills[currentSkillIndex - 1] && currentCard.skills[currentSkillIndex - 1].name) {
        $(".arrow-left").css("visibility", "visible");
    }
    if (currentCard.skills[currentSkillIndex] && currentCard.skills[currentSkillIndex].name) {
        $(".card-detail-skill-proc").text(currentCard.skills[currentSkillIndex].maxProbability + "%");
    }
}

function showDialog(dialogId) {
    var target = document.getElementById(dialogId);
    target.style.visibility = 'visible';
    var bg = document.getElementById('dialogBack');
    bg.style.width = window.innerWidth + 'px';
    bg.style.visibility = 'visible';
    document.getElementById(dialogId).style.visibility = 'visible';
    return target;
}

function hideDialog(dialogId) {
    var bg = document.getElementById('dialogBack');
    bg.style.visibility = 'hidden';
    var target = document.getElementById(dialogId);
    target.style.visibility = 'hidden';
}

function getRarityClassName(rarity, evolution, maxEvolution) {
    switch (rarity) {
        case 4:
            return "card-figure-rarity-ep-" + evolution + "-" + maxEvolution;
        case 5:
            return "card-figure-rarity-l-" + evolution + "-" + maxEvolution;
        default:
            return "";
    }
}

function getGrowthName(growthType) {
    switch (growthType) {
        case 2:
            return "Fast";
        case 1:
            return "Normal";
        case 3:
            return "Late Bloomer";
        default:
            return "???";
    }
}

function prevSkill() {
    currentSkillIndex--;
    updateSkillDisplay();
}

function nextSkill() {
    currentSkillIndex++;
    updateSkillDisplay();
}


text:
#include "Command.h"

Command::Command() {}

Command::Command(string command) {
    string tempCmd;
    size_t x = command.find(" ");
    char* tempCmdCStr = new char[500];

    if (x == string::npos) //npos is a static member constant value with the greatest
    {                           // possible value for an element of type size_t.
        this->command = command;
    }
    else
    {
        tempCmd = command;

        this->command = tempCmd.substr(0, x);
        tempCmd.erase(0, x + 1);
        strcpy(tempCmdCStr, tempCmd.c_str());
        char* temp= strtok(tempCmdCStr, " ");

        while (temp != NULL)
        {
            user_flags.push_back(temp);
            temp = strtok(NULL, " ");
        }
    }
    /*
        command = the string upto the first space
        user_flags = vector of char* that is composed of everything after the initial command
    */
}

bool Command::run() {
    if (command == "exit") {
        exit(EXIT_SUCCESS);
    }

    int status;
    bool ran = true;
    char* x[500];
    char* temp = new char[100];

    strcpy(temp, command.c_str());  //copies command.c_str() onto temp with a NULL at the end
    x[0] = temp;

    if (user_flags.size() != 0)
    {
		for (unsigned i = 1; i <= user_flags.size(); ++i)
		{
			x[i] = user_flags[i - 1];
		}
    }

    x[user_flags.size() + 1] = NULL;
    pid_t pid = fork();
    /*
    Description: fork creates a child process that differs from the parent process only in its PID and
    PPID, and in the fact that resource utilizations are set to 0. File locks and pending signals
    are not inherited.

    Returns: On success, the PID of the child process is returned in the parent's thread of execution,
    and a 0 is returned in the child's thread of execution.

    */

    if (pid == -1) //fork failed
    {
        ran = false;
        perror("fork() has failed");
        exit(EXIT_FAILURE);
    }
    else if (pid == 0)  //This is done by the child process.
    {
        // char const* fileName = "output.txt";
        // int fd = open(fileName, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
        // dup2(fd, 1);   // make stdout go to file
        int blue = execvp(command.c_str(), x);
        // close(fd);
        if (blue == -1)   ///* If execvp returns, it must have failed. */
        {
            ran = false;
            perror("execvp() has failed");
            exit(EXIT_FAILURE);
        }
    }
    else if (pid > 0)       /* This is run by the parent.  Wait for the child to terminate. */
    {
        if (waitpid(pid, &status, 0) == -1) //waiting for the child
        {
            perror("wait() has failed");
        }

        if (WIFEXITED(status) == 1) //returns a nonzero value if the child process terminated normally with exit or _exit.
        {
            if (WEXITSTATUS(status) != 0) //WEXITSTATUS returns the child's exit status.
            {
                ran = false;
            }
        }
    }

    return ran;
}


text:
<?php

defined ( '_JEXEC' ) or die ();

// Disable caching
$this->cache = false;

// Show one topic row
?>
<?php if ($this->spacing) : ?>

	<td class="kcontenttablespacer" colspan="<?php echo empty($this->topicActions) ? 5 : 6 ?>">

<?php endif; ?>

<tr class="<?php echo $this->getTopicClass('k', 'row') ?>">

		<?php echo $this->formatLargeNumber ( max(0,$this->topic->getTotal()-1) ); ?> <?php echo JText::_('COM_KUNENA_GEN_REPLIES') ?>

		<?php echo $this->getTopicLink ( $this->topic, 'unread', $this->topic->getIcon() ) ?>

		<?php if ($this->topic->attachments) echo $this->getIcon ( 'ktopicattach', JText::_('COM_KUNENA_ATTACH') ); ?>
		<?php if ($this->topic->poll_id) echo $this->getIcon ( 'ktopicpoll', JText::_('COM_KUNENA_ADMIN_POLLS') ); ?>

			<?php
			echo $this->getTopicLink ( $this->topic, null, null, KunenaHtmlParser::stripBBCode ( $this->topic->first_post_message, 500), 'ktopic-title km' );
			if ($this->topic->getUserTopic()->favorite) {
				echo $this->getIcon ( 'kfavoritestar', JText::_('COM_KUNENA_FAVORITE') );
			}
			if ($this->topic->unread) {
				echo $this->getTopicLink ( $this->topic, 'unread', '(' . $this->topic->unread . ' ' . JText::_('COM_KUNENA_A_GEN_NEWCHAR') . ')' );
			}
			if ($this->topic->locked != 0) {
				echo $this->getIcon ( 'ktopiclocked', JText::_('COM_KUNENA_LOCKED_TOPIC') );
			}
			?>

			 <?php echo JText::sprintf('COM_KUNENA_CATEGORY_X', $this->getCategoryLink ( $this->topic->getCategory() ) ) ?>

			<span class="ktopic-posted-time" title="<?php echo KunenaDate::getInstance($this->topic->first_post_time)->toKunena('config_post_dateformat_hover'); ?>">
				<?php echo JText::_('COM_KUNENA_TOPIC_STARTED_ON') . ' ' . KunenaDate::getInstance($this->topic->first_post_time)->toKunena('config_post_dateformat');?>

			<?php echo JText::_('COM_KUNENA_BY') . ' ' . $this->topic->getFirstPostAuthor()->getLink() ?>

		<?php if ($this->pages > 1) : ?>

<?php echo JText::_('COM_KUNENA_PAGE') ?>

<?php echo $this->GetTopicLink ( $this->topic, 0, 1 ) ?>

			<?php if ($this->pages > 4) : $startPage = $this->pages - 3; ?>

...

			<?php else: $startPage = 1; endif;
			for($hopPage = $startPage; $hopPage < $this->pages; $hopPage ++) : ?>

<?php echo $this->getTopicLink ( $this->topic, $hopPage, $hopPage+1 ) ?>

			<?php endfor; ?>

		<?php endif; ?>

		<?php if (!empty($this->keywords)) : ?>

			<?php echo JText::sprintf('COM_KUNENA_TOPIC_TAGS', $this->escape($this->keywords)) ?>

		<?php endif; ?>

		<?php echo $this->formatLargeNumber ( $this->topic->hits );?>
		 <?php echo JText::_('COM_KUNENA_GEN_HITS');?>

			<?php if (!empty($this->topic->avatar)) : ?>
			 <?php echo $this->topic->getLastPostAuthor()->getLink( $this->topic->avatar ) ?>
			<?php endif; ?>

			<?php
			echo $this->getTopicLink ( $this->topic, 'last', JText::_('COM_KUNENA_GEN_LAST_POST') );
			echo ' ' . JText::_('COM_KUNENA_BY') . ' ' . $this->topic->getLastPostAuthor()->getLink();
			?>

			<span class="ktopic-date" title="<?php echo KunenaDate::getInstance($this->topic->last_post_time)->toKunena('config_post_dateformat_hover'); ?>">
				<?php echo KunenaDate::getInstance($this->topic->last_post_time)->toKunena('config_post_dateformat'); ?>

<?php if (!empty($this->topicActions)) : ?>
	<input class ="kcheck" type="checkbox" name="topics[<?php echo $this->topic->id?>]" value="1" />
<?php endif; ?>

<?php if ($this->module) : ?>

	<td class="ktopicmodule" colspan="<?php echo empty($this->topicActions) ? 5 : 6 ?>"><?php echo $this->module; ?>

<?php endif; ?>


text:
namespace sheaf
{

///
/// Ids for standard poset members.
///
enum primitives_schema_member_index
{
  PRIMITIVES_SCHEMA_MEMBER_INDEX_BEGIN = 2, // Must be same as first std id.
  SIZE_INDEX = 2,
  ALIGNMENT_INDEX, // 3
  INDEX_INDEX, // 4
  PRIMITIVES_SCHEMA_MEMBER_INDEX_END, // Must be one more than last std id.
  NOT_A_PRIMITIVES_SCHEMA_MEMBER_INDEX = INT_MAX
};

///
/// Number of dofs defined by primitives schema
///
const int PRIMITIVES_SCHEMA_DOF_CT =
  PRIMITIVES_SCHEMA_MEMBER_INDEX_END - PRIMITIVES_SCHEMA_MEMBER_INDEX_BEGIN;

///
/// Prefix increment operator for primitives_schema_member_index.
///
SHEAF_DLL_SPEC primitives_schema_member_index& operator++(primitives_schema_member_index& x);

///
/// The name of the enumerator xpt.
///
SHEAF_DLL_SPEC const std::string& primitives_schema_member_index_to_name(primitives_schema_member_index xpt);

///
/// The enumerator with name xname.
///
SHEAF_DLL_SPEC primitives_schema_member_index primitives_schema_member_index_from_name(const std::string& xname);

///
/// The enumerator corresponding to primitive index xindex.
///
SHEAF_DLL_SPEC primitives_schema_member_index primitives_schema_member_index_from_index(pod_index_type xindex);

///
/// True if xindex is a valid primitive index.
///
SHEAF_DLL_SPEC bool is_primitives_schema_member_index(pod_index_type xindex);

} // namespace sheaf

#endif // ifndef PRIMITIVES_SCHEMA_MEMBER_INDEX_H


text:
using UnityEngine;
using UnityEditor;
using System.Collections;
// DEPRECATED
public class OTPrefabBreaker : Editor
{
}
#endif


text:
@implementation NSDate_PrettyDateTests {
    NSString *expects, *result;
}

- (void)setUp
{
    [super setUp];
    // Set-up code here.
}

- (void)tearDown
{
    // Tear-down code here.
    [super tearDown];
}

- (void)testPrettyDateFuture {
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:5];
    result = [date prettyDate];
    expects = @"future date";
    STAssertTrue([result isEqualToString:expects], [NSString stringWithFormat:@"Expected '%@' got '%@'", expects, result]);
}

- (void)testPrettyDateJustNow
{
    NSDate *date = [NSDate date];
    result = [date prettyDate];
    expects = @"just now";
    STAssertTrue([result isEqualToString:expects], [NSString stringWithFormat:@"Expected '%@' got '%@'", expects, result]);
}

- (void)testPrettyDateSeconds
{
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:-30];
    result = [date prettyDate];
    expects = @"30 seconds ago";
    STAssertTrue([result isEqualToString:expects], [NSString stringWithFormat:@"Expected '%@' got '%@'", expects, result]);
}

- (void)testPrettyDateMinutes
{
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:-60];
    result = [date prettyDate];
    expects = @"a minute ago";
    STAssertTrue([result isEqualToString:expects], [NSString stringWithFormat:@"Expected '%@' got '%@'", expects, result]);
}

- (void)testPrettyDateHours
{
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:-3600];
    result = [date prettyDate];
    expects = @"last hour";
    STAssertTrue([result isEqualToString:expects], [NSString stringWithFormat:@"Expected '%@' got '%@'", expects, result]);
}

- (void)testPrettyDateYesterday
{
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:-86400];
    result = [date prettyDate];
    expects = @"yesterday";
    STAssertTrue([result isEqualToString:expects], [NSString stringWithFormat:@"Expected '%@' got '%@'", expects, result]);
}

- (void)testPrettyDateDays
{
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:-172800];
    result = [date prettyDate];
    expects = @"2 days ago";
    STAssertTrue([result isEqualToString:expects], [NSString stringWithFormat:@"Expected '%@' got '%@'", expects, result]);
}

@end


text:
public record Rect(Point point1, Point point) {
}


text:
using UnityEngine;
using System.Collections;

public class EJ_ButtonEvent : MonoBehaviour {

	public UITweener MyTween;

	public void OnTrigger(){
		MyTween.PlayForward();
	}

	public void OnClick(){
		MyTween.PlayForward();
	}

	public void OnExit(){
		MyTween.PlayReverse ();
	}

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}
}


text: Rails.application.config.middleware.delete Rack::Deflater


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Model\Action;

use Oro\Component\Action\Action\AbstractAction as BaseAbstractAction;

/**
 * @deprecated since 1.10. Use {@see Oro\Component\Action\Action\AbstractAction} instead
 */
abstract class AbstractAction extends BaseAbstractAction
{
}