text:
.head{
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    line-height: 44px;
    height: 44px;
    background: #fff;
    border-bottom: 1px solid #ddd;
    color: #000;
    z-index: 100;
}
.head .title{
    font-size: 14px;
    text-align: center;
    padding: 0 44px;
}
.head .left{
    position: absolute;
    width: 44px;
    left: 0;
    top: 0;
    bottom: 0;
    text-align: center;
    color: #333;
}
.head .right{
    width: 20px;
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    text-align: center;
    color: #333;
}.link-right{
    display: block;
    position: relative;
    line-height: 45px;
    padding-left: 15px;
    padding-right: 12px;
    border-bottom: 1px solid #eeeeee;
    border-top: 1px solid #eeeeee;
    font-size: 14px;
    color: #6b6b6b;
    background: #fff;
}
.link-right .triangle{
    position: absolute;
    right: 12px;
    top:0;
    bottom:0;
    vertical-align: middle;
}
.link-right .triangle span:first-child{padding-right: 5px;vertical-align: middle;}
.link-right .triangle span.font{color: #999;vertical-align: middle;}
.link-right+.link-right{
    border-top: none;
}/*btn*/
.btn{ display:inline-block; padding:0 12px; cursor:pointer;height:30px;line-height:28px; font-size:14px; text-align:center; white-space:nowrap; vertical-align:middle; border:none}
.btn:focus{ outline:thin dotted; outline:5px auto -webkit-focus-ring-color; outline-offset:-2px; }
.btn:focus, .btn:active, .btn.active, .btn.disabled, .btn[disabled]{ text-decoration:none; }

.btn.btn-default{
    background-color: #e3e3e3 ;
    color: #555 ;
}
.btn-default:hover, .btn-default:focus, .btn-default:active, .btn-default.active, .btn-default.disabled, .btn-default[disabled]{ color: #555 ; background-color:#dad8d8;}

/*主要*/
.btn-primary{
    color:#fff;
    background-color:#0085d0;
}
.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .btn-primary.disabled, .btn-primary[disabled]{ color:#fff; background-color:#0379bb;}

/*信息*/
.btn-info{ color:#fff; text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25); background-color:#2f96b4; }
.btn-info:hover, .btn-info:focus, .btn-info:active, .btn-info.active, .btn-info.disabled, .btn-info[disabled]{ color:#fff; background-color:#2f96b4; *background-color:#2a85a0 }
/*成功*/
.btn-success{ color:#fff; text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25); background-color:#51a351;}
.btn-success:hover, .btn-success:focus, .btn-success:active, .btn-success.active, .btn-success.disabled, .btn-success[disabled]{ color:#fff; background-color:#51a351; *background-color:#499249 }

/*按钮尺寸*/
.btn-large{ padding:0 30px; font-size:14px;line-height: 45px; height: 45px;}
.btn-bigger{padding:0 20px; font-size:12px;line-height: 36px; height: 36px;}
.btn-big{ padding:0 15px; font-size:12px; line-height: 30px;height:30px;}
.btn-smaller{ padding:0 10px; font-size:12px; line-height: 23px;height: 23px;}
.btn-small{ padding:0 10px; font-size:12px; line-height: 20px;height: 20px;}
.btn-mini{ padding:0 6px; font-size:10px; line-height: 14px;height: 14px;}
/*块级按钮*/
.btn-block{ -moz-box-sizing:border-box; display:block; padding-left:0; padding-right:0; width:100%; }.user .body{
    padding: 60px 0 20px;
}
.user .btn-box{
    padding: 20px 15px;
}
/*.order .rc-tabs-top{overflow: visible !important;}*/
.order .rc-tabs-nav-container{
    background: #fff;
}
.order .rc-tabs-ink-bar{
    background: #90c41f;
}
.order .rc-tabs-tab-active,.order .rc-tabs-tab-active:hover{color: #90c41f}
.order .rc-tabs-top{border: none}

.order-item {
    padding-top: 15px;
    /*border-top: 1px solid #ddd;*/
    border-bottom: 1px solid #eee;
}
/*.order-item+.order-item{border-top:none;}*/
.order-item .header{
    position: relative;
    line-height: 40px;
    vertical-align: middle;
    padding: 0 10px;
    box-sizing: border-box;
    background: #fff;
    text-align: right;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
}
.order-item .left{
    position: absolute;
    left: 10px;
    top: 0;
    bottom: 0;
    right: 0;
    line-height: 40px;
    vertical-align: middle;
    text-align: left;
}
.order-item .warning{
   color: #fe0103;
}
.order-item .success{
    color: red;
}

.order-item .body{
    position: relative;
    padding:8px 12px;
    background:#f8f8f8;
    min-height: 80px;

}
.order-item .body img{
    position: absolute;
    width: 80px;
    height: 80px;
    left: 12px;
    top: 8px;
}
.order-item .body .right-box{
    margin-left: 80px;
    padding: 10px;
}
.order-item .right-box h3{
    font-size: 14px;
    line-height: 18px;
    color: #333;
}
.order-item .right-box p{
    font-size: 12px;
    padding-top: 8px;
    color: #666;
}

.order-item .foot{
    padding: 0 12px;
    line-height: 30px;
    text-align: right;
    color: #5d5d5d;
    background: #fff;
}.form-items{
    border-top:1px solid #ddd;
    padding-top: 50px;
}

.form-item{
    border-bottom:1px solid #ddd;
    background: #fff;
    line-height: 44px;
    display: flex;
    align-items:center;
    display: -webkit-flex;
    color: #333;
}
.form-item label{
    padding-left: 10px;
    box-sizing: border-box;
    -webkit-flex:1;
    -moz-flex:1;
    flex:1;
    color: #000;
}

.form-item input,.form-item span{
    -webkit-flex:5;
    -moz-flex:5;
    flex:5;
    display: flex;
    display: -webkit-flex;
    border: none;
}
.form-item span span{
    display: flex;
    display: -webkit-flex;
    -webkit-flex:1;
    -moz-flex:1;
    flex:1;
}
.form-item input{
    box-sizing: border-box;
    padding: 5px 10px;
    line-height: 44px;
}
.form-items .tips{
    padding: 10px 15px 0;
    color: #999;
}
.form-items .tips.error,.form-items .tips .error{
    color: #ec0c0c;
}
.form-items .btn-box{
    padding: 15px 0 0 15px;
}

/*# sourceMappingURL=css_3.css.map?4dffa274*/


text:
from cachel import compat

if compat.ASYNC_AWAIT:
    from ._test_simple_async import *

redpajama_set_name: RedPajamaGithub


text:
/**

	File:		osutil.c

	Project:	DCPU-16 Toolchain
	Component:	LibDCPU

	Authors:	James Rhodes

	Description:	Defines functions for interacting with the
			local operating system (such as getting
			directory names, etc.)

**/

#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#else
#include <libgen.h>
#endif
#include <stdlib.h>
#include <assert.h>
#include "osutil.h"

bstring osutil_arg0 = NULL;
#ifdef _WIN32
char* dirname(char* path)
{
	// FIXME: This assumes the resulting path will always
	// be shorter than the original (which it should be
	// given that we're only returning a component of it, right?)
	char drive[_MAX_DRIVE];
	char dir[_MAX_DIR];
	_splitpath(path, drive, dir, NULL, NULL);
	strcpy(path, drive);
	strcpy(path + strlen(path), dir);
	return path;
}
#endif

///
/// Returns the directory name component of the specified path.
///
/// Returns the directory component of the specified path in a
/// cross-platform manner.
///
/// @param path The path to retrieve the directory name of.
/// @return The directory name component.
///
bstring osutil_dirname(bstring path)
{
	bstring bpath;
	char* cpath;
	char* opath;

	cpath = bstr2cstr(path, '0');
	// needs to return in case of dirname implementation not changing parameter
	// in particular this doesn't work on OS X check $ man 3 dirname
	opath = dirname(cpath);
	bpath = bfromcstr(opath);
	bcstrfree(cpath);

	return bpath;
}

///
/// Sets the specified file handler to binary mode.
///
/// On some platforms (Windows), file descriptors are opened in text
/// mode by default.  In particular, on these platforms, standard
/// input, output and error are all text mode by default which causes
/// issues when outputting emulator bytecode to these descriptors.
/// This function sets a file descriptor into binary mode in a
/// cross-platform manner.
///
/// @param fd The file descriptor to switch into binary mode.
///
void osutil_makebinary(FILE* fd)
{
#ifdef _WIN32
	_setmode(_fileno(stdout), _O_BINARY);
#endif
}

///
/// Stores the application path in a global context.
///
/// Stores the application path (arg0) in a global context so that
/// libraries can retrieve it later using osutil_getarg0.  All applications
/// using a DCPU-16 Toolchain library should invoke this method after
/// parsing their arguments.  If this value is not set, some libraries
/// may be unable to resolve their required runtime components.
///
/// @param arg0 The string containing argument 0.
///
void osutil_setarg0(freed_bstring arg0)
{
	if (osutil_arg0 != NULL)
		bdestroy(osutil_arg0);
	osutil_arg0 = bstrcpy(arg0.ref);
	bautodestroy(arg0);
}

///
/// Retrieves the current path to the application.
///
/// Retrieves the previously stored path to the application and
/// returns a copy of the internal string.
///
/// @return A copy of the current path to the application.  The result
///	    must be freed manually.
///
bstring osutil_getarg0()
{
	assert(osutil_arg0 != NULL);

	return bstrcpy(osutil_arg0);
}

///
/// Retrieves the current directory that the application executable is located in.
///
/// Retrieves the previously stored path to the application, resolves the directory
/// using os_dirname and returns a copy of the directory the application is contained in.
///
/// @return The path of the directory containing the application.  The result must be freed manually.
///
bstring osutil_getarg0path()
{
	bstring arg0 = osutil_getarg0();
	bstring path = osutil_dirname(arg0);
	bdestroy(arg0);
	return path;
}


text:
#region

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

#endregion

namespace Tabster.Data
{
    public class TablaturePlaylistItem
    {
        public TablaturePlaylistItem(ITablatureFile file, FileInfo fileInfo)
        {
            File = file;
            FileInfo = fileInfo;
        }

        public ITablatureFile File { get; private set; }
        public FileInfo FileInfo { get; private set; }
    }

    public class TablaturePlaylist : IEnumerable<TablaturePlaylistItem>
    {
        private readonly List<TablaturePlaylistItem> _items = new List<TablaturePlaylistItem>();

        public TablaturePlaylist(string name)
        {
            Name = name;
        }

        #region Tablature Methods

        public void Add(TablaturePlaylistItem item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            _items.Add(item);
        }

        public bool Remove(TablaturePlaylistItem item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            return _items.Remove(item);
        }

        public bool Remove(string path)
        {
            if (path == null)
                throw new ArgumentNullException("path");

            return Remove(Find(x => x.FileInfo.FullName.Equals(path)));
        }

        public TablaturePlaylistItem Find(Predicate<TablaturePlaylistItem> match)
        {
            if (match == null)
                throw new ArgumentNullException("match");

            return _items.Find(match);
        }

        public List<TablaturePlaylistItem> FindAll(Predicate<TablaturePlaylistItem> match)
        {
            if (match == null)
                throw new ArgumentNullException("match");

            return _items.FindAll(match);
        }

        public TablaturePlaylistItem Find(ITablatureFile file)
        {
            if (file == null)
                throw new ArgumentNullException("file");

            return _items.Find(x => x.File.Equals(file));
        }

        public TablaturePlaylistItem Find(string path)
        {
            if (path == null)
                throw new ArgumentNullException("path");

            return _items.Find(x => x.FileInfo.FullName.Equals(path, StringComparison.OrdinalIgnoreCase));
        }

        public List<TablaturePlaylistItem> GetTablatureItems()
        {
            return new List<TablaturePlaylistItem>(_items);
        }

        #endregion

        #region Implementation of IEnumerable

        public IEnumerator<TablaturePlaylistItem> GetEnumerator()
        {
            return ((IEnumerable<TablaturePlaylistItem>) _items).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion

        public string Name { get; set; }

        public long? Id { get; set; }

        public DateTime? Created { get; set; }

        public int Count
        {
            get { return _items.Count; }
        }
    }
}


text:
package io.github.azagniotov.stubby4j;

import io.github.azagniotov.stubby4j.server.ssl.SslUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
import org.apache.http.ssl.SSLContexts;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http2.client.HTTP2Client;
import org.eclipse.jetty.http2.client.http.HttpClientTransportOverHTTP2;
import org.eclipse.jetty.util.ssl.SslContextFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.net.ProxySelector;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

import static java.util.Arrays.asList;

public final class HttpClientUtils {

    private HttpClientUtils() {

    }

    static CloseableHttpClient buildHttpClient(final String tlsVersion) throws Exception {
        return buildHttpClient(tlsVersion, buildSSLContextWithRemoteCertificateLoaded(tlsVersion));
    }

    private static CloseableHttpClient buildHttpClient(final String tlsVersion, final SSLContext sslContext) throws Exception {

        System.out.println("Running tests using TLS version: " + tlsVersion);

        SSLEngine engine = sslContext.createSSLEngine();
        engine.setEnabledProtocols(new String[]{tlsVersion});
        System.out.println("SSLEngine [client] enabled protocols: ");
        System.out.println(new HashSet<>(asList(engine.getEnabledProtocols())));

        final SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslContext,
                new DefaultHostnameVerifier());

        return HttpClientBuilder.create()
                .setDefaultRequestConfig(RequestConfig
                        .custom()
                        .setSocketTimeout(45000)
                        .setConnectTimeout(45000)
                        .build())
                // When .useSystemProperties(), the FakeX509TrustManager gets exercised
                //.useSystemProperties()
                .setSSLSocketFactory(sslSocketFactory)
                .setMaxConnTotal(200)
                .setMaxConnPerRoute(20)
                .setConnectionTimeToLive(-1, TimeUnit.MILLISECONDS)
                .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
                .disableRedirectHandling()

                // In ProxyConfigWithStubsTest.shouldReturnProxiedRequestResponse_WhenStubsWereNotMatched():
                //
                // I had to set this header to avoid "Not in GZIP format java.util.zip.ZipException: Not in GZIP format" error:
                // The 'null' overrides the default value "gzip", also I had to .disableContentCompression() on WEB_CLIENT
                .disableContentCompression()
                .disableAutomaticRetries()
                .build();
    }

    static SSLContext buildSSLContextWithRemoteCertificateLoaded(final String tlsVersion) throws Exception {
        //
        // 1. Download and save the remote self-signed certificate from the stubby4j server with TLS at localhost:7443
        //    This opens an SSL connection to the specified hostname and port and prints the SSL certificate.
        // ---------------------------------------------------------------------------------
        // $ echo quit | openssl s_client -showcerts -servername localhost -connect "localhost":7443 > FILE_NAME.pem
        //
        //
        // 2. Optionally, you can perform verification using cURL. Note: the -k (or --insecure) option is NOT used
        // ---------------------------------------------------------------------------------
        // $ curl -X GET --cacert FILE_NAME.pem  --tls-max 1.1  https://localhost:7443/hello -v
        //
        //
        // 3. Finally, load the saved self-signed certificate to a keystore
        // ---------------------------------------------------------------------------------
        // $ keytool -import -trustcacerts -alias stubby4j -file FILE_NAME.pem -keystore FILE_NAME.jks
        //
        //
        // 4. Load the generated FILE_NAME.jks file into the trust store of SSLContext, which then can be
        //    used to create an SSL socket factory for your web client. The STUBBY_SELF_SIGNED_TRUST_STORE
        //    was created using the following code:
        //    https://github.com/azagniotov/stubby4j/blob/737f1f16650ce78a9a63f8f3e23c60ba2769cdb4/src/main/java/io/github/azagniotov/stubby4j/server/ssl/SslUtils.java#L168-L172
        // ---------------------------------------------------------------------------------
        return SSLContexts.custom()
                .setProtocol(tlsVersion)
                .loadTrustMaterial(SslUtils.SELF_SIGNED_CERTIFICATE_TRUST_STORE, null)
                .build();
    }

    static SslContextFactory jettyClientSslContextFactory(final String tlsProtocol) {
        final SslContextFactory sslContextFactory = new SslContextFactory.Client();

        sslContextFactory.setEndpointIdentificationAlgorithm("HTTPS");
        sslContextFactory.setProtocol(tlsProtocol);
        sslContextFactory.setTrustStore(SslUtils.SELF_SIGNED_CERTIFICATE_TRUST_STORE);

        return sslContextFactory;
    }

    static HttpClient jettyHttpClientOnHttp11() {
        return new HttpClient();
    }

    static HttpClient jettyHttpClientOnHttp11WithClientSsl(final String tlsProtocol) {
        return new HttpClient(jettyClientSslContextFactory(tlsProtocol));
    }

    static HttpClient jettyHttpClientOnHttp20() {
        final HTTP2Client http2Client = new HTTP2Client();

        final HttpClientTransportOverHTTP2 transport = new HttpClientTransportOverHTTP2(http2Client);

        final HttpClient httpClient = new HttpClient(transport);
        httpClient.setMaxConnectionsPerDestination(4);

        return httpClient;
    }

    static HttpClient jettyHttpClientOnHttp20WithClientSsl(final String tlsProtocol) {
        final SslContextFactory sslContextFactory = jettyClientSslContextFactory(tlsProtocol);

        final HTTP2Client http2Client = new HTTP2Client();
        http2Client.addBean(sslContextFactory);

        final HttpClientTransportOverHTTP2 transport = new HttpClientTransportOverHTTP2(http2Client);
        transport.setUseALPN(true);

        final HttpClient httpClient = new HttpClient(transport, sslContextFactory);
        httpClient.setMaxConnectionsPerDestination(4);

        return httpClient;
    }
}


text:
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("http://mockbin.com/har"))
    .header("content-type", "application/x-www-form-urlencoded")
    .method("POST", HttpRequest.BodyPublishers.ofString("foo=bar&hello=world"))
    .build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../">
  <title data-ice="title">FormioPDFBuilder | formiojs</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

<meta name="description" content="Common js library for client side interaction with <form.io>"><meta property="twitter:card" content="summary"><meta property="twitter:title" content="formiojs"><meta property="twitter:description" content="Common js library for client side interaction with <form.io>">

  Home

  Reference
  Source

    <input class="search-input">

CFormioBuilder

CFormioFormBuilder

CFormioForm

CFormio

CFormioPDFBuilder

CFormioPDF

CFormioWizardBuilder

CFormioWizard

FcreateForm

FformFactory

componentsCFormioComponents

FComponents

VValidator

VFormioComponentsIndex

components/addressCAddressComponent

FAddress

components/address/fixturesVcomponent

Vcomponents

components/baseCBaseComponent

FBase

components/base/editFormVBaseEditAPI

VBaseEditConditional

VBaseEditData

VBaseEditDisplay

VBaseEditLayout

VBaseEditLogic

VBaseEditValidation

VEditFormUtils

components/base/fixturesVcomponent

Vcomponent

Vcomponents

components/buttonCButtonComponent

FButton

components/button/fixturesVcomponent

Vcomponents

components/checkboxCCheckBoxComponent

FCheckbox

components/checkbox/fixturesVcomponent

Vcomponents

components/columnsCColumnComponent

CColumnsComponent

FColumns

components/columns/fixturesVcomponent

Vcomponents

components/containerCContainerComponent

FContainer

components/container/fixturesVcomponent

Vcomponents

components/contentCContentComponent

FContent

components/content/fixturesVcomponent

Vcomponents

components/currencyCCurrencyComponent

FCurrency

components/currency/fixturesVcomponent

Vcomponents

components/datagridCDataGridComponent

FDataGrid

components/datagrid/fixturesVcomponent

Vcomponents

components/datetimeCDateTimeComponent

FDateTime

components/datetime/fixturesVcomponent

Vcomponents

components/dayCDayComponent

FDay

components/day/fixturesVcomponent

Vcomponents

components/editgridCEditGridComponent

FEditGrid

components/editgrid/fixturesVcomponent

Vcomponent

Vcomponents

components/emailCEmailComponent

FEmail

components/email/fixturesVcomponent

Vcomponents

components/fieldsetCFieldsetComponent

FFieldset

components/fieldset/fixturesVcomponent

Vcomponents

components/fileCFileComponent

FFile

components/formCFormComponent

FForm

components/form/fixturesVcomponent

Vcomponent

Vcomponents

components/hiddenCHiddenComponent

FHidden

components/hidden/fixturesVcomponent

Vcomponents

components/htmlCHTMLComponent

FHTML

components/html/fixturesVcomponent

Vcomponents

components/locationCLocationComponent

FLocation

components/location/fixturesVcomponent

Vcomponents

components/numberCNumberComponent

FNumber

components/number/fixturesVcomponent

Vcomponent

Vcomponents

components/panelCPanelComponent

FPanel

components/panel/fixturesVcomponent

Vcomponents

components/passwordCPasswordComponent

FPassword

components/password/fixturesVcomponent

Vcomponents

components/phonenumberCPhoneNumberComponent

FPhoneNumber

components/phonenumber/fixturesVcomponent

Vcomponents

components/radioCRadioComponent

FRadio

components/radio/fixturesVcomponent

Vcomponents

components/resourceCResourceComponent

FResource

components/resource/fixturesVcomponent

Vcomponents

components/selectCSelectComponent

FSelect

components/select/fixturesVcomponent

Vcomponent

Vcomponents

components/selectboxesCSelectBoxesComponent

FSelectBoxes

components/selectboxes/fixturesVcomponent

Vcomponent

Vcomponents

components/signatureCSignatureComponent

FSignature

components/signature/fixturesVcomponent

Vcomponents

components/surveyCSurveyComponent

FSurvey

components/survey/fixturesVcomponent

Vcomponents

components/tableCTableComponent

FTable

VTableEditOptions

components/table/fixturesVcomponent

Vcomponents

components/tabsCTabsComponent

FTabs

components/tagsCTagsComponent

FTags

components/tags/fixturesVcomponent

Vcomponents

components/textareaCTextAreaComponent

FTextArea

components/textarea/fixturesVcomponent

Vcomponents

components/textfieldCTextFieldComponent

FTextField

components/textfield/editFormVTextFieldEditDisplay

VTextFieldEditValidation

components/textfield/fixturesVcomponent

Vcomponents

components/timeCTimeComponent

FTime

components/time/fixturesVcomponent

Vcomponents

components/unknownCUnknownComponent

components/wellCWellComponent

FWell

components/well/fixturesVcomponent

Vcomponents

contrib/stripe/checkoutCStripeCheckoutComponent

contrib/stripe/checkout/fixturesVcomponent

Vcomponents

contrib/stripe/stripeCStripeComponent

contrib/stripe/stripe/fixturesVcomponent

Vcomponents

providers/storageFbase64

Fdropbox

Fs3

Furl

utilsVBuilderUtils

VFormioUtils

utils/jsonlogicVlodashOperators

import {FormioPDFBuilder} from 'formiojs/src/formio.pdf.builder.js'

  public
  class

  | source

FormioPDFBuilder

Extends:

src/formio.form.builder~FormioFormBuilder → FormioPDFBuilder

Member Summary

Public Members

      public

          dropZone: *

      public

      get

          dropZoneStyles: string

      public

          isBuilt: boolean

      public

          pdfForm: *

Method Summary

Public Methods

      public

          activateDropZone()

      public

          addBuilderComponent(component: *)

      public

          addComponent(component: *, element: *, data: *, before: *): *

      public

          addComponentTo(parent: *, schema: *, element: *, sibling: *): *

      public

          addDropZone()

      public

          addSubmitButton()

      public

          build()

      public

          clear()

      public

          deleteComponent(component: *): *

      public

          destroy()

      public

          disableDropZone()

      public

          dragStart(event: *, component: *)

      public

          dragStop(event: *, prevX: *, prevY: *): boolean

      public

          redraw()

      public

          refreshDraggable()

      public

          render(): *

      public

          setForm(form: *): *

      public

          updateComponent(component: *): *

Public Members

    public

    dropZone: *

      source

    public

    get

    dropZoneStyles: string

      source

    public

    isBuilt: boolean

      source

    public

    pdfForm: *

      source

Public Methods

    public

    activateDropZone()

      source

    public

    addBuilderComponent(component: *)

      source

Params:

Name	Type	Attribute	Description

      component
      *

    public

    addComponent(component: *, element: *, data: *, before: *): *

      source

Params:

Name	Type	Attribute	Description

      component
      *

      element
      *

      data
      *

      before
      *

Return:

          *

    public

    addComponentTo(parent: *, schema: *, element: *, sibling: *): *

      source

Params:

Name	Type	Attribute	Description

      parent
      *

      schema
      *

      element
      *

      sibling
      *

Return:

          *

    public

    addDropZone()

      source

    public

    addSubmitButton()

      source

    public

    build()

      source

    public

    clear()

      source

    public

    deleteComponent(component: *): *

      source

Params:

Name	Type	Attribute	Description

      component
      *

Return:

          *

    public

    destroy()

      source

    public

    disableDropZone()

      source

    public

    dragStart(event: *, component: *)

      source

Params:

Name	Type	Attribute	Description

      event
      *

      component
      *

    public

    dragStop(event: *, prevX: *, prevY: *): boolean

      source

Params:

Name	Type	Attribute	Description

      event
      *

      prevX
      *

      prevY
      *

Return:

          boolean

    public

    redraw()

      source

    public

    refreshDraggable()

      source

    public

    render(): *

      source

Return:

          *

    public

    setForm(form: *): *

      source

Params:

Name	Type	Attribute	Description

      form
      *

Return:

          *

    public

    updateComponent(component: *): *

      source

Params:

Name	Type	Attribute	Description

      component
      *

Return:

          *

  Generated by ESDoc(1.1.0)


text:
%% Demonstration of the Central Limit Theorem, based on Bishop 2.6
%
%%

% This file is from pmtk3.googlecode.com

function centralLimitDemo

samples = 100000;
bins = 20;
N = [1 5 10];
for i=1:length(N)
   figure(i);
   convolutionHist(N(i),samples,bins);
   printPmtkFigure(sprintf('cltBeta%d', N(i)));
end

%%
%Plot a normalized histogram of 'N' i.i.d. standard uniform samples of size
%'sampleSize' using the specified number of bins.
function convolutionHist(N,sampleSize,bins)
%X = mean(rand(sampleSize,N),2);
a = 1; b = 5;
X = mean(betarnd(a, b,sampleSize,N),2);
[counts binLocations] = hist(X,bins);
counts = counts / (sampleSize/bins); %Normalize counts
bar(binLocations,counts);
axis([0 1 0 3])
set(gca,'XTick',[0 0.5 1]);
set(gca,'YTick',0:3);
%text(0.1,2.7,['N = ',num2str(N)],'FontSize',14);
title(sprintf('N = %d', N), 'fontsize', 14)
end
end


text:
namespace Google.Cloud.Datastream.V1Alpha1.Snippets
{
    // [START datastream_v1alpha1_generated_Datastream_CreateRoute_async_flattened]
    using Google.Cloud.Datastream.V1Alpha1;
    using Google.LongRunning;
    using System.Threading.Tasks;

    public sealed partial class GeneratedDatastreamClientSnippets
    {
        /// <summary>Snippet for CreateRouteAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task CreateRouteAsync()
        {
            // Create client
            DatastreamClient datastreamClient = await DatastreamClient.CreateAsync();
            // Initialize request argument(s)
            string parent = "projects/[PROJECT]/locations/[LOCATION]/privateConnections/[PRIVATE_CONNECTION]";
            Route route = new Route();
            string routeId = "";
            // Make the request
            Operation<Route, OperationMetadata> response = await datastreamClient.CreateRouteAsync(parent, route, routeId);

            // Poll until the returned long-running operation is complete
            Operation<Route, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Route result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation<Route, OperationMetadata> retrievedResponse = await datastreamClient.PollOnceCreateRouteAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Route retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END datastream_v1alpha1_generated_Datastream_CreateRoute_async_flattened]
}


text:
import { Column, Separator } from "@artsy/palette"
import React from "react"
import { createFragmentContainer, graphql } from "react-relay"
import { SectionContainer } from "./SectionContainer"
import { UserBidHistory_me$data } from "__generated__/UserBidHistory_me.graphql"
import { SettingsAuctionsLotStandingFragmentContainer } from "./SettingsAuctionsLotStanding"

interface UserBidHistoryProps {
  me: UserBidHistory_me$data
}

export const UserBidHistory: React.FC<UserBidHistoryProps> = ({
  me: { inactiveLotStandings: lotStandings },
}) => {
  if (!lotStandings || lotStandings.length === 0) {
    return <SectionContainer title="Bid History"></SectionContainer>
  }

  return (
    <SectionContainer title="Bid History">
      {lotStandings.map((lotStanding, i) => {
        if (!lotStanding) return null

        return (
          <React.Fragment key={i}>
            <SettingsAuctionsLotStandingFragmentContainer
              lotStanding={lotStanding}
            />

            {i !== lotStandings.length - 1 && (
              <Column span={12}>
                <Separator />
              </Column>
            )}
          </React.Fragment>
        )
      })}
    </SectionContainer>
  )
}

export const UserBidHistoryFragmentContainer = createFragmentContainer(
  UserBidHistory,
  {
    me: graphql`
      fragment UserBidHistory_me on Me {
        inactiveLotStandings: lotStandings(live: false) {
          ...SettingsAuctionsLotStanding_lotStanding
        }
      }
    `,
  }
)


text:
import sys
import os
sys.path.insert(0, os.path.abspath('..'))

import pso


text:
<?php

namespace GameAffinity\BackendBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class DesarrolladorType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nombre')
            ->add('slug')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'GameAffinity\DesarrolladorBundle\Entity\Desarrollador'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'gameaffinity_backendbundle_desarrollador';
    }
}


text:
CREATE TEMPORARY TABLE songs_backup(id, path, parent, track_number, disc_number, title, artist, album_artist, year, album, artwork, duration);
INSERT INTO songs_backup SELECT id, path, parent, track_number, disc_number, title, artist, album_artist, year, album, artwork, duration FROM songs;
DROP TABLE songs;
CREATE TABLE songs (
	id INTEGER PRIMARY KEY NOT NULL,
	path TEXT NOT NULL,
	parent TEXT NOT NULL,
	track_number INTEGER,
	disc_number INTEGER,
	title TEXT,
	artist TEXT,
	album_artist TEXT,
	year INTEGER,
	album TEXT,
	artwork TEXT,
  duration INTEGER,
	UNIQUE(path) ON CONFLICT REPLACE
);
INSERT INTO songs SELECT * FROM songs_backup;
DROP TABLE songs_backup;


text:
<?php

namespace Drupal\test_theme;

/**
 * Represents a random class, used to test if themes can provide classes.
 */
class ThemeClass {}


text:
package jToolkit4FixedPipeline.image.reader;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: Astemir Eleev
 * Date: 27.01.13
 * Time: 13:36
 * To change this template use File | Settings | File Templates.
 */
public class TargaLoader {
    private static int offset;
    private byte[] imageData;

    public TargaLoader (String pathToFile) {
        try {
            File f = new File(pathToFile);
            imageData = new byte[(int)f.length()];
            BufferedInputStream bufStram = new BufferedInputStream(new FileInputStream(f));
            bufStram.read(imageData);
            bufStram.close();
        } catch (IOException ioexception) {
            Logger.getLogger(TargaLoader.class.getName()).log(Level.WARNING, "io exception", ioexception);
        }
    }

    public BufferedImage getBufferedImage () {
        return decode(imageData);
    }

    public byte[] getByteArrayImage () {
        return ((DataBufferByte)(decode(imageData).getRaster().getDataBuffer())).getData();
    }

    public ByteBuffer getByteBufferImage () {
        byte[] data = ((DataBufferByte)(decode(imageData).getRaster().getDataBuffer())).getData();

        final ByteBuffer bb = ByteBuffer.allocateDirect(data.length);
        bb.order(ByteOrder.nativeOrder());
        bb.put(data, 0, data.length);
        bb.flip();

        return bb;
    }

    public int getImageWidth () {
        return getBufferedImage().getWidth();
    }

    public int getImageHeight () {
        return getBufferedImage().getHeight();
    }

    private BufferedImage decode(byte[] buf) {
        offset = 0;

        // Reading header bytes
        // buf[2]=image type code 0x02=uncompressed BGR or BGRA
        // buf[12]+[13]=width
        // buf[14]+[15]=height
        // buf[16]=image pixel size 0x20=32bit, 0x18=24bit
        // buf{17]=Image Descriptor Byte=0x28 (00101000)=32bit/origin upperleft/non-interleaved
        for (int i=0;i<12;i++)
            read(buf);
        int width = read(buf)+(read(buf)<<8);   // 00,04=1024
        int height = read(buf)+(read(buf)<<8);  // 40,02=576
        read(buf);
        read(buf);

        int n = width*height;
        int[] pixels = new int[n];
        int idx=0;

        if (buf[2]==0x02 && buf[16]==0x20) { // uncompressed BGRA
            while(n>0) {
                int b = read(buf);
                int g = read(buf);
                int r = read(buf);
                int a = read(buf);
                int v = (a<<24) | (r<<16) | (g<<8) | b;
                pixels[idx++] = v;
                n-=1;
            }
        } else if (buf[2]==0x02 && buf[16]==0x18) {  // uncompressed BGR
            while(n>0) {
                int b = read(buf);
                int g = read(buf);
                int r = read(buf);
                int a = 255; // opaque pixel
                int v = (a<<24) | (r<<16) | (g<<8) | b;
                pixels[idx++] = v;
                n-=1;
            }
        } else {
            // RLE compressed
            while (n>0) {
                int nb = read(buf); // num of pixels
                if ((nb&0x80)==0) { // 0x80=dec 128, bits 10000000
                    for (int i=0;i<=nb;i++) {
                        int b = read(buf);
                        int g = read(buf);
                        int r = read(buf);
                        pixels[idx++] = 0xff000000 | (r<<16) | (g<<8) | b;
                    }
                } else {
                    nb &= 0x7f;
                    int b = read(buf);
                    int g = read(buf);
                    int r = read(buf);
                    int v = 0xff000000 | (r<<16) | (g<<8) | b;
                    for (int i=0;i<=nb;i++)
                        pixels[idx++] = v;
                }
                n-=nb+1;
            }
        }

        BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        bimg.setRGB(0, 0, width,height, pixels, 0,width);
        return bimg;
    }

    private static int btoi(byte b) {
        int a = b;
        return (a<0?256+a:a);
    }

    private static int read(byte[] buf) {
        return btoi(buf[offset++]);
    }
}


text:
import axios from 'axios';
/**
 * Validates TAF input in two steps:
 * 1) Check for fallback values
 * 2) Server side validation
 * @param  {object} tafAsObject The TAF JSON to validate
 * @return {object} A report of the validation
 */
const TafValidator = (BACKEND_SERVER_URL, tafAsObject, inputParsingReport) => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: BACKEND_SERVER_URL + '/tafs/verify',
      withCredentials: true,
      data: JSON.stringify(tafAsObject),
      headers: { 'Content-Type': 'application/json' }
    }).then(
      response => {
        if (response.data) {
          let responseJson = response.data;
          if (responseJson.hasOwnProperty('errors') && typeof responseJson.errors === 'string') {
            try {
              responseJson.errors = JSON.parse(responseJson.errors);
            } catch (exception) {
              console.error('Unparseable errors data from response', exception);
            }
          }
          const aggregateReport = {
            message: responseJson.message ? responseJson.message : ' ',
            succeeded: inputParsingReport.succeeded && responseJson.succeeded,
            errors: Object.assign({}, inputParsingReport.errors, responseJson.errors),
            TAC:responseJson.TAC
          };
          resolve(aggregateReport);
          /* this.setState({
            validationReport: aggregateReport
          }); */
        } else {
          resolve(inputParsingReport);
          /* this.setState({
            validationReport: inputParsingReport
          }); */
        }
      }
    ).catch(error => {
      console.error(error);
      const aggregateReport = {
        message: 'Unable to validate, TAF input is not valid',
        subheading: '(Couldn\'t retrieve all validation details.)',
        succeeded: false,
        errors: inputParsingReport.errors,
        TAC: null
      };
      resolve(aggregateReport);
      /* this.setState({
        validationReport: aggregateReport
      }); */
    });
  });
};

export default TafValidator;


text:
<?php

namespace Digbang\Security\Roles;

use Cartalyst\Sentinel\Roles\RoleableInterface;

interface Roleable extends RoleableInterface
{
    /**
     * Add a role to the entity.
     *
     * @param Role $role
     */
    public function addRole(Role $role);

    /**
     * Remove a role from the entity.
     *
     * @param Role $role
     */
    public function removeRole(Role $role);
}


text:
from django.dispatch import receiver
from django.db.models.signals import m2m_changed, post_save

from oscar.core.loading import import_module
import_module('offer.models', ['Voucher'], locals())
import_module('order.models', ['OrderDiscount'], locals())

@receiver(m2m_changed)
def receive_basket_voucher_change(sender, **kwargs):
    if kwargs['model'] == Voucher and kwargs['action'] == 'post_add':
        voucher_id = list(kwargs['pk_set'])[0]
        voucher = Voucher._default_manager.get(pk=voucher_id)
        voucher.num_basket_additions += 1
        voucher.save()

@receiver(post_save, sender=OrderDiscount)
def receive_order_discount_save(sender, instance, **kwargs):
    # Record the amount of discount against the appropriate offers
    # and vouchers
    discount = instance
    if discount.voucher:
        discount.voucher.total_discount += discount.amount
        discount.voucher.save()
    discount.offer.total_discount += discount.amount
    discount.offer.save()


text:
package com.expedia.dsp.data.squeeze.impl.text;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.CombineFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.CombineFileRecordReader;
import org.apache.hadoop.mapreduce.lib.input.CombineFileSplit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;

import java.io.IOException;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.mock;

/**
 * Tests for {@link TextCombineFileInputFormat}
 *
 * @author Yashraj R. Sontakke
 */
@RunWith(PowerMockRunner.class)
public class TextCombineFileInputFormatTest {
    private final JobContext context = mock(JobContext.class);
    private final CombineFileSplit inputSplit = mock(CombineFileSplit.class);
    private final TaskAttemptContext taskAttemptContext = mock(TaskAttemptContext.class);

    @Test
    public void testConstructor() {
        CombineFileInputFormat combineFileInputFormat = new TextCombineFileInputFormat();
        assertTrue(combineFileInputFormat instanceof TextCombineFileInputFormat);
    }

    @Test
    public void testCreateRecordReader() throws IOException {
        TextCombineFileInputFormat combineFileInputFormat = new TextCombineFileInputFormat();
        RecordReader recordReader =  combineFileInputFormat.createRecordReader(inputSplit, taskAttemptContext);
        assertTrue(recordReader instanceof CombineFileRecordReader);
    }

    @Test
    public void testIsSplitable() {
        TextCombineFileInputFormat combineFileInputFormat = new TextCombineFileInputFormat();
        assertFalse(combineFileInputFormat.isSplitable(context, new Path("/soruce/path")));
    }
}


text:
<?php namespace Gzero\Repository;

use Gzero\Entity\User;
use Gzero\Social\SocialException;
use Illuminate\Database\Query\Builder;
use Laravel\Socialite\AbstractUser;

class SocialRepository {

    /**
     * @var string
     */
    private $table = 'social_integrations';
    /**
     * @var Builder
     */
    private $builder;
    /**
     * @var UserRepository
     */
    private $userRepo;

    /**
     * Social repository constructor.
     *
     * @param UserRepository $userRepo User model
     */
    public function __construct(UserRepository $userRepo)
    {
        $this->builder  = \App::make('db');
        $this->userRepo = $userRepo;
    }

    /**
     * Function retrieve social services by the given user id.
     *
     * @param $socialId    int social id
     *
     * @return mixed|static
     */
    public function getSocialId($socialId)
    {
        return $this->newQB()->where('social_id', '=', $socialId)->first();
    }

    /**
     * Function retrieve a user by the given social id and social service name.
     *
     * @param $socialId    int user social id
     * @param $serviceName string name of social service
     *
     * @return User
     */
    public function getUserIdBySocialId($socialId, $serviceName)
    {
        return $this->newQB()->where('social_id', '=', $serviceName . '_' . $socialId)->value('user_id');
    }

    /**
     * Function retrieve social services by the given user id.
     *
     * @param $userId    int user id
     *
     * @return \Illuminate\Support\Collection
     */
    public function getUserSocialIds($userId)
    {
        return $this->newQB()->where('user_id', '=', $userId)->pluck('social_id');
    }

    /**
     * Function creates new user based on social service response and create relation with social integration in database.
     *
     * @param $serviceName    string name of social service
     * @param $response       AbstractUser response data
     *
     * @return User
     * @throws SocialException
     */
    public function createNewUser($serviceName, AbstractUser $response)
    {
        $data         = $this->parseServiceResponse($response);
        $existingUser = $this->userRepo->getByEmail($data['email']);
        // duplicated user verification
        if ($existingUser === null) {
            $data['password'] = str_random(40);
            $user = $this->userRepo->create($data);
            // create relation for new user and social integration
            $this->addSocialRelation($user, $serviceName, $response);
            return $user;
        } else {
            session()->put('url.intended', route('register'));
            throw new SocialException(
                trans('gzero-social::common.email_already_in_use_message', ['service_name' => title_case($serviceName)])
            );
        }
    }

    /**
     * Function adds new social account for existing user.
     *
     * @param $user        User user entity
     * @param $serviceName string name of social service
     * @param $response    AbstractUser response data
     *
     * @return User
     */
    public function addUserSocialAccount(User $user, $serviceName, AbstractUser $response)
    {
        $user->has_social_integrations = true;
        $user->save();
        // create relation for new user and social integration
        $this->addSocialRelation($user, $serviceName, $response);
        return $user;
    }

    /**
     * Function creates relation for given user and social integration.
     *
     * @param $user        User user entity
     * @param $serviceName string name of social service
     * @param $response    AbstractUser response data
     *
     * @return mixed
     */
    public function addSocialRelation(User $user, $serviceName, AbstractUser $response)
    {
        // create relation for new user and social integration
        return $this->newQB()->insert(
            [
                'user_id'    => $user->id,
                'social_id'  => $serviceName . '_' . $response->id,
                'created_at' => \DB::raw('NOW()')
            ]
        );
    }

    /**
     * Database query builder.
     *
     * @return Builder
     */
    private function newQB()
    {
        return $this->builder->table($this->table);
    }

    /**
     * Function parses social service response and prepares user data to insert to database.
     *
     * @param $response AbstractUser response data
     *
     * @return array parsed user data for database insertion
     */
    private function parseServiceResponse(AbstractUser $response)
    {
        $userData = [
            'has_social_integrations' => true,
            'nick'                    => $response->getNickname()
        ];
        // set user email if exists (twitter returns as null)
        if ($response->getEmail()) {
            $userData['email'] = $response->getEmail();
        } else {
            $userData['email'] = uniqid('social_', true); // set unique email placeholder
        }
        // set user first and last name
        $name = explode(" ", $response->getName());
        if (count($name) >= 2) {
            $userData['first_name'] = $name[0];
            $userData['last_name']  = $name[1];
        }

        return $userData;
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('stats', '0005_remove_sortie_score_wo_bonus'),
    ]

    operations = [
        migrations.AddField(
            model_name='score',
            name='type',
            field=models.CharField(editable=False, choices=[('int', 'integer'), ('pct', 'percent')], max_length=3, default='int'),
        ),
        migrations.AlterField(
            model_name='logentry',
            name='type',
            field=models.CharField(choices=[('respawn', 'respawn'), ('end', 'end'), ('takeoff', 'takeoff'), ('landed', 'landed'), ('ditched', 'ditched'), ('crashed', 'crashed'), ('bailout', 'bailout'), ('damaged', 'damaged'), ('wounded', 'wounded'), ('killed', 'killed'), ('destroyed', 'destroyed'), ('shotdown', 'shotdown')], db_index=True, max_length=16),
        ),
    ]


text:
package com.exilant.exility.core;

/**
 * represents a bar chart
 *
 */
class BarChart extends ChartField {
	/**
	 * should we show this as staking
	 */
	boolean stacking = false;
	/**
	 * horizontal or vertical
	 */
	String direction = null;
}


text:
package pl.edu.agh.dsm.monitor.core.model.measurement.complex.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import pl.edu.agh.dsm.monitor.core.model.measurement.complex.ComplexMeasurement;
import pl.edu.agh.dsm.monitor.core.model.measurement.complex.ComplexMeasurementParam;
import pl.edu.agh.dsm.monitor.core.model.measurement.complex.ComplexType;
import pl.edu.agh.dsm.monitor.core.model.measurement.complex.task.annotation.Task;
import pl.edu.agh.dsm.monitor.core.model.measurement.complex.task.annotation.TaskAnnotationParser;
import pl.edu.agh.dsm.monitor.core.model.user.ApplicationUser;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * Created by Tom on 2014-05-29.
 */
@Component("ComplexTasksExecutor")		// because taskExecutor collides with other spring bean name
public class TaskExecutor {

	static final Logger log = LoggerFactory.getLogger(TaskExecutor.class);

	@Autowired
	private ApplicationContext appCtx;
	private List<ComplexMeasurementTask> timeBasedTasks = new ArrayList<>();
	private List<ComplexMeasurementTask> dataBasedTasks = new ArrayList<>();

	private List<ComplexType> availableComplexTypes = new ArrayList<>();
	private Map<String, String> typeCodeBeanNameMap = new HashMap<>();

	@Scheduled(fixedDelay = 5000)
	public void updateTimeBasedTasks() {
		for(ComplexMeasurementTask task : timeBasedTasks) {
			task.update();
		}
	}

	public void updateDataBasedTasks(UUID baseMeasurementId) {
		for(ComplexMeasurementTask task : dataBasedTasks) {
			UUID baseId = task.getComplexMeasurement().getBaseMeasurementId();
			if(baseId.equals(baseMeasurementId)) {
				task.update();
			}
		}
	}

	public void createTask(ComplexMeasurement measurement) throws IllegalArgumentException {
		String beanName = typeCodeBeanNameMap.get(measurement.getType());
		Assert.notNull(beanName, "no such complex type : " + measurement.getType());
		ComplexMeasurementTask task = (ComplexMeasurementTask) appCtx.getBean(beanName, measurement);
		if(task.getUpdateType() == UpdateType.DATA_BASED) {
			dataBasedTasks.add(task);
		} else {
			timeBasedTasks.add(task);
		}
		log.debug("created a new task with id {}", measurement.getId());
	}

	public void deleteTask(UUID uuid) {
		for(ComplexMeasurementTask task : timeBasedTasks) {
			UUID id = task.getComplexMeasurement().getId();
			if(id.equals(uuid)) {
				timeBasedTasks.remove(task);
				log.debug("deleted task with id {}", id);
				return;
			}
		}
		for(ComplexMeasurementTask task : dataBasedTasks) {
			UUID id = task.getComplexMeasurement().getId();
			if(id.equals(uuid)) {
				dataBasedTasks.remove(task);
				log.debug("deleted task with id {}", id);
				return;
			}
		}
		log.warn("task ({}) was not deleted", uuid);
	}

	public List<ComplexType> getAvailableComplexTypes() {
		return availableComplexTypes;
	}

	public ComplexType getComplexType(String typeCode) {
		for(ComplexType complexType : availableComplexTypes) {
			if(complexType.getTypeCode().equals(typeCode)) {
				return complexType;
			}
		}
		return null;
	}

	@PostConstruct
	public void initAvailableTaskTypes() {
		String[] beanNames = appCtx.getBeanNamesForType(ComplexMeasurementTask.class, true, false);
		for (String beanName : beanNames) {
			Task task = appCtx.findAnnotationOnBean(beanName, Task.class);
			ComplexType complexType = TaskAnnotationParser.getComplexType(task);
			checkComplexType(complexType, beanName);
			typeCodeBeanNameMap.put(complexType.getTypeCode(), beanName);
			availableComplexTypes.add(complexType);
			log.info("registered complex task type: {}", complexType.getTypeCode());
		}
	}

	private void checkComplexType(ComplexType complexType, String beanName) {
		if (complexType.getTypeCode().isEmpty()) {
			throw new FatalBeanException("Task with empty taskCode : " + beanName);
		}
		if (typeCodeBeanNameMap.containsKey(complexType.getTypeCode())) {
			throw new FatalBeanException("Multiple tasks with the same code : " + complexType.getTypeCode());
		}
	}
}


text:
package com.siyeh.igtest.threading.synchronized_method;

public class SynchronizedMethod {
    public <warning descr="Method 'fooBar()' declared 'synchronized'"><caret>synchronized</warning> void fooBar() {
        System.out.println("foo");
    }

    public static <warning descr="Method 'bar()' declared 'synchronized'">synchronized</warning> void bar() {
        final var foo = "foo";
        System.out.println(foo);
    }

    public synchronized native void fooBaz();

    static class X extends SynchronizedMethod {

        @Override
        public synchronized void fooBar() {
            super.fooBar();
        }
    }
}


text:
// Copyright (c) 2012 The President and Fellows of Harvard College
// Use of this source code is governed by the LICENSE file found in the root of this project.
(function(App) {
	// dependencies
	var Model = App.Model;
	var Collection = App.Collection;
	var url = App.utils.url;

	/**
	 * Segment model.
	 *
	 * @class Segment
	 * @namespace Catool.models
	 * @extends Catool.Model
	 * @constructor
	 */
	var Segment = Model.extend({
		idAttribute: 'id'
	});
	App.models.Segment = Segment;

	/**
	 * Segments collection.
	 *
	 * @class Segments
	 * @namespace Catool.collections
	 * @extends Catool.Collection
	 * @constructor
	 */
	var Segments = Collection.extend({
		/**
		 * Associate this collection with Segment models.
		 *
		 * @property model
		 */
		model: Segment
	});
	App.collections.Segments = Segments;

	/**
	 * Tag model.
	 *
	 * @class Tag
	 * @namespace Catool.models
	 * @extends Catool.Model
	 * @constructor
	 */
	var Tag = Model.extend({
		idAttribute: 'id'
	});
	App.models.Tag = Tag;

	/**
	 * Tags collection.
	 *
	 * @class Tags
	 * @namespace Catool.collections
	 * @extends Catool.Collection
	 * @constructor
	 */
	var Tags = Collection.extend({
		/**
		 * Associate this collection with Segment models.
		 *
		 * @property model
		 */
		model: Tag
	});
	App.collections.Tag = Tags;

	/**
	 * User model.
	 *
	 * @class User
	 * @namespace Catool.models
	 * @extends Catool.Model
	 * @constructor
	 */
	var User = Model.extend({
		idAttribute: 'id',

		/**
		 * Initialize the user model.
		 *
		 * Overridden to automatically create a *fullname* attribute if
		 * it's not provided.
		 *
		 * @method initialize
		 */
		initialize: function() {
			if(!this.get('fullname')) {
				this.set({ fullname: this.get("name") });
			}
		}
	});
	App.models.User  = User;

	/**
	 * Note model.
	 *
	 * @class Note
	 * @namespace Catool.models
	 * @extends Catool.Model
	 * @constructor
	 */
	var Note = App.Model.extend({
		idAttribute: 'id',

		/**
		 * Initialize the note model.
		 */
		initialize: function() {
			// set url root at run time since we need the base url, which is set at run time
			this.urlRoot = url('/notes');
		},

		/**
		 * Parse the server response.
		 *
		 * Overridden to parse the CakePHP response and associate
		 * the note with its related model instances.
		 *
		 * @method parse
		 * @param {Object} response
		 * @return {Object} model attributes
		 */
		parse: function(response) {
			var attrs = {};

			if(response.results) {
				response = response.results;
			}

			_.extend(attrs, response.Note);
			if(response.User) {
				attrs.user = new User(response.User);
			}
			if(response.Segment) {
				attrs.segments = new Segments(response.Segment);
			}
			if(response.Tag) {
				attrs.tags = new Tags(response.Tag);
			}

			return attrs;
		},

		/**
		 * Test if the Note is an annotation.
		 *
		 * @method isAnnotation
		 * @return {Boolean} true if it is an annotation, false otherwise.
		 */
		isAnnotation: function() {
			return this.get('type') === 'annotation';
		},

		/**
		 * Test if the Note is a comment.
		 *
		 * @method isComment
		 * @return {Boolean} true if it is a comment, false otherwise.
		 */
		isComment: function() {
			return this.get('type') === 'comment';
		},

		/**
		 * Test if a note is a comment on another note.
		 *
		 * @method isCommentOn
		 * @param {Object} note An instance of Note
		 * @return {Boolean} true if it is a comment on the note, false otherwise.
		 */
		isCommentOn: function(note) {
			return this.isComment() && this.get('parent_id') === note.get('id');
		},

		/**
		 * Retrieve all comments on this.
		 *
		 * @method getComments
		 * @return {Object} list of comments on the annotation
		 */
		getComments: function() {
			if(this.isAnnotation()) {
				return this.collection.getCommentsFor(this);
			}
			return null;
		},

		/**
		 * Checks if the model has any tags.
		 */
		hasTags: function() {
			return this.get('tags').size() > 0;
		}
	});
	App.models.Note = Note;

	/**
	 * Notes collection.
	 *
	 * @class Notes
	 * @namespace Catool.collections
	 * @extends Catool.Collection
	 * @constructor
	 */
	var Notes =  Collection.extend({
		/**
		 * Associate this collection with Note models.
		 *
		 * @property model
		 */
		model: Note,

		/**
		 * An instance of a target model (i.e. Video, etc). This is
		 * required to fetch the default set of models from the server.
		 *
		 * @property targetModel
		 */
		targetModel: null,

		/**
		 * Initialize the collection.
		 *
		 * Note: this is called by the constructor.
		 *
		 * @method initialize
		 * @param {Array} models An array of models
		 * @param {Object} options A set of config options.
		 */
		initialize: function(models, options) {
			this.targetModel = options.targetModel;
		},

		/**
		 * Parse the server response.
		 *
		 * @method parse
		 * @param {Object} response Response object
		 * @return {Array} An array of results
		 */
		parse: function(response) {
			return response.results;
		},

		/**
		 * Fetch the default set of models from the server. Overrides
		 * the default fetch method to limit the models to the current
		 * target.
		 *
		 * @method fetch
		 * @param {Object} options A set of options
		 * @return a set of models
		 */
		fetch: function(options) {
			var success, data;
			options = options || {};
			success = options.success;
			data = options.data;

			options.url = url('/notes', { target_id: this.targetModel.get('id') });
			options.success = _.bind(function() {
				if(success) {
					success.apply(this, arguments);
				}
				this.trigger('fetch', this, data);
			}, this);

			return Collection.prototype.fetch.call(this, options);
		},

		/**
		 * Search the collection
		 *
		 * @method search
		 * @param {Object} a query object
		 * @return a set of models
		 */
		 search: function(query) {
			this.fetch({ data: query });
		 },

		/**
		 * Returns the comments for an annotation.
		 *
		 * @method getCommentsFor
		 * @param {Object} annotation An instance of a Note model
		 * @return {Array} a list of Note models
		 */
		getCommentsFor: function(annotation) {
			var comments =_(this.models).filter(function(note) {
				return note.isCommentOn(annotation);
			});

			return comments;
		},

		/**
		 * Returns a list of annotations.
		 *
		 * @method getAnnotations
		 * @return {Array} a list of annotation models
		 */
		getAnnotations: function() {
			return this.filter(function(note) {
				return note.isAnnotation();
			});
		}
	});
	App.collections.Notes = Notes;

	/**
	 * Video target model.
	 *
	 * @class Video
	 * @namespace Catool.models
	 * @extends Catool.Model
	 * @constructor
	 */
	var Video = Model.extend({
		idAttribute: 'id',

		/**
		 * Initialize the model.
		 */
		initialize: function() {
			// set url root at run time since we need the base url, which is set at run time
			this.urlRoot = url('/videos');
		}

	});
	App.models.Video = Video;

})(Catool);


text:
/*
 * File:   RegexLexerTest.cpp
 * Author: Paolo D'Apice
 *
 * Created on March 27, 2012, 3:10 PM
 */

#define BOOST_TEST_MODULE ConnectionPoolTest
#include <boost/test/unit_test.hpp>

#include "net/sf1r/distributed/RegexLexer.hpp"
#include <boost/foreach.hpp>
#include <string>
#include <vector>

using namespace NS_IZENELIB_SF1R;
using namespace std;

BOOST_AUTO_TEST_CASE(sanity) {
    const string URI_PATTERN = "^\\/\\w+(\\/\\w+)?$";
    RegexLexer lexer(URI_PATTERN);

    BOOST_CHECK_EQUAL(URI_PATTERN, lexer.regex());

    vector<string> good;
    good.push_back("/test");
    good.push_back("/test/echo");
    good.push_back("/recommend");
    good.push_back("/recommend/visit_item");

    BOOST_FOREACH(const string& input, good) {
        BOOST_CHECK(lexer.match(input));
    }

    vector<string> bad;
    bad.push_back("");
    bad.push_back(" ");
    bad.push_back("/");
    bad.push_back("/test/");
    bad.push_back("/test/echo/");
    bad.push_back("/recommend/visit_item/");

    BOOST_FOREACH(const string& input, bad) {
        BOOST_CHECK(not lexer.match(input));
    }
}

BOOST_AUTO_TEST_CASE(test_uri) {
    const string URI_PATTERN = "^test(\\/\\w+)?$";
    RegexLexer lexer(URI_PATTERN);

    BOOST_CHECK_EQUAL(URI_PATTERN, lexer.regex());

    vector<string> good;
    good.push_back("test");
    good.push_back("test/echo");

    BOOST_FOREACH(const string& input, good) {
        BOOST_CHECK(lexer.match(input));
    }

    vector<string> bad;
    bad.push_back("");
    bad.push_back(" ");
    bad.push_back("/");
    bad.push_back("/test/");
    bad.push_back("/test/echo");
    bad.push_back("recommend");
    bad.push_back("recommend/visit_item");
    bad.push_back("recommend/visit_item/");

    BOOST_FOREACH(const string& input, bad) {
        BOOST_CHECK(not lexer.match(input));
    }
}


text:
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/time.h>
#include <linux/timex.h>
#include <linux/kernel_stat.h>
#include <linux/mc146818rtc.h>
#include <linux/init.h>
#include <linux/bcd.h>
#include <linux/ioport.h>

#include <asm/io.h>
#include <asm/nvram.h>
#include <asm/prom.h>
#include <asm/sections.h>
#include <asm/time.h>

extern spinlock_t rtc_lock;

static int nvram_as1 = NVRAM_AS1;
static int nvram_as0 = NVRAM_AS0;
static int nvram_data = NVRAM_DATA;

long __init chrp_time_init(void)
{
	struct device_node *rtcs;
	struct resource r;
	int base;

	rtcs = find_compatible_devices("rtc", "pnpPNP,b00");
	if (rtcs == NULL)
		rtcs = find_compatible_devices("rtc", "ds1385-rtc");
	if (rtcs == NULL || of_address_to_resource(rtcs, 0, &r))
		return 0;

	base = r.start;
	nvram_as1 = 0;
	nvram_as0 = base;
	nvram_data = base + 1;

	return 0;
}

int chrp_cmos_clock_read(int addr)
{
	if (nvram_as1 != 0)
		outb(addr>>8, nvram_as1);
	outb(addr, nvram_as0);
	return (inb(nvram_data));
}

void chrp_cmos_clock_write(unsigned long val, int addr)
{
	if (nvram_as1 != 0)
		outb(addr>>8, nvram_as1);
	outb(addr, nvram_as0);
	outb(val, nvram_data);
	return;
}

/*
 * Set the hardware clock. -- Cort
 */
int chrp_set_rtc_time(struct rtc_time *tmarg)
{
	unsigned char save_control, save_freq_select;
	struct rtc_time tm = *tmarg;

	spin_lock(&rtc_lock);

	save_control = chrp_cmos_clock_read(RTC_CONTROL); /* tell the clock it's being set */

	chrp_cmos_clock_write((save_control|RTC_SET), RTC_CONTROL);

	save_freq_select = chrp_cmos_clock_read(RTC_FREQ_SELECT); /* stop and reset prescaler */

	chrp_cmos_clock_write((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);

	if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
		BIN_TO_BCD(tm.tm_sec);
		BIN_TO_BCD(tm.tm_min);
		BIN_TO_BCD(tm.tm_hour);
		BIN_TO_BCD(tm.tm_mon);
		BIN_TO_BCD(tm.tm_mday);
		BIN_TO_BCD(tm.tm_year);
	}
	chrp_cmos_clock_write(tm.tm_sec,RTC_SECONDS);
	chrp_cmos_clock_write(tm.tm_min,RTC_MINUTES);
	chrp_cmos_clock_write(tm.tm_hour,RTC_HOURS);
	chrp_cmos_clock_write(tm.tm_mon,RTC_MONTH);
	chrp_cmos_clock_write(tm.tm_mday,RTC_DAY_OF_MONTH);
	chrp_cmos_clock_write(tm.tm_year,RTC_YEAR);

	/* The following flags have to be released exactly in this order,
	 * otherwise the DS12887 (popular MC146818A clone with integrated
	 * battery and quartz) will not reset the oscillator and will not
	 * update precisely 500 ms later. You won't find this mentioned in
	 * the Dallas Semiconductor data sheets, but who believes data
	 * sheets anyway ...                           -- Markus Kuhn
	 */
	chrp_cmos_clock_write(save_control, RTC_CONTROL);
	chrp_cmos_clock_write(save_freq_select, RTC_FREQ_SELECT);

	spin_unlock(&rtc_lock);
	return 0;
}

void chrp_get_rtc_time(struct rtc_time *tm)
{
	unsigned int year, mon, day, hour, min, sec;

	do {
		sec = chrp_cmos_clock_read(RTC_SECONDS);
		min = chrp_cmos_clock_read(RTC_MINUTES);
		hour = chrp_cmos_clock_read(RTC_HOURS);
		day = chrp_cmos_clock_read(RTC_DAY_OF_MONTH);
		mon = chrp_cmos_clock_read(RTC_MONTH);
		year = chrp_cmos_clock_read(RTC_YEAR);
	} while (sec != chrp_cmos_clock_read(RTC_SECONDS));

	if (!(chrp_cmos_clock_read(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
		BCD_TO_BIN(sec);
		BCD_TO_BIN(min);
		BCD_TO_BIN(hour);
		BCD_TO_BIN(day);
		BCD_TO_BIN(mon);
		BCD_TO_BIN(year);
	}
	if (year < 70)
		year += 100;
	tm->tm_sec = sec;
	tm->tm_min = min;
	tm->tm_hour = hour;
	tm->tm_mday = day;
	tm->tm_mon = mon;
	tm->tm_year = year;
}


text:
package structure.adapter.interface_adapter;

/**
 * Created by zhuyanan on 17/7/24.
 */
public class Cat extends AbstractAnimal {

    @Override
    public void hello() {
        System.out.println("hello,it's cat please!");
    }
}


text:
layout: post
title: Ruby Wrappers for SymEngine, a C++ symbolic manipulation library
date: 2015-08-17 14:30
author: Abinash Meher
comments: true
categories: [SymEngine,GSOC2015,GSOC,Students]
---
I am sure you have heard about [Wolfram Alpha](http://www.wolframalpha.com/). Some of you would have used its [Mathematics section](http://www.wolframalpha.com/examples/Math.html) at some point of time to cross check your solution to a maths problem. If you haven't, please do. A computer algebra system (CAS) does the same thing. Algebraic computation or symbolic computation are all used interchangeably. A CAS solves problems the same way a human does, but way more quickly and precisely. There is very less chance for an error, that we humans often make.

## Introduction
My project was to write the Ruby extensions for the library [SymEngine](https://github.com/sympy/symengine) and come up with a Ruby-ish interface, after which we can use the features of SymEngine from Ruby.

[SymEngine](https://github.com/sympy/symengine) is a library for symbolic computation in C++. You may ask, why SymEngine? There are other CASs that I know of. This question was indeed asked. At the beginning, the idea was to use ruby wrappers for [sage](http://www.sagemath.org/) (a mathematics software system) which uses [Pynac](http://pynac.org/), an interface to [GiNaC](http://www.ginac.de/) (another CAS). As it turns out from the benchmarks, SymEngine is much faster than Pynac. What about directly wrapping GiNaC? SymEngine is also a bit faster than GiNaC.

The motivation for [SymEngine](https://github.com/sympy/symengine) itself is to develop it once in C++ and then use it from other languages rather than doing the same thing all over again for each language that it is required in. In particular, a long term goal is to make Sage as well as SymPy use it by default, thus unifying the Python CAS communities. The goal of implementing the Ruby wrappers is to provide a CAS for the Ruby community.

### How will this be useful?
There are times when we might need a symbolic computation library. Here is an incomplete list of some of the situations:

- We need to do some algebra to get systems of equations in suitable form for numerical computation.
- We need to make substitutions for some variables and don't want to risk a math error by hand. There might be times when we want to partially simplify an expression by substituting only a few of its variables.
- We have a situation where we need to find the optimum number of something to maximise our profits, and the mathematical model devised is just too complicated to solve by hand.
- We need to perform non-trivial derivatives or integrals.
- We are trying to understand the domain of a new function.
- Most root finding algorithms search for a single root, whereas often there are more than one.
- We need to solve a linear system or manipulate a symbolic matrix exactly.
- We need to manipulate exact expressions and solutions, as opposed to approximate ones using a numerical method.

With that said, a symbolic manipulation library is indispensable for scientists and students. Ruby has gained a great deal of popularity over the years, and a symbolic manipulation library gem  like this project in Ruby might prove to be the foundation for a computer algebra system in Ruby. With many efforts like these, Ruby might become the first choice for academicians given how easy it is to code your logic in Ruby.

## How to install the gem?
To install, please follow the [compile instructions given in the README](https://github.com/sympy/symengine/blob/master/symengine/ruby/README.md). After you are done, I would suggest to test the extensions. To run the test suite execute `rspec spec` on the command line, from the `symengine/ruby` dir.

The gem is still in alpha release. Please help us out by reporting any issues in [the repo issue tracker](https://github.com/sympy/symengine/issues).

## What can I do with the gem?
Currently, the following features are available in the gem:
- Construct expressions out of variables (mathematical).
- Simplify the expressions.
- Carry out arithmetic operations like `+`, `-`, `*`, `/`, `**` with the variables and expressions.
- Extract arguments or variables from an expression.
- Differentiate an expression with respect to another.
- Substitute variables with other expressions.

Features that will soon be ported to the SymEngine gem
- Functions, including trigonometric, hyperbolic and some special functions.
- Matrices, and their operations.
- Basic number-theoretic functions.

I have developed a [few IRuby notebooks](https://github.com/sympy/symengine/tree/master/symengine/ruby/notebooks) that demonstrate the use of the new SymEngine module in ruby.

Below is an example taken from the notebooks.

---
## Using the SymEngine Gem
SymEngine is a module in the extensions, and the classes are a part of it. So first you fire up the interpreter or an IRuby notebook and load the file:
```ruby
require 'symengine'
=> true
```
Go ahead and try a function:
```ruby
SymEngine.ascii_art
=>   _____           _____         _
    |   __|_ _ _____|   __|___ ___|_|___ ___
    |__   | | |     |   __|   | . | |   | -_|
    |_____|_  |_|_|_|_____|_|_|_  |_|_|_|___|
          |___|               |___|
```
or create a variable:
```ruby
basic = SymEngine::Basic.new
=> #<SymEngine::Basic:0x00000001e95290>
```
This shows that we have successfully loaded the module.

### SymEngine::Symbol
Just like there are variables like x, y, and z in a mathematical expression or equation, we have `SymEngine::Symbol` in SymEngine to represent them. To use a variable, first we need to make a `SymEngine::Symbol` object with the string we are going to represent the variable with.:
```ruby
puts x = SymEngine::Symbol.new("x")
puts y = SymEngine::Symbol.new("y")
puts z = SymEngine::Symbol.new("z")

x
y
z
```
Then we can construct expressions out of them:
```ruby
e = (x-y)*(x**y/z)
e.to_s
=> "x**y*(x - y)/z"
```
In SymEngine, every object is an instance of Basic or its subclasses. So, even an instance of `SymEngine::Symbol` is a Basic object.:
```ruby
x.class
=> SymEngine::Symbol

x.is_a? SymEngine::Basic
=> true
```
Now that we have an expression, we would like to see it's expanded form using `#expand`:
```ruby
f = e.expand()
f.to_s
=> "x**(1 + y)/z - x**y*y/z"
```
Or check if two expressions are same:
```ruby
f == - (x**y*y/z) + (x**y*x/z)
=> true
```
But `e` and `f` are not equal since they are only mathematically equal, not structurally:
```ruby
e == f
=> false
```
Let us suppose you want to know **what variables/symbols your expression has**. You can do that with the `#free_symbols` method, which returns a set of the symbols that are in the expression.:
```ruby
f.free_symbols
=> #<Set: {#<SymEngine::Basic:0x00000001f0ca70>, #<SymEngine::Basic:0x00000001f0ca48>, #<SymEngine::Basic:0x00000001f0ca20>}>
```
Let us use `#map` method to see the elements of the `Set`.:
```ruby
f.free_symbols.map { |x| x.to_s }
=> ["x", "y", "z"]
```
`#args` returns the terms of the expression,:
```ruby
f.args.map { |x| x.to_s }
["-x**y*y/z", "x**(1 + y)/z"]
```
or if it is a single term it breaks down the elements:
```ruby
f.args[0].args.map { |k| k.to_s }
=> ["-1", "x**y", "y", "z**(-1)"]
```
### SymEngine::Integer

You can make objects of class `SymEngine::Integer`. It's like regular `Integer` in ruby kernel, except it can do all the operations a `Basic` object can — such as arithmetic operations, etc.:
```ruby
a = SymEngine::Integer.new(12)
b = SymEngine::Integer.new(64)
a**b

=> 1168422057627266461843148138873451659428421700563161428957815831003136
```
Additionally, it can support numbers of arbitrarily large length.
```ruby
(a**x).to_s
=> "12**x"
```

### SymEngine::Rational

You can also make objects of class `SymEngine::Rational` which is the SymEngine counterpart for `Rationals` in Ruby.:
```ruby
c = Rational('2/3')
d = SymEngine::Rational.new(c)

=> 2/3
```
Like any other `Basic` object arithmetic operations can be done on this rational type too.:
```ruby
(a-d).to_s
=> "34/3"
```
---
You **need not create** an instance of `SymEngine::Integer` or `SymEngine::Rational`, every time you want to use them in an expression that uses many `Integer`s. Let us say you already have `Integer`/`Rational` object. Even then you can use them without having to create a new `SymEngine` object.:
```ruby
k = (1 / (x * y) - x * y + 2) * (c + x * y) # c is a Rational object, not SymEngine::Rational
k.to_s
=> "(2/3 + x*y)*(2 + 1/(x*y) - x*y)"
```
As you can see, ruby kernel `Integer`s and `Rational`s interoperate seamlessly with the `SymEngine` objects.
```ruby
k.expand.to_s
=> "7/3 + (2/3)*1/(x*y) + (4/3)*x*y - x**2*y**2"
```
---
## What I learned

In the rest of the post, I would like to summarise my work and what I learned as a participant of [Google Summer of Code 2015](https://www.google-melange.com/gsoc/homepage/google/gsoc2015).

## Pre-midterm Evaluations

I am a newbie when it comes to Ruby, and it took me a while to setup the gem and configure files for the building of extensions.

### The struggle between shared, static and dynamic libraries
I faced a lot of problem in the early stages, when I was trying to build the extensions. [Ondrej](https://github.com/certik), my mentor, and [Isuru](https://github.com/isuruf), a fellow GSoC student, helped me a lot. There were many C flags that were being reported as missing. Some flags `cmake` added by default but `extconf.rb` didn't, the same one that was required to be added to build it as a shared library. I am still confused about the details, some of which are [explored in greater detail in my personal blog](http://abinashmeher999.github.io/2015/05/29/Building-the-wrappers/). Finally, the library had to be built as a dynamic one. The problem of missing C flags was resolved later by hooking the process to `cmake` rather than `mkmf`.

### Load Errors and problems in linking
Many [`LoadError`s](http://abinashmeher999.github.io/2015/06/12/The-Load-Error/) popped up, but were eventually solved. [Ivan](https://github.com/dilcom/) helped a lot in debugging the errors. In the end, it turned out to be a simple file missing in the gemspec, that was not being installed.

### Reconfiguring building
One of our aims during developing this was to get rid of unessential dependencies. The ones we already had the tools for. Like later the file `extconf.rb`, that is used to generate Makefile for the extension was removed, because that could also be done by `cmake`. Flags were added to `cmake` for building the Ruby extensions, like the flag `-DWITH_RUBY=yes`. The `Makefile` then generates the library `symengine.so` in the directory `lib/symengine`.Along with `extconf.rb`, the file `extconf.h` was also gone. Along these lines, the dependency on `rake` was also removed, and with that the `Rakefile`. Any task automation will most probably be done in python. So, the `Rake::ExtensionTask` was done by `cmake` and the `Rake::GemPackageTask` was replaced by the manual method of `gem build symengine.gemspec` and `gem install symengine-0.0.0.gem`

### Travis setup
Not many projects have travis-ci setup for multiple languages. Not even the tutorials had clearly mentioned about setting up for multiple languages. But I did know about one of them, which is Shogun, the machine-learning toolbox. I referred to their `.travis.yml` and setup it up. If something like this wouldn't have worked the plan was to manually install the required version of ruby and then execute the shell commands.

### Making a basic object
Finally, I was able to successfully build the extensions, link the extensions with the SymEngine library, load the ruby-extension library in the interpreter and successfully instantiate an object of type `Basic`.

### Inheritance and Symbols
At this time, the way inheritance works(like the sequence of formation and destruction of objects of a class that had a superclass) with the Ruby C API, was confusing for all of us. I designed an [experiment](http://abinashmeher999.github.io/2015/06/26/the-symbol-class/#inheritance-in-ruby-c-api)
to check what was actually happening. That cleared things out, and made the it easier to wrap things from now on. I also wrapped the `Symbol` class during the course.

## Post-midterm Evaluations

### Redesign of the C interface
We had to design an ugly function to wrap vector in C. That led us to redesign the C interface. This approach had no reinterpret casting that was being done earlier. Each data structure had a type that was determined at compile time. For C, it was an opaque structure, while for C++ the opaque structure declared in the shared header file was implemented in the source file that had C++ data types. This [blog post](http://abinashmeher999.github.io/2015/07/03/improving-the-c-interface/) explains it further.

### Integer and Rational
While trying to port the SymEngine classes, `Integer` and `Rational`, I had to port many methods in `Basic` before that. I also replicated the `rake` tasks in NMatrix, for detection of memory leaks, in form of bash scripts.

### Common enumeration
Since all objects in the Ruby C API are of the type `CBasic`, we needed a function that would give us the typename during the runtime for the corresponding objects to be wrapped in ruby, as an object of the correct `Class` in ruby. Since, this was achieved with `enum` in C++, the same thing could be done in C too, with all the classes written manually again. But there was no guarantee for this to be consistent, if ever the features required to be wrapped for a new language, and also manually adding the class in all the enum list everytime a new class is added was prone to errors. So, to make this DRY, we automated this by sharing the list of enums. More details for the implementation can be found [here](http://abinashmeher999.github.io/2015/07/17/common-enumeration-in-c-and-c++/).

### Class coercion and interoperability
To support interoperability with the builtin ruby types, I had to overload the methods in builtin classes earlier(this was not continued). Overriding all the existing binary operations for a ruby class to support SymEngine types, violated the open/closed principle. There was indeed another way, which is *'Class Coercion'*. It was suggested by [Isuru](https://github.com/isuruf/). After that, SymEngine types could seamlessly interoperate between the ruby types.

### Arithmetic operations
After this, all the arithmetic operations had been successfully ported. Each `Basic` object can now perform arithmetic operations with other `Basic` object(sometimes even ruby objects like `Integer`). The test file in python, that had all the corresponding test cases was ported to its RSpec counterpart.

### Substitutions
Recently I completed porting the substitutions module to the extensions(`#subs`). This feature has added a lot of convenience as now you can substitute a `SymEngine::Symbol` with some other value in an expression and then `#expand` to get the result.

### Trigonometric functions
Currently, I am working on porting the trigonometric functions in SymEngine to the extensions. This would first require to wrap the `Function` class and then the `TrigFunction` class in SymEngine.

### Integration of other Ruby gems
I also have plans to integrate the ruby bindings for `gmp`, `mpfr` and `mpc` libraries, that are already available as gems, with ruby bindings for our library. I have created an issue [here](https://github.com/sympy/symengine/issues/490). Feel free to drop any suggestions.

---
There is much scope for improvement in both the projects. For SymEngine, to support more features like polynomials and series-expansion in the near future, and improving the user interface and the exception handling for the extensions. In short, making the extensions more ruby-ish.

I am grateful to my mentor, [Mr. Ondřej Čertík](https://github.com/certik), the [Ruby Science Foundation](http://sciruby.com/) and the [SymPy Organisation](http://www.sympy.org/en/index.html) for the opportunity that they gave me and guiding me through the project, and my team-mates for helping me with the issues. I hope more people will contribute to the project and together we will give a nice symbolic manipulation gem to the Ruby community.


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package model.item.weapons;

/**
 *
 * @author Dr.Chase
 */
public enum DamageTypeEnum {
    LETHAL,
    STUN
}


text:
ASDF_VERSION=v0.8.1
ASDF_HOME=$HOME/.asdf
ASDF_BIN=$ASDF_HOME/asdf.sh

if [[ ! -f "${ASDF_BIN}" ]]; then
    git clone https://github.com/asdf-vm/asdf.git ~/.asdf --branch $ASDF_VERSION
fi

. $ASDF_BIN
. $ASDF_HOME/plugins/java/set-java-home.zsh

fpath=(${ASDF_HOME}/completions $fpath)
autoload -Uz compinit
compinit


text:
package org.kuali.continuity.plan.action.dto;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.kuali.continuity.action.dto.DomainObjectDTO;
import org.kuali.continuity.action.dto.RefDTO;
import org.kuali.continuity.admin.domain.Building;
import org.kuali.continuity.admin.domain.DepartmentType;
import org.kuali.continuity.domain.EvacuationPlan;
import org.kuali.continuity.plan.domain.DepartmentInfo;

public class DepartmentInfoDTO {

	public List<DomainObjectDTO> departmentTypes = new ArrayList<DomainObjectDTO>();
	public List<BuildingDTO> buildings = new ArrayList<BuildingDTO>();
	public String employFaculty = "";
	public RefDTO evacuationPlan = new RefDTO();
	public String costCenter;
	public String comment;

	// head counts
	public int academicStaffCount;
	public int residentsAndFellowsCount;
	public int fulltimeStaffCount;
	public int parttimeStaffCount;
	public int studentStaffCount;
	public int volunteersCount;
	public int guestsCount;
	public int otherStaffCount;

	public DepartmentInfoDTO() {

	}

	public DepartmentInfoDTO(DepartmentInfo dObj) {
		if (dObj == null) return;
		this.departmentTypes =  this.getDepartmentTypeDTOs(dObj.getDepartmentTypes());
		this.buildings = this.getBuildingDTOs(dObj.getBuildings());
		this.employFaculty = dObj.getEmployFaculty();
		this.evacuationPlan = new RefDTO(dObj.getEvacuationPlan());
		this.costCenter = dObj.getCostCenter();
		this.comment = dObj.getComment();
		this.academicStaffCount = dObj.getAcademicStaffCount();
		this.residentsAndFellowsCount = dObj.getResidentsAndFellowsCount();
		this.fulltimeStaffCount = dObj.getFulltimeStaffCount();
		this.parttimeStaffCount = dObj.getParttimeStaffCount();
		this.studentStaffCount = dObj.getStudentStaffCount();
		this.volunteersCount = dObj.getVolunteersCount();
		this.guestsCount = dObj.getGuestsCount();
		this.otherStaffCount = dObj.getOtherStaffCount();
	}

	public DepartmentInfo getDepartmentInfo() {
		DepartmentInfo deptInfo = new DepartmentInfo();
		deptInfo.setDepartmentTypes(this.getDepartmentTypes(departmentTypes));
		deptInfo.setBuildings(this.getBuildings(this.buildings));
		deptInfo.setEmployFaculty(this.employFaculty);
		deptInfo.setEvacuationPlan(new EvacuationPlan(this.evacuationPlan.id));
		deptInfo.setCostCenter(this.costCenter);
		deptInfo.setComment(this.comment);
		deptInfo.setAcademicStaffCount(this.academicStaffCount);
		deptInfo.setResidentsAndFellowsCount(this.residentsAndFellowsCount);
		deptInfo.setFulltimeStaffCount(this.fulltimeStaffCount);
		deptInfo.setParttimeStaffCount(this.parttimeStaffCount);
		deptInfo.setStudentStaffCount(this.studentStaffCount);
		deptInfo.setVolunteersCount(this.volunteersCount);
		deptInfo.setGuestsCount(this.guestsCount);
		deptInfo.setOtherStaffCount(this.otherStaffCount);
		return deptInfo;
	}

	// TODO: refactor
	private List<DepartmentType> getDepartmentTypes(List<DomainObjectDTO> dtos) {
		if (dtos == null) return null;
		List<DepartmentType> list = new ArrayList<DepartmentType>();
		for (DomainObjectDTO domainObjectDTO : dtos) {
			list.add(new DepartmentType(domainObjectDTO.id));
		}
		return list;
	}

	// TODO: refactor
	private Map<Building, String> getBuildings(List<BuildingDTO> dtos) {
		if (dtos == null) return null;
		Map<Building, String> map = new HashMap<Building, String>();
		for (BuildingDTO buildingDTO : dtos) {
			map.put(new Building(buildingDTO.id), buildingDTO.comment);
		}
		return map;
	}

	// TODO: refactor
	private List<BuildingDTO> getBuildingDTOs(Map<Building, String> dObjs) {
		List<BuildingDTO> dObjDTOs = new ArrayList<BuildingDTO>();
		if (dObjs != null) {
			Set<Building> bldgs = dObjs.keySet();
			for (Building building : bldgs) {
				BuildingDTO bldgDTO = new BuildingDTO(building);
				bldgDTO.comment = dObjs.get(building);
				dObjDTOs.add(bldgDTO);
			}
		}
		return dObjDTOs;
	}

	// TODO: refactor
	private List<DomainObjectDTO> getDepartmentTypeDTOs(List<DepartmentType> dObjs) {
		List<DomainObjectDTO> dObjDTOs = new ArrayList<DomainObjectDTO>();
		if (dObjs != null) {
			for (DepartmentType dObj : dObjs) {
				dObjDTOs.add(new DomainObjectDTO(dObj));
			}
		}
		return dObjDTOs;
	}

}


text:
import {
    ChangeDetectorRef, Component
} from '@angular/core';

import {
    style, trigger, animate, transition, state
} from '@angular/animations';

import {RuntimeService} from '../../services/runtime.service';
import {GadgetInstanceService} from '../../grid/grid.service';
import {EndPointService} from '../../configuration/tab-endpoint/endpoint.service';
import {GadgetPropertyService} from '../_common/gadget-property.service';
import {GadgetBase} from '../_common/gadget-base';
import {DiskService} from './service';
import {OptionsService} from "../../configuration/tab-options/service";

@Component({
    selector: 'app-dynamic-component',
    moduleId: module.id,
    templateUrl: './view.html',
    styleUrls: ['../_common/styles-gadget.css'],
    animations: [

        trigger('accordion', [
            state('in', style({
                height: '*'
            })),
            state('out', style({
                opacity: '0',
                height: '0px'
            })),
            transition('in => out', animate('700ms ease-in-out')),
            transition('out => in', animate('300ms ease-in-out'))
        ]),
        trigger('accordion2', [
            state('in', style({
                height: '*'
            })),
            state('out', style({
                opacity: '0',
                height: '0px'
            })),
            transition('in => out', animate('300ms ease-in-out')),
            transition('out => in', animate('800ms ease-in-out'))
        ])
    ]
})
export class DiskGadgetComponent extends GadgetBase {

    topic: any;

    showOperationControls = false;

    data: any;

    threshold: string;

    badColorScheme = {
        domain: ['#a10910', '#DDDDDD']
    };
    goodColorScheme = {
        domain: ['#00c700', '#DDDDDD']
    };
    used;
    avail;

    detailMenuOpen: string;

    colorScheme = this.goodColorScheme;

    constructor(protected _runtimeService: RuntimeService,
                protected _gadgetInstanceService: GadgetInstanceService,
                protected _propertyService: GadgetPropertyService,
                protected _endPointService: EndPointService,
                protected _changeDetectionRef: ChangeDetectorRef,
                protected _diskService: DiskService,
                protected _optionsService: OptionsService) {
        super(_runtimeService,
            _gadgetInstanceService,
            _propertyService,
            _endPointService,
            _changeDetectionRef,
            _optionsService);

        this.run();
        this.setTopic();
    }

    public preRun(): void {

        this.threshold = this.getPropFromPropertyPages('threshold');
        this.detailMenuOpen = 'out';

    }

    public run() {
        this.data = [];
        this.initializeRunState(true);
        this.updateData(null);
    }

    public stop() {
        this.setStopState(false);
    }

    public updateData(data: any[]) {

        this._diskService.getMockData().subscribe(_data => {
                this.data = _data;

                const thresholdVal = Number(this.threshold);

                if (this.data[0].value < thresholdVal) {
                    this.colorScheme = this.goodColorScheme;
                } else {
                    this.colorScheme = this.badColorScheme;
                }

                this.used = this.data[0].value;
                this.avail = this.data[1].value;

            },
            error => this.handleError(error));
    }

    public updateProperties(updatedProperties: any) {

        /**
         * todo
         *  A similar operation exists on the procmman-config-service
         *  whenever the property page form is saved, the in memory board model
         *  is updated as well as the gadget instance properties
         *  which is what the code below does. This can be eliminated with code added to the
         *  config service or the property page service.
         *
         * **/

        const updatedPropsObject = JSON.parse(updatedProperties);

        this.propertyPages.forEach(function (propertyPage) {

            for (let x = 0; x < propertyPage.properties.length; x++) {

                for (const prop in updatedPropsObject) {
                    if (updatedPropsObject.hasOwnProperty(prop)) {
                        if (prop === propertyPage.properties[x].key) {
                            propertyPage.properties[x].value = updatedPropsObject[prop];
                        }

                    }
                }
            }
        });

        this.threshold = updatedPropsObject.threshold;
        this.title = updatedPropsObject.title;
        this.setEndPoint(updatedPropsObject.endpoint);

        this.run();

    }
    setTopic() {
        this._diskService.getHelpTopic().subscribe(data => {

            this.topic = data;

        });
    }
    toggleAcordion(): void {

        this.detailMenuOpen = this.detailMenuOpen === 'out' ? 'in' : 'out';

    }
}


text:
A simple tool that will intercept requests made via http.request and
mikeal's request module and respond with dummy data.

Heavily inspired by: https://github.com/chrisk/fakeweb

## Installation

```
npm install node-fakeweb
```

## Basic Examples

```
var request = require('request');
var fakeweb = require('node-fakeweb');
var output = function(err, resp, body) { console.log(body); }

fakeweb.allowNetConnect = false;
fakeweb.registerUri({uri: 'http://www.testing.com:80/', body: 'Hello!'});
request.get({uri: 'http://www.testing.com:80/'}, output);
```

This will output:

```
[ctide ~]:~$ node test/test.js
Hello!
```