text:
'use strict';
var mocha = require('mocha');
var chakram = require('chakram');
var request = chakram.request;
var expect = chakram.expect;

describe('tests for /v2.0/data/pollen/{id}', function () {
  describe('tests for get', function () {
    it('should respond 200 for "A record of all pollen samples in time/space for a particular taxon."', function () {
      var response = request('get', 'http://localhost:3005/v2.0/data/pollen/{id}', {
        'time': true
      });

      expect(response).to.have.status(200);
      return chakram.wait();
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/mirstack/w8f.png?branch=master)](https://travis-ci.org/mirstack/w8f)

**File creation detector.**

This is a simple tool that detects file existance or creation. The script can be used to
wait with performing some operations until non-existant yet file appears.

## Installation

To install `w8f` go to [releases][releases] page and pick latest package. Download
it and unpack with desired prefix:

    $ unzip -d /usr/local w8f-*.zip

[releases]: https://github.com/mirstack/w8f/releases

### Installing from source

To install package from sources you need to have few dependencies installed first. Install
**bash 4.0 or higher** and **inotifywait** tool in your system. When you're ready with
your dependencies run the following:

    $ ./configure --prefix=/usr/local
    $ make install

Run `install-man` instead of `install` if you want to have man pages installed as well.

## Usage

Given an example:

    $ w8f /tmp/hello

It will exit with status `0` when `/tmp/hello` appears. If the file already
exists, program will exit immediatelly with success.

You can use different timeouts and intervals:

    $ w8f -t20 -i2 /tmp/hello

This example will wait 20 seconds, checking every 2 seconds if file exists.

## Hacking

If you wanna hack on `w8f` just clone the repo and play with the code.

### Testing

You can run tests with `test` target, no extra stuff is needed:

    $ make test

### Releasing

To build a new release use bundled make target called `pack`:

    $ make pack

It will wrap the binary and other needed files into a zip archive and save
it to `pkg/w8f-x.y.z-{os}-{arch}.zip`.

## Contribute

1. Fork the project.
2. Write awesome code (in a feature branch).
3. Test, test, test...!
4. Commit, push and send Pull Request.


text:
Programas simples em C++ que demostram uma solução para dois problemas clássicos
de paralelismo em Ciência da Computação:

  - Problema dos filosofos famintos;
  - Problema do barbeiro dorminhoco.

Os problemas foram propostos em uma aula de Sistemas Operacionais II pela
Universidade Feevale.

## Método

Resolvemos utilizar a linguagem C++ para resolver os problemas pois permite
criação de threads facilmente e é multiplataforma.

OBS: Os projetos utilizam o padrão C++11 então o compilador usado
deve suportar essa versão

## Onde está o código?

Cada problema tem seu próprio programa e método de build. Os projetos
estão separados em branches. Abaixo você tem um link para elas:

  - [Problema dos filósofos](https://github.com/mkautzmann/problema-paralelismo/tree/problema-filosofos)
  - [Problema do barbeiro](https://github.com/mkautzmann/problema-paralelismo/tree/problema-barbeiro)

Cada branch também tem seu próprio README com explicações sobre o projeto.

## Autores

  - [Gustavo Willrich](https://github.com/gustavo7w)
  - [Matheus Kautzmann](https://github.com/mkautzmann)


text:
<!DOCTYPE HTML>

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

        This editor is read-only (mode='viewer').


text:
This is a project exploring the counting of objects in images. While the project makes use of the example of counting wheat grains in images of wheat plants, it can be applied to objects of any kind. A very high-level description of the way the system works is that it trains a classifier to recognise images of the object being counted then attempts to recognise instances of this object in any given image and returns the number of recognised matches. As such, the count returned is really an estimate.

![](https://github.com/oduwa/Pic-Numero/blob/master/Assets/pipeline.png)

The system can make use of different classifiers depending on your choice (currently SVM, MLP neural net and CNN). It might be useful to know that the results of the classifications of the last count can be found in src/Results. "<filename>_0" means it was classified as false (not an object being counted)  while "<filename>_1" means it was classified as true (object being counted).

## Usage ##
First, to train the system to identify objects you want, all you have to do is populate the "train" folder (which contains "positive" and "negative" subfolders) with your training images appropriately.

Then in your code be sure to add `from PicNumero import PicNumero`.

You can then use `PicNumero.run_with_svm()` `PicNumero.run_with_mlp()` or `PicNumero.run_with_cnn()` with the filename of the image whose objects are to be counted as the argument.

```python
from PicNumero import PicNumero

imagePath = "Path/To/Your/Image.png"
count = PicNumero.run_with_cnn(imagePath)
```

PicNumero also includes a helper standalone program for ROI extraction however it is only available for Mac OS X and certain flavours of Linux at this time. Can be found in dist/gui/. Run from terminal with the command "./dist/gui/gui". Source is contained in "gui.py" and "gui\_checkbox\_handlers.py".

## Dependencies ##
Makes use of Python 2.7 and the scikit machine learning and image processing libraries (which can be found [here](http://scikit-learn.org/stable/) and [here](http://scikit-image.org)).

**Note: _TensorFlow is required to use the CNN functionality (CNN.py). If you do
not have TensorFlow already installed, visit [here](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md)
for detailed instructions on how to install it._**

## Compatibility ##

Tested and working on OS X and certain flavours of Linux. Should work on Windows too but could potentially need some tweaking; I've never tried to run it on windows before.

## Credits ##

Made use of Google's excellent [TensorFlow](https://www.tensorflow.org) library


text:
<link rel="import" href="/components/polymer/polymer-element.html">

<dom-module id="my-page1">
	<template>

DEMO PAGE 1

I have a grey cat

	</template>

</dom-module>


text:
define( [
	"../core",
	"./var/nonce",
	"./var/rquery",
	"../ajax"
], function( jQuery, nonce, rquery ) {

"use strict";

var oldCallbacks = [],
	rjsonp = /(=)\?(?=&|$)|\?\?/;

// Default jsonp settings
jQuery.ajaxSetup( {
	jsonp: "callback",
	jsonpCallback: function() {
		var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
		this[ callback ] = true;
		return callback;
	}
} );

// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {

	var callbackName, overwritten, responseContainer,
		jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
			"url" :
			typeof s.data === "string" &&
				( s.contentType || "" )
					.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
				rjsonp.test( s.data ) && "data"
		);

	// Handle iff the expected data type is "jsonp" or we have a parameter to set
	if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {

		// Get callback name, remembering preexisting value associated with it
		callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
			s.jsonpCallback() :
			s.jsonpCallback;

		// Insert callback into url or form data
		if ( jsonProp ) {
			s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
		} else if ( s.jsonp !== false ) {
			s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
		}

		// Use data converter to retrieve json after script execution
		s.converters[ "script json" ] = function() {
			if ( !responseContainer ) {
				jQuery.error( callbackName + " was not called" );
			}
			return responseContainer[ 0 ];
		};

		// Force json dataType
		s.dataTypes[ 0 ] = "json";

		// Install callback
		overwritten = window[ callbackName ];
		window[ callbackName ] = function() {
			responseContainer = arguments;
		};

		// Clean-up function (fires after converters)
		jqXHR.always( function() {

			// If previous value didn't exist - remove it
			if ( overwritten === undefined ) {
				jQuery( window ).removeProp( callbackName );

			// Otherwise restore preexisting value
			} else {
				window[ callbackName ] = overwritten;
			}

			// Save back as free
			if ( s[ callbackName ] ) {

				// Make sure that re-using the options doesn't screw things around
				s.jsonpCallback = originalSettings.jsonpCallback;

				// Save the callback name for future use
				oldCallbacks.push( callbackName );
			}

			// Call if it was a function and we have a response
			if ( responseContainer && jQuery.isFunction( overwritten ) ) {
				overwritten( responseContainer[ 0 ] );
			}

			responseContainer = overwritten = undefined;
		} );

		// Delegate to script
		return "script";
	}
} );

} );


text:
"""
This module contains an operator to run downstream tasks only for the
latest scheduled DagRun
"""
from __future__ import annotations

from typing import TYPE_CHECKING, Iterable

import pendulum

from airflow.operators.branch import BaseBranchOperator
from airflow.utils.context import Context

if TYPE_CHECKING:
    from airflow.models import DAG, DagRun

class LatestOnlyOperator(BaseBranchOperator):
    """
    Allows a workflow to skip tasks that are not running during the most
    recent schedule interval.

    If the task is run outside of the latest schedule interval (i.e. external_trigger),
    all directly downstream tasks will be skipped.

    Note that downstream tasks are never skipped if the given DAG_Run is
    marked as externally triggered.
    """

    ui_color = "#e9ffdb"  # nyanza

    def choose_branch(self, context: Context) -> str | Iterable[str]:
        # If the DAG Run is externally triggered, then return without
        # skipping downstream tasks
        dag_run: DagRun = context["dag_run"]
        if dag_run.external_trigger:
            self.log.info("Externally triggered DAG_Run: allowing execution to proceed.")
            return list(context["task"].get_direct_relative_ids(upstream=False))

        dag: DAG = context["dag"]
        next_info = dag.next_dagrun_info(dag.get_run_data_interval(dag_run), restricted=False)
        now = pendulum.now("UTC")

        if next_info is None:
            self.log.info("Last scheduled execution: allowing execution to proceed.")
            return list(context["task"].get_direct_relative_ids(upstream=False))

        left_window, right_window = next_info.data_interval
        self.log.info(
            "Checking latest only with left_window: %s right_window: %s now: %s",
            left_window,
            right_window,
            now,
        )

        if not left_window < now <= right_window:
            self.log.info("Not latest execution, skipping downstream.")
            # we return an empty list, thus the parent BaseBranchOperator
            # won't exclude any downstream tasks from skipping.
            return []
        else:
            self.log.info("Latest, allowing execution to proceed.")
            return list(context["task"].get_direct_relative_ids(upstream=False))


text:
  <md-card>

  </md-card>

  <md-card>
    <button md-button>FLAT</button>
    <button md-raised-button md-tooltip="This is a tooltip!">RAISED</button>
    <button md-raised-button color="primary">PRIMARY RAISED</button>
    <button md-raised-button color="accent">ACCENT RAISED</button>
  </md-card>

  <md-card>
    <md-checkbox>Unchecked</md-checkbox>
    <md-checkbox [checked]="true">Checked</md-checkbox>
    <md-checkbox [indeterminate]="true">Indeterminate</md-checkbox>
    <md-checkbox [disabled]="true">Disabled</md-checkbox>
  </md-card>

  <md-card>
    <md-radio-button name="symbol">Alpha</md-radio-button>
    <md-radio-button name="symbol">Beta</md-radio-button>
    <md-radio-button name="symbol" disabled>Gamma</md-radio-button>
  </md-card>

  <md-card class="app-input-section">
    <input mdInput placeholder="First name" />

    <input mdInput #nickname placeholder="Nickname" maxlength="50" />
      <md-hint align="end">
        {{nickname.characterCount}} / 50
      </md-hint>

    <input mdInput />
      <md-placeholder>
        android Favorite phone
      </md-placeholder>

    <input mdInput placeholder="Motorcycle model" />

        motorcycle

  </md-card>

  <md-card>
    <md-list class="app-list">
      <md-list-item *ngFor="let food of foods">

{{food.name}}

{{food.rating}}

      </md-list-item>
    </md-list>
  </md-card>

  <md-card>
    <md-spinner class="app-spinner"></md-spinner>
    <md-spinner color="accent" class="app-spinner"></md-spinner>
  </md-card>

  <md-card>

      Indeterminate progress-bar
      <md-progress-bar
          class="app-progress"
          mode="indeterminate"
          aria-label="Indeterminate progress-bar example"></md-progress-bar>

      Determinate progress bar - {{progress}}%
      <md-progress-bar
          class="app-progress"
          color="accent"
          mode="determinate"
          [value]="progress"
          aria-label="Determinate progress-bar example"></md-progress-bar>

  </md-card>

  <md-card>
    <md-tab-group>
      <md-tab label="Earth">

EARTH

      </md-tab>
      <md-tab label="Fire">

FIRE

      </md-tab>
    </md-tab-group>
  </md-card>

  <md-card>
    <md-icon>build</md-icon>
  </md-card>

  <md-card>
    <button md-button [md-menu-trigger-for]="menu">
      MENU
    </button>
  </md-card>

  <md-menu #menu="mdMenu">
    <button md-menu-item>Lemon</button>
    <button md-menu-item>Lime</button>
    <button md-menu-item>Banana</button>
  </md-menu>

  <md-card>

Last dialog result: {{lastDialogResult}}

    <button md-raised-button (click)="openDialog()">DIALOG</button>
    <button md-raised-button (click)="showSnackbar()">SNACKBAR</button>
  </md-card>


text:
> see https://aka.ms/autorest

This is the AutoRest configuration file for ServiceFabricClient.

---
## Getting Started
To build the SDK for ServiceFabricClient, simply [Install AutoRest](https://aka.ms/autorest/install) and in this folder, run:

> `autorest`

To see additional help and options, run:

> `autorest --help`
---

## Configuration

### Basic Information
These are the global settings for the ServiceFabricClient API.

``` yaml
openapi-type: data-plane
tag: '6.0'
```

### Tag: 1.0.0

These settings apply only when `--tag=1.0.0` is specified on the command line.

``` yaml $(tag) == '1.0.0'
input-file:
- Microsoft.ServiceFabric/stable/1.0.0/servicefabric.json
```

### Tag: 5.6

These settings apply only when `--tag=5.6` is specified on the command line.

``` yaml $(tag) == '5.6'
input-file:
- Microsoft.ServiceFabric/stable/5.6/servicefabric.json
```

### Tag: 6.0

These settings apply only when `--tag=6.0` is specified on the command line.

``` yaml $(tag) == '6.0'
input-file:
- Microsoft.ServiceFabric/stable/6.0/servicefabric.json
```

---
# Code Generation

## Swagger to SDK

This section describes what SDK should be generated by the automatic system.
This is not used by Autorest itself.

``` yaml $(swagger-to-sdk)
swagger-to-sdk:
  - repo: azure-sdk-for-python
  - repo: azure-sdk-for-go
```

## Python

These settings apply only when `--python` is specified on the command line.
Please also specify `--python-sdks-folder=<path to the root directory of your azure-sdk-for-python clone>`.
Use `--python-mode=update` if you already have a setup.py and just want to update the code itself.

``` yaml $(python)
python-mode: create
python:
  license-header: MICROSOFT_MIT_NO_VERSION
  payload-flattening-threshold: 2
  namespace: azure.servicefabric
  package-name: azure-servicefabric
  add-credentials: true
  clear-output-folder: true
```
``` yaml $(python) && $(python-mode) == 'update'
python:
  no-namespace-folders: true
  output-folder: $(python-sdks-folder)/azure-servicefabric/azure/servicefabric
```
``` yaml $(python) && $(python-mode) == 'create'
python:
  basic-setup-py: true
  output-folder: $(python-sdks-folder)/azure-servicefabric
```

## Go

These settings apply only when `--go` is specified on the command line.

``` yaml $(go)
go:
  license-header: MICROSOFT_APACHE_NO_VERSION
  namespace: servicefabric
  clear-output-folder: true
```

### Go multi-api

``` yaml $(go) && $(multiapi)
batch:
  - tag: "1.0.0"
  - tag: "5.6"
  - tag: "6.0"
```

### Tag: 1.0.0 and go

These settings apply only when `--tag=1.0.0 --go` is specified on the command line.

``` yaml $(tag) == '1.0.0' && $(go)
output-folder: $(go-sdk-folder)/services/servicefabric/1.0.0/servicefabric
```

### Tag: 5.6 and go

These settings apply only when `--tag=5.6 --go` is specified on the command line.

``` yaml $(tag) == '5.6' && $(go)
output-folder: $(go-sdk-folder)/services/servicefabric/5.6/servicefabric
```

### Tag: 6.0 and go

These settings apply only when `--tag=6.0 --go` is specified on the command line.

``` yaml $(tag) == '6.0' && $(go)
output-folder: $(go-sdk-folder)/services/servicefabric/6.0/servicefabric
```


text:
using System;
using FluentAssertions;
using Unicorn.Configuration;
using Xunit;

namespace Unicorn.Tests.Configuration
{
	public class ConfigurationUtilityTests
	{
		[Fact]
		public void ResolveConfigurationPath_ResolvesExpectedPath_WhenPathIsAbsolute()
		{
			ConfigurationUtility.ResolveConfigurationPath("c:\\web").Should().Be("c:\\web");
		}

		[Fact]
		public void ResolveConfigurationPath_ResolvesExpectedPath_WhenPathIsRootRelative()
		{
			// HostingEnvironment returns null out of web context so path = empty string
			ConfigurationUtility.ResolveConfigurationPath("~/").Should().Be(AppDomain.CurrentDomain.BaseDirectory);
		}

		[Fact]
		public void ResolveConfigurationPath_ResolvesExpectedPath_WhenPathIsRelative()
		{
			// HostingEnvironment returns null out of web context so root = empty string
			ConfigurationUtility.ResolveConfigurationPath("~/../hello").Should().Be($"{AppDomain.CurrentDomain.BaseDirectory}\\..\\hello");
		}
	}
}


text:
package org.helm.notation2.tools;

import java.io.IOException;

import org.helm.chemtoolkit.CTKException;
import org.helm.chemtoolkit.CTKSmilesException;
import org.helm.notation2.Chemistry;
import org.helm.notation2.Monomer;
import org.helm.notation2.MonomerFactory;
import org.helm.notation2.exception.BuilderMoleculeException;
import org.helm.notation2.exception.ChemistryException;
import org.helm.notation2.exception.HELM2HandledException;
import org.helm.notation2.exception.MonomerException;
import org.helm.notation2.exception.MonomerLoadingException;
import org.helm.notation2.exception.NotationException;
import org.helm.notation2.exception.ParserException;
import org.helm.notation2.parser.ParserHELM2;
import org.helm.notation2.parser.exceptionparser.ExceptionState;
import org.helm.notation2.parser.notation.polymer.PolymerNotation;
import org.helm.notation2.tools.SMILES;
import org.jdom2.JDOMException;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;

/**
 * SMILESTest
 *
 * @author hecht
 */
public class SMILESTest {
  ParserHELM2 parser;

  @Test
  public PolymerNotation getSimpleRNANotation() throws ParserException, JDOMException {
    String notation = "RNA1{P.R(A)[sP].RP.R(G)P.[LR]([5meC])}$$$$";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);
  }

  public PolymerNotation getInlineSmilesModAdenine() throws ParserException, JDOMException {
    String notation = "RNA1{R(C)P.R([Nc1ncnc2n([*])cnc12 |$;;;;;;;_R1;;;$|])[sP].RP.R(G)P.[LR]([5meC])P}$$$$";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);
  }

  public PolymerNotation getSimplePeptideNotation() throws ParserException, JDOMException {
    String notation = "PEPTIDE1{G.G.K.A.A.[seC]}$$$$";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);
  }

  public PolymerNotation getInlineSmilesPeptideNotation() throws ParserException, JDOMException {
    String notation = "PEPTIDE1{G.G.K.A.[C[C@H](N[*])C([*])=O |$;;;_R1;;_R2;$|].[seC]}$$$$";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);
  }

  public PolymerNotation getSimpleChemNotation() throws ParserException, JDOMException {
    String notation = "CHEM1{[PEG2]}$$$$";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);

  }

  public PolymerNotation getSmilesNotation() throws ParserException, JDOMException {
    String notation = "CHEM1{[[*]OCCOCCOCCO[*] |$_R1;;;;;;;;;;;_R3$|]}$$$$";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);

  }

  public PolymerNotation getRNANotationWithInline() throws ParserException, JDOMException {
    String notation =
        "RNA1{[C[C@@]1([*])O[C@H](CO[*])[C@@H](O[*])[C@H]1O |$;;_R3;;;;;_R1;;;_R2;;$|([Cc1nc2c(N)ncnc2n1[*] |$;;;;;;;;;;;_R1$|])[O[26P]([*])([*])=O |$;;_R1;_R2;$|]].R(C)P.R(T)P.R(G)}$$$$";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);
  }

  public PolymerNotation getRNANotationWithSalt() throws ParserException, JDOMException {
    String notation =
        "RNA1{P.R(A)[sP].R(A)[[Na+].[O-]P([*])([*])=O |$;;;_R1;_R2;$|].[LR]([5meC])}$$$$";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);

  }

  public PolymerNotation getChemNotationWithSalt() throws ParserException, JDOMException {
    String notation =
        "CHEM1{[[Na+].[O-]C1C=CC(=O)N1CC1CCC(CC1)C([*])=O |$;;;;;;;;;;;;;;;;_R1;$,c:2|]}$$$$";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);

  }

  public PolymerNotation getPeptideNotationWithSalt() throws ParserException, JDOMException {
    String notation =
        "PEPTIDE1{G.G.K.[[Na+].C[C@H](N[*])C([O-])[*] |$;;;;_R1;;;_R2$|].A.[seC]}$$$$";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);
  }

  public PolymerNotation getPeptideNotationWithBrackets() throws ParserException, JDOMException {
    String notation = "PEPTIDE1{A.[[*]C(=O)[C@H](C)N([*])C |$_R2;;;;;;_R1;;;$|].A}$$$$V2.0";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);
  }

  public PolymerNotation getPeptideNotationWithoutBrackets() throws ParserException, JDOMException {
    String notation = "PEPTIDE1{A.[*C(=O)[C@H](C)N(*)C |$_R2;;;;;;_R1;;;$|].A}$$$$V2.0";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);
  }

  public PolymerNotation getPeptideNotationWithAtomMap() throws ParserException, JDOMException {
    String notation = "PEPTIDE1{A.[[OH:2]C(=O)[C@H](C)N([H:1])C].A}$$$$V2.0";
    return HELM2NotationUtils.readNotation(notation).getListOfPolymers().get(0);
  }

  @Test
  public void testSMILES() throws BuilderMoleculeException, CTKException, ChemistryException, ParserException, JDOMException {
    String test =
        "PEPTIDE1{D}|PEPTIDE2{E}|PEPTIDE3{L.R}|CHEM1{[MCC]}$PEPTIDE1,PEPTIDE2,1:R2-1:R3|PEPTIDE3,PEPTIDE1,2:R2-1:R3$$$V2.0";

    String smile = SMILES.getSMILESForAll(HELM2NotationUtils.readNotation(test));
    String expectedResult = "OC(=O)C1CCC(CN2C(=O)C=CC2=O)CC1.[H]N[C@@H](CCC(=O)C(=O)[C@@H](N[H])CC(=O)C(=O)[C@H](CCCNC(N)=N)NC(=O)[C@@H](N[H])CC(C)C)C(O)=O";
    if (Chemistry.getInstance().getChemistry().equals("org.helm.chemtoolkit.chemaxon.ChemaxonManipulator")) {
      Assert.assertEquals(smile, expectedResult);
    }

  }

  @Test
  public void testSMILESCanonical() throws CTKSmilesException, BuilderMoleculeException, CTKException, NotationException, ChemistryException, ParserException, JDOMException {

    String test =
        "PEPTIDE1{D}|PEPTIDE2{E}|PEPTIDE3{L.R}|CHEM1{[MCC]}$PEPTIDE1,PEPTIDE2,1:R2-1:R3|PEPTIDE3,PEPTIDE1,2:R2-1:R3$$$V2.0";

    String canSmile = SMILES.getCanonicalSMILESForAll(HELM2NotationUtils.readNotation(test));
    if (Chemistry.getInstance().getChemistry().equals("org.helm.chemtoolkit.chemaxon.ChemaxonManipulator")) {
      Assert.assertEquals(canSmile, "OC(=O)C1CCC(CN2C(=O)C=CC2=O)CC1.CC(C)C[C@H](N)C(=O)N[C@@H](CCCNC(N)=N)C(=O)C(=O)C[C@H](N)C(=O)C(=O)CC[C@H](N)C(O)=O");
    }
  }

  public void testHELM1AgainstHELM2(String notation) throws BuilderMoleculeException, CTKException, ChemistryException, ParserException, JDOMException, NotationException {

    String test = notation + "V2.0";
    SMILES.getSMILESForAll(HELM2NotationUtils.readNotation(test));

    SMILES.getCanonicalSMILESForAll(HELM2NotationUtils.readNotation(test));

  }

  @Test
  public void testGetSmilesPolymer() throws CTKSmilesException, BuilderMoleculeException, HELM2HandledException, CTKException, ParserException, JDOMException, NotationException, ChemistryException {
    SMILES.getCanonicalSMILESForPolymer(getSimpleRNANotation());

    SMILES.getCanonicalSMILESForPolymer(getInlineSmilesModAdenine());

    SMILES.getCanonicalSMILESForPolymer(getSimplePeptideNotation());

    SMILES.getCanonicalSMILESForPolymer(getInlineSmilesPeptideNotation());

    SMILES.getCanonicalSMILESForPolymer(getSimpleChemNotation());

    SMILES.getCanonicalSMILESForPolymer(getSmilesNotation());
    if (Chemistry.getInstance().getChemistry().equals("org.helm.chemtoolkit.chemaxon.ChemaxonManipulator")) {
      SMILES.getCanonicalSMILESForPolymer(getRNANotationWithSalt());
    }

  }

  @Test
  public void testGetSmilesFormats() throws CTKSmilesException, BuilderMoleculeException, HELM2HandledException, CTKException, ParserException, JDOMException, NotationException, ChemistryException {
	String canonicalSMILES = "C[C@@H](C(=O)N(C)[C@@H](C)C(=O)N[C@@H](C)C(=O)O)N[H]";
    Assert.assertEquals(SMILES.getCanonicalSMILESForPolymer(getPeptideNotationWithBrackets()),canonicalSMILES);

    Assert.assertEquals(SMILES.getCanonicalSMILESForPolymer(getPeptideNotationWithoutBrackets()),canonicalSMILES);

    Assert.assertEquals(SMILES.getCanonicalSMILESForPolymer(getPeptideNotationWithAtomMap()),canonicalSMILES);

  }

  @Test
  public void testSelfCycle() throws ExceptionState, IOException, JDOMException, BuilderMoleculeException, CTKException, NotationException, MonomerException, ChemistryException,
      ParserException {
    // backbone cyclic peptide
    String notation = "PEPTIDE1{A.A.G.K}$PEPTIDE1,PEPTIDE1,1:R1-4:R2$$$";
    testHELM1AgainstHELM2(notation);

    // backbone cyclic RNA
    notation = "RNA1{R(C)P.RP.R(A)P.RP.R(A)P.R(U)P}$RNA1,RNA1,1:R1-16:R2$$$";
    testHELM1AgainstHELM2(notation);

    // cyclic chem
    notation = "CHEM1{[SS3]}|CHEM2{[SS3]}$CHEM1,CHEM2,1:R1-1:R1|CHEM1,CHEM2,1:R2-1:R2$$$";
    testHELM1AgainstHELM2(notation);

    // peptide-chem cycles
    notation = "PEPTIDE1{H.H.E.E.E}|CHEM1{[SS3]}|CHEM2{[EG]}$PEPTIDE1,CHEM2,5:R2-1:R2|CHEM2,CHEM1,1:R1-1:R2|PEPTIDE1,CHEM1,1:R1-1:R1$$$";
    testHELM1AgainstHELM2(notation);

    // multiple peptide-chem cycles
    notation =
        "PEPTIDE1{E.E.E.E.E}|PEPTIDE2{E.D.D.I.A.C.D.E}|CHEM1{[SS3]}|CHEM2{[SS3]}|CHEM3{[SS3]}$PEPTIDE2,CHEM2,8:R2-1:R1|PEPTIDE1,CHEM3,5:R2-1:R2|PEPTIDE1,CHEM1,1:R1-1:R1|PEPTIDE2,CHEM3,1:R1-1:R1|CHEM1,CHEM2,1:R2-1:R2$$$";
    testHELM1AgainstHELM2(notation);
  }

  @Test(expectedExceptions = BuilderMoleculeException.class)
  public void testChiralCenter() throws ExceptionState, IOException, JDOMException, BuilderMoleculeException, CTKException, NotationException, MonomerException,
      ChemistryException, ParserException {
    // backbone and branch cyclic RNA
    String notation = "RNA1{R(C)P.RP.R(A)P.RP.R(A)P.R(U)P}$RNA1,RNA1,4:R3-9:R3$$$";
    testHELM1AgainstHELM2(notation);

  }

  @Test
  public void testInlineNotation() throws CTKSmilesException, BuilderMoleculeException, CTKException, NotationException, ParserException, JDOMException, MonomerLoadingException, IOException,
      MonomerException, ChemistryException {

    String notation = "PEPTIDE1{A.G.G.G.C.C.K.K.K.K}|CHEM1{[MCC]}$PEPTIDE1,CHEM1,10:R3-1:R1$$$";
    String smiles = SMILES.getCanonicalSMILESForAll(HELM2NotationUtils.readNotation(notation));

    // replaced A with Smiles String
   // notation = "PEPTIDE1{[C[C@H](N[H:1])C([OH:2])=O].G.G.G.C.C.K.K.K.K}|CHEM1{MCC}$PEPTIDE1,CHEM1,10:R3-1:R1$$$";
    notation = "PEPTIDE1{[C[C@H](N[H:1])C([OH:2])=O].G.G.G.C.C.K.K.K.K}|CHEM1{[MCC]}$PEPTIDE1,CHEM1,10:R3-1:R1$$$";
    String smilesInline = SMILES.getCanonicalSMILESForAll(HELM2NotationUtils.readNotation(notation));
    AssertJUnit.assertEquals(smiles, smilesInline);

    // replaced A with slightly modified A
    notation = "PEPTIDE1{[C[C@H](N[*])C(=O)C[*] |$;;;_R1;;;;_R2$|].G.G.G.C.C.K.K.K.K}|CHEM1{[MCC]}$PEPTIDE1,CHEM1,10:R3-1:R1$$$";

    System.out.println(SMILES.getCanonicalSMILESForAll(HELM2NotationUtils.readNotation(notation)));

  }

  @Test
  public void testGetGenericStructure() throws HELM2HandledException, ChemistryException, IOException, CTKException, ParserException, JDOMException {
    String notation = "CHEM1{[SS3]}|CHEM2{[SS3]}$CHEM1,CHEM2,1:R1-1:R1|CHEM1,CHEM2,1:R2-1:R2$$$";
    SMILES.containsGenericStructurePolymer(HELM2NotationUtils.readNotation(notation).getListOfPolymers());
  }

  @Test
  public void testAttachmentMonomer() throws CTKSmilesException, BuilderMoleculeException, CTKException, NotationException, ChemistryException, ParserException, JDOMException{
	  String notation = "PEPTIDE1{A.A.C.G.[dK].E.C.H.A}$PEPTIDE1,PEPTIDE1,3:R3-7:R3$$$";
	  System.out.println(SMILES.getCanonicalSMILESForAll(HELM2NotationUtils.readNotation(notation)));
  }

  @Test
  public void test() throws MonomerLoadingException, ChemistryException, CTKException{
		String polymerType = "PEPTIDE";
		String monomerID = "C";
		Monomer monomer;

		monomer = MonomerFactory.getInstance().getMonomerStore().getMonomer(polymerType, monomerID);
		SMILES.convertMolToSMILESWithAtomMapping(monomer.getMolfile(), monomer.getAttachmentList());
  }

}


text:
import builtins
import functools
import inspect
import os
import typing

def parseType(name, typeTable):
	if hasattr(builtins, name):
		return getattr(builtins, name)
	if name in typeTable:
		return typeTable[name]
	if '.' in name:
		seek = typeTable
		for part in name.split('.'):
			try:
				if not part in seek:
					break
				seek = seek[part]
			except TypeError:
				if not hasattr(seek, part):
					break
				seek = getattr(seek, part)
		else:
			return seek
	raise ValueError("Unrecognized type: %s" % name)

def describeTypeOf(obj):
	if obj is None:
		return 'None'
	if isinstance(obj, tuple):
		return "tuple of %s" % '/'.join(sorted(set(describeTypeOf(e) for e in obj))) if obj else "tuple"
	if isinstance(obj, list):
		return "list of %s" % '/'.join(sorted(set(describeTypeOf(e) for e in obj))) if obj else "list"
	if isinstance(obj, dict):
		return "map from %s to %s" % ('/'.join(sorted(set(describeTypeOf(k) for k in obj))), '/'.join(sorted(set(describeTypeOf(v) for v in obj.values())))) if obj else "map"
	if isinstance(obj, set):
		return "set of %s" % '/'.join(sorted(set(describeTypeOf(e) for e in obj))) if obj else "set"
	return type(obj).__name__

def describeTypestring(typestring, typeTable):
	typestring = typestring.strip()
	if typestring == '':
		# This isn't illegal at the top level, but verify() wouldn't have called in that case
		# If it happens here it means it's a fragment of a larger expression and can't be empty
		raise ValueError("Empty substring in type string")

	if typestring == 'None':
		return "None"
	if typestring[-1] == '?':
		return "(optional) %s" % describeTypestring(typestring[:-1], typeTable)
	if typestring[-1] == '^':
		return "(implicit) %s" % describeTypestring(typestring[:-1], typeTable)
	ends, rest = typestring[0] + typestring[-1], typestring[1:-1]
	if ends == '()':
		subtypes = rest.split(',')
		if len(subtypes) == 1:
			return "tuple of %s" % describeTypestring(rest, typeTable)
		elif len(subtypes) == 2:
			return "%s or %s" % tuple(describeTypestring(e, typeTable) for e in subtypes)
		else:
			return "%sor %s" % (''.join("%s, " % describeTypestring(e, typeTable) for e in subtypes[:-1]), describeTypestring(subtypes[-1], typeTable))
	if ends == '[]':
		return "list of %s" % describeTypestring(rest, typeTable)
	if ends == '{}':
		if ':' in rest:
			return "map from %s to %s" % tuple(describeTypestring(e, typeTable) for e in rest.split(':', 1))
		else:
			return "set of %s" % describeTypestring(rest, typeTable)

	try:
		return parseType(typestring, typeTable).__name__
	except ValueError as e:
		raise ValueError("Invalid typestring `%s': %s" % (typestring, e))

def verify(typestring, typeTable):
	"""
	Check that 'typestring' is a valid typestring. Throws ValueError if not
	"""
	if typestring == inspect.Parameter.empty:
		return True

	if isinstance(typestring, str):
		pass
	elif isinstance(typestring, tuple) and len(typestring) == 2 and isinstance(typestring[0], str) and callable(typestring[1]):
		typestring = typestring[0]
	else:
		raise ValueError("Invalid typestring `%s': not a string or string/predicate")

	if typestring.strip() == '':
		return True
	describeTypestring(typestring, typeTable) # Will throw ValueError if bad
	return True

def typecheck(typestring, value, typeTable, setter = None):
	"""
	Check that 'value' satisfies 'typestring'.
	If 'setter' is non-None, it may be called to replace the function parameter with a converted instance
	"""

	if typestring == inspect.Parameter.empty:
		return True
	typestring = typestring.strip()
	if typestring == '':
		return True

	# None type
	if typestring == 'None':
		return value is None

	# Optional type, e.g. 'int?'
	if typestring[-1] == '?':
		return (value is None) or typecheck(typestring[:-1], value, typeTable, setter)

	# Convertable type, e.g. 'int^'
	if typestring[-1] == '^':
		substr = typestring[:-1]
		try:
			ty = parseType(substr, typeTable)
		except ValueError as e:
			raise ValueError("Can't implicitly convert to unrecognized type: %s" % substr)

		# Already the proper type; no conversion necessary
		if isinstance(value, ty):
			return True

		# Attempt the conversion
		try:
			ctor = getattr(ty, '__init__')
			# If the constructor is wrapped in a typechecker, get the real constructor
			while hasattr(ctor, 'tcWrappedFn'):
				ctor = ctor.tcWrappedFn
			spec = inspect.getfullargspec(ctor)
			if len(spec.args) != 2: # self + the one parameter
				raise TypeError("constructor is not unary")
			argName = spec.args[1]
			if argName not in spec.annotations:
				raise TypeError("constructor parameter has no type annotation")
			if not typecheck(spec.annotations[argName], value, typeTable):
				raise TypeError("got type [%s]; constructor takes [%s]" % (describeTypeOf(value), describeTypestring(spec.annotations[argName], typeTable)))
			setter(ty(value))
			return True
		except Exception as e:
			raise TypeError("Unable to implicitly convert to %s: %s" % (ty.__name__, e))

	ends, rest = typestring[0] + typestring[-1], typestring[1:-1]

	if ends == '()':
		# Union type, e.g. '(int, str)'
		if ',' in rest:
			return any(typecheck(substr, value, typeTable, setter) for substr in rest.split(','))

		# Tuple type, e.g. '(int)'
		else:
			if not isinstance(value, tuple):
				return False
			return all(typecheck(rest, e, typeTable) for e in value)

	# List type, e.g. '[int]'
	if ends == '[]':
		if not isinstance(value, list):
			return False
		return all(typecheck(rest, e, typeTable, lambda new: value.__setitem__(i, new)) for i, e in enumerate(value))

	if ends == '{}':
		# Dict type, e.g. '{int: int}'
		if ':' in rest:
			if not isinstance(value, dict):
				return False
			keystr, valstr = map(lambda s: s.strip(), rest.split(':', 1))
			def renameKey(old, new):
				value[new] = value[old]
				del value[old]
			return all(typecheck(keystr, k, typeTable, lambda new: renameKey(k, new)) and typecheck(valstr, v, typeTable, lambda new: value.__setitem__(k, new)) for k, v in value.items())

		# Set type, e.g. '{int}'
		else:
			if not isinstance(value, set):
				return False
			def replaceEntry(old, new):
				value.remove(old)
				value.add(new)
			return all(typecheck(rest, e, typeTable, lambda new: replaceEntry(e, new)) for e in value)

	# Bare type, e.g. 'int'
	return isinstance(value, parseType(typestring, typeTable))

@typing.no_type_check_decorator
def tc(f, preVerifyAnnotations = True, nextOverload = None):
	signature = inspect.signature(f)

	# Need to look up types in the scope that 'f' was declared in
	# Scan for the first frame that's within the function's
	fFile = inspect.getsourcefile(f)
	lines, fStartLine = inspect.getsourcelines(f)
	fEndLine = fStartLine + len(lines) - 1
	for frame, filename, lineno, _, _, _ in inspect.stack():
		if filename == fFile and fStartLine <= lineno <= fEndLine:
			typeTable = frame.f_globals
			break
	else:
		raise RuntimeError("Unable to find scope containing the declaration of %s" % f)

	# Make sure the annotations are valid
	if preVerifyAnnotations:
		for param in signature.parameters.values():
			verify(param.annotation, typeTable)
		verify(signature.return_annotation, typeTable)

	@functools.wraps(f)
	def wrap(*args, **kw):
		try:
			binding = signature.bind_partial(*args, **kw)
			for name, param in signature.parameters.items():
				typestring = param.annotation

				# Already did the checking in verify(); at this point typestring is either just the string or a tuple with the string and predicate
				predicate = None
				if isinstance(typestring, tuple):
					typestring, predicate = typestring

				if name in binding.arguments: # If not, using the default value. We could typecheck the default as well, but choosing not to
					value = binding.arguments[name]
					if not typecheck(typestring, value, typeTable, lambda new: binding.arguments.__setitem__(name, new)):
						raise TypeError("Invalid argument `%s' of type [%s]; expected [%s]" % (name, describeTypeOf(binding.arguments[name]), describeTypestring(typestring, typeTable)))
					if predicate is not None:
						result = predicate(value)
						if result is not True:
							result = ("predicate unsatisfied: %s" % result) if result else 'predicate unsatisfied'
							raise TypeError("Invalid argument `%s': %s" % (name, result))

			rtn = {'rtn': f(*binding.args, **binding.kwargs)}

			typestring, predicate = signature.return_annotation, None
			if isinstance(typestring, tuple):
				typestring, predicate = typestring
			if not typecheck(typestring, rtn['rtn'], typeTable, lambda new: rtn.__setitem__('rtn', new)):
				raise TypeError("Invalid return value of type [%s]; expected [%s]" % (describeTypeOf(rtn['rtn']), describeTypestring(typestring, typeTable)))
			if predicate is not None and not predicate(rtn['rtn']):
				raise TypeError("Invalid return value: predicate unsatisfied")
		except TypeError:
			# If there are overloads, move on to those
			if nextOverload is not None:
				try:
					return nextOverload(*args, **kw)
				except TypeError:
					# The overload didn't match; keep the exception chain going
					raise
				except Exception as e:
					# If an overload matched (i.e. didn't raise a TypeError) but then the method threw some other exception, it shouldn't chain into previous TypeErrors raised by overload resolution failures
					raise e from None
			#TODO Right now all the overload type errors come out in a chain because of PEP3134; it'd be nice to generate a single exception that lists all the signatures, but an elegant way to do that escapes me at the moment
			raise

		return rtn['rtn']
	wrap.tcWrappedFn = f
	return wrap

# 'tc' is designed to be used as '@tc', not '@tc()', so it can't take arguments. This version takes arguments and forwards them to tc
def tc_opts(*, verify = True, overload = None):
	def wrap(f):
		return tc(f, verify, overload)
	return wrap


text:
import os
import re
import datetime
import webapp2
from google.appengine.api import memcache
from .utils.to_json import to_json

import jwt
from jwt.contrib.algorithms.pycrypto import RSAAlgorithm
from jwt.contrib.algorithms.py_ecdsa import ECAlgorithm

jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256))
jwt.register_algorithm('ES256', ECAlgorithm(ECAlgorithm.SHA256))

JWT_ALGORITHM = os.environ['JWT_ALGORITHM']
JWT_PUBLIC_KEY = os.environ['JWT_PUBLIC_KEY']
JWT_PRIVATE_KEY = os.environ['JWT_PRIVATE_KEY']
JWT_EXP = os.environ.get('JWT_EXP')
CLIENT = os.environ['CLIENT']

OWNER = os.environ['OWNER']

default_config = {
    'user_model': 'src.user.plugins.UserModel'
}

def import_class(input_cls):
    if not isinstance(input_cls, str):
        # It's a class - return as-is
        return input_cls

    try:
        input_cls = webapp2.import_string(input_cls)
        return input_cls
    except Exception, exc:
        # Couldn't import the class
        raise ValueError("Couldn't import the model class '%s': %s: %s" % (input_cls, Exception, exc))

def user_required(handler):
    def check_signin(self, *args, **kwargs):
        user = self.user
        if user:
            role = user.role
            if role == "owner":
                return handler(self, *args, **kwargs)

            path = self.request.path
            cache_key = "{}:{}".format(role, path)
            if memcache.get(cache_key):
                return handler(self, *args, **kwargs)

            access_authorizations = self.config['access_authorizations']
            my_access_authorizations = access_authorizations.get(role)

            if my_access_authorizations:
                for pattern in my_access_authorizations:
                    result = re.match(pattern, path)
                    if result and result.group(0) == path:
                        memcache.add(cache_key, True, time=1800)
                        return handler(self, *args, **kwargs)

            return self.handle_error_string('You cannot access this resource.', 403)
        else:
            return self.handle_error_string('You need login.', 403)

    return check_signin

class BaseHandler(webapp2.RequestHandler):
    @webapp2.cached_property
    def app(self):
        return webapp2.get_app()

    @webapp2.cached_property
    def config(self):
        return self.app.config.load_config('AUTH', default_values=default_config)

    @webapp2.cached_property
    def user_model(self):
        """Configured user model."""
        cls = self.config['user_model']
        return import_class(cls)

    @webapp2.cached_property
    def user_info(self):
        jwt_token = self.get_jwt_token()
        payload = self.decode_jwt_token(jwt_token)
        return payload

    @webapp2.cached_property
    def user(self):
        user_info = self.user_info
        user_id = user_info.get('id') if user_info else None
        return self.user_model.get_by_id(user_id) if user_id else None

    def get_jwt_token(self):
        jwt_token = self.request.headers.get('Authorization')
        return jwt_token.lstrip("JWT").strip() if jwt_token else None

    @staticmethod
    def decode_jwt_token(jwt_token):
        try:
            return jwt.decode(
                jwt_token, JWT_PUBLIC_KEY, issuer=CLIENT, algorithms=[JWT_ALGORITHM])
        except:
            return None

    @staticmethod
    def encode_jwt_token(payload):
        payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(days=JWT_EXP or 7)
        payload['iat'] = datetime.datetime.utcnow()
        payload['iss'] = CLIENT
        return jwt.encode(payload, JWT_PRIVATE_KEY, JWT_ALGORITHM)

    def handle_error(self, e, status=400):
        self.abort(status, detail='%s: %s' % (type(e).__name__, e.message))

    def handle_error_string(self, s, status=400):
        self.abort(status, detail=s)

    def handle_json(self, obj):
        try:
            self.response.headers[b'Content-Type'] = b'application/json'
            self.response.write(to_json(obj))
        except Exception as e:
            self.handle_error(e)

    def options(self):
        pass

    def dispatch(self):
        try:
            webapp2.RequestHandler.dispatch(self)
        finally:
            self.response.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
            self.response.headers['Access-Control-Allow-Credentials'] = 'true'
            self.response.headers['Access-Control-Allow-Origin'] = CLIENT
            self.response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'


text:
<?php

	/* SVN FILE: $Id$ */

	/**
	 * @author Oliver Lillie (aka buggedcom) <publicmail@buggedcom.co.uk>
	 * @package PHPVideoToolkit
	 * @license BSD
	 * @copyright Copyright (c) 2008 Oliver Lillie <http://www.buggedcom.co.uk>
	 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
	 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
	 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
	 * is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be
	 * included in all copies or substantial portions of the Software.
	 *
	 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
	 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
	 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
	 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
	 */

	echo '<link type="text/css" rel="stylesheet" href="../common/styles.css"><meta name="author" content="Oliver Lillie">';
	echo '← Back to examples list

';
	echo 'This example shows you how to access the information about your ffmpeg installation.

';
	$ignore_demo_files = true;

// 	load the examples configuration
	require_once '../example-config.php';

// 	require the library
	require_once '../../phpvideotoolkit.'.$use_version.'.php';

// 	temp directory
	$tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_PATH.'working'.DS.'tmp'.DS;

// 	start ffmpeg class
	$toolkit = new PHPVideoToolkit($tmp_dir);

// 	get the ffmpeg info
	$info = $toolkit->getFFmpegInfo();

// 	determine the type of support for ffmpeg-php
	echo 'FFmpeg-PHP Support
';

// 	determine if ffmpeg-php is supported
	$has_ffmpeg_php_support = $toolkit->hasFFmpegPHPSupport();
// 	you can also determine if it has ffmpeg php support with below
// 	$has_ffmpeg_php_support = $info['ffmpeg-php-support'];

	switch($has_ffmpeg_php_support)
	{
		case 'module' :
			echo 'Congratulations you have the FFmpeg-PHP module installed.
';
			break;

		case 'emulated' :
			echo 'You haven\'t got the FFmpeg-PHP module installed, however you can use the PHPVideoToolkit\'s adapter\'s to emulate FFmpeg-PHP.
In order to make use of the FFmpeg-PHP adapter class all you need to do is add the following, replacing xxxx with the path to the files, then use FFmpeg-PHP as normal.

	if(!class_exists(\'ffmpeg_movie\'))
	{
		require_once \'xxxx/adapters/ffmpeg-php/ffmpeg_movie.php\';
		require_once \'xxxx/adapters/ffmpeg-php/ffmpeg_frame.php\';
		require_once \'xxxx/adapters/ffmpeg-php/ffmpeg_animated_gif.php\';
	}
Note: It is recommended that if you heavily use FFmpeg-PHP that you install the module.

';
			break;

		case false :
			echo 'You have no support at all for FFmpeg-PHP.
';
			break;
	}

	echo '
This is the information that is accessible about your install of FFmpeg.
';
	echo 'You may also wish to see example 14 which gives you an encode/decode lookup table.';
	echo '
';
	print_r($info);
	echo '
';
    echo '';


text:
'use strict';

const
    webpack = require('webpack'),
    env = require('../env'),
    layout = require('../layout'),
    Html = require('html-webpack-plugin'),
    ExtractTextPlugin = require('extract-text-webpack-plugin'),
    path = require('path'),
    SvgStore = require('webpack-svgstore-plugin');

module.exports = [
    new webpack.DefinePlugin({
        'process.env': JSON.stringify({
            NODE_ENV: env.NODE_ENV,
            PLATFORM: env.PLATFORM,
            API_BASE_URL: env.API_BASE_URL
        })
    }),
    new Html({
        template: layout.src.front.htmlEntry
    }),
    new ExtractTextPlugin('app.css', {
        allChunks: true
    }),
    new SvgStore(
        path.join(layout.src.frontDir, 'app', 'common', 'icons', '*.svg'),
        '',
        {
            name: 'icons.svg',
            chunk: 'main',
            prefix: 'th-',
            svgoOptions: {
                plugins: [
                    { collapseGroups: true },
                    { transformsWithOnePath: true },
                    { convertPathData: true },
                    { cleanupIDs: true },
                    { removeAttrs: {
                        attrs: ['fill']
                    }}
                ]
            }
        }
    )
];


text:
package cz.crcs.ectester.data;

import cz.crcs.ectester.common.ec.*;
import javacard.security.KeyPair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.ext.EntityResolver2;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.function.Function;

/**
 * @author Jan Jancar johny@neuromancer.sk
 */
public class EC_Store {
    private DocumentBuilder db;
    private Map<String, EC_Category> categories;
    private static EC_Store instance;

    private EC_Store() {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {
            SchemaFactory scf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema sch = scf.newSchema(this.getClass().getResource("/cz/crcs/ectester/data/schema.xsd"));
            dbf.setSchema(sch);
            dbf.setNamespaceAware(true);
            dbf.setIgnoringComments(true);
            dbf.setXIncludeAware(true);
            dbf.setIgnoringElementContentWhitespace(true);
            db = dbf.newDocumentBuilder();
            db.setErrorHandler(new ErrorHandler() {
                @Override
                public void warning(SAXParseException exception) throws SAXException {
                    System.err.println("EC_Store | Warning : " + exception);
                }

                @Override
                public void error(SAXParseException exception) throws SAXException {
                    System.err.println("EC_Store | Error : " + exception);
                }

                @Override
                public void fatalError(SAXParseException exception) throws SAXException {
                    System.err.println("EC_Store | Fatal : " + exception);
                    throw new SAXException(exception);
                }
            });
            db.setEntityResolver(new EntityResolver2() {
                @Override
                public InputSource getExternalSubset(String name, String baseURI) throws SAXException, IOException {
                    return null;
                }

                @Override
                public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId) throws SAXException, IOException {
                    InputSource is = new InputSource();
                    is.setSystemId(systemId);
                    is.setByteStream(getClass().getClass().getResourceAsStream("/cz/crcs/ectester/data/" + systemId));
                    return is;
                }

                @Override
                public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                    return null;
                }
            });

            parse();
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
    }

    private void parse() throws SAXException, ParserConfigurationException, IOException {

        InputStream categories = this.getClass().getResourceAsStream("/cz/crcs/ectester/data/categories.xml");
        if (categories == null) {
            throw new IOException();
        }
        Document categoriesDoc = db.parse(categories);
        categories.close();
        categoriesDoc.normalize();

        NodeList catList = categoriesDoc.getElementsByTagName("category");

        this.categories = new TreeMap<>();
        for (int i = 0; i < catList.getLength(); ++i) {
            Node catNode = catList.item(i);
            if (catNode instanceof Element) {
                Element catElem = (Element) catNode;
                Node name = catElem.getElementsByTagName("name").item(0);
                Node dir = catElem.getElementsByTagName("directory").item(0);
                Node desc = catElem.getElementsByTagName("desc").item(0);

                EC_Category category = parseCategory(name.getTextContent(), dir.getTextContent(), desc.getTextContent());
                this.categories.put(name.getTextContent(), category);
            } else {
                throw new SAXException("?");
            }
        }
    }

    private EC_Category parseCategory(String name, String dir, String desc) throws ParserConfigurationException, IOException, SAXException {

        Map<String, EC_Data> objMap = new TreeMap<>();

        InputStream curves = this.getClass().getResourceAsStream("/cz/crcs/ectester/data/" + dir + "/curves.xml");
        if (curves != null) {
            Document curvesDoc = db.parse(curves);
            curvesDoc.normalize();

            NodeList curveList = curvesDoc.getElementsByTagName("curve");

            for (int i = 0; i < curveList.getLength(); ++i) {
                Node curveNode = curveList.item(i);
                if (curveNode instanceof Element) {
                    Element curveElem = (Element) curveNode;
                    Node id = curveElem.getElementsByTagName("id").item(0);
                    Node bits = curveElem.getElementsByTagName("bits").item(0);
                    Node field = curveElem.getElementsByTagName("field").item(0);

                    NodeList descc = curveElem.getElementsByTagName("desc");
                    String descs = null;
                    if (descc.getLength() != 0) {
                        descs = descc.item(0).getTextContent();
                    }

                    byte alg;
                    if (field.getTextContent().equalsIgnoreCase("prime")) {
                        alg = KeyPair.ALG_EC_FP;
                    } else {
                        alg = KeyPair.ALG_EC_F2M;
                    }
                    short bitsize = Short.parseShort(bits.getTextContent());

                    EC_Curve curve = new EC_Curve(id.getTextContent(), bitsize, alg, descs);

                    InputStream csv = parseDataElement(dir, curveElem);
                    if (!curve.readCSV(csv)) {
                        throw new IOException("Invalid csv data." + id.getTextContent());
                    }
                    csv.close();

                    objMap.put(id.getTextContent(), curve);
                } else {
                    throw new SAXException("?");
                }
            }
            curves.close();
        }

        InputStream keys = this.getClass().getResourceAsStream("/cz/crcs/ectester/data/" + dir + "/keys.xml");
        if (keys != null) {
            Document keysDoc = db.parse(keys);
            keysDoc.normalize();

            NodeList directs = keysDoc.getDocumentElement().getChildNodes();
            for (int i = 0; i < directs.getLength(); ++i) {
                Node direct = directs.item(i);
                if (direct instanceof Element) {
                    Element elem = (Element) direct;

                    NodeList ids = elem.getElementsByTagName("id");
                    if (ids.getLength() != 1) {
                        throw new SAXException("key no id?");
                    }
                    String id = ids.item(0).getTextContent();

                    EC_Params result = parseKeylike(dir, elem);

                    objMap.put(id, result);
                } else {
                    throw new SAXException("?");
                }
            }
            keys.close();
        }

        InputStream results = this.getClass().getResourceAsStream("/cz/crcs/ectester/data/" + dir + "/results.xml");
        if (results != null) {
            Document resultsDoc = db.parse(results);
            resultsDoc.normalize();

            NodeList directs = resultsDoc.getDocumentElement().getChildNodes();
            for (int i = 0; i < directs.getLength(); ++i) {
                Node direct = directs.item(i);
                if (direct instanceof Element) {
                    Element elem = (Element) direct;

                    NodeList ids = elem.getElementsByTagName("id");
                    if (ids.getLength() != 1) {
                        throw new SAXException("result no id?");
                    }
                    String id = ids.item(0).getTextContent();

                    EC_Data result = parseResultlike(dir, elem);

                    objMap.put(id, result);
                } else {
                    throw new SAXException("?");
                }
            }
            results.close();
        }

        return new EC_Category(name, dir, desc, objMap);
    }

    private EC_Data parseResultlike(String dir, Element elem) throws SAXException, IOException {
        String tag = elem.getTagName();
        Node id = elem.getElementsByTagName("id").item(0);

        NodeList descc = elem.getElementsByTagName("desc");
        String descs = null;
        if (descc.getLength() != 0) {
            descs = descc.item(0).getTextContent();
        }

        Node curve = elem.getElementsByTagName("curve").item(0);

        EC_Data result;
        if (tag.equals("kaResult")) {
            Node ka = elem.getElementsByTagName("ka").item(0);
            Node onekey = elem.getElementsByTagName("onekey").item(0);
            Node otherkey = elem.getElementsByTagName("otherkey").item(0);

            result = new EC_KAResult(id.getTextContent(), ka.getTextContent(), curve.getTextContent(), onekey.getTextContent(), otherkey.getTextContent(), descs);
        } else if (tag.equals("sigResult")) {
            Node sig = elem.getElementsByTagName("sig").item(0);
            Node signkey = elem.getElementsByTagName("signkey").item(0);
            Node verifykey = elem.getElementsByTagName("verifykey").item(0);
            NodeList datas = elem.getElementsByTagName("raw");
            String data = null;
            if (datas.getLength() != 0) {
                data = datas.item(0).getTextContent();
            }

            result = new EC_SigResult(id.getTextContent(), sig.getTextContent(), curve.getTextContent(), signkey.getTextContent(), verifykey.getTextContent(), data, descs);
        } else {
            throw new SAXException("?");
        }

        InputStream csv = parseDataElement(dir, elem);
        if (!result.readCSV(csv)) {
            throw new IOException("Invalid csv data. " + id.getTextContent());
        }
        csv.close();

        return result;
    }

    private EC_Params parseKeylike(String dir, Element elem) throws SAXException, IOException {
        Node id = elem.getElementsByTagName("id").item(0);
        Node curve = elem.getElementsByTagName("curve").item(0);

        NodeList desc = elem.getElementsByTagName("desc");
        String descs = null;
        if (desc.getLength() != 0) {
            descs = desc.item(0).getTextContent();
        }

        EC_Params result;
        if (elem.getTagName().equals("pubkey")) {
            result = new EC_Key.Public(id.getTextContent(), curve.getTextContent(), descs);
        } else if (elem.getTagName().equals("privkey")) {
            result = new EC_Key.Private(id.getTextContent(), curve.getTextContent(), descs);
        } else if (elem.getTagName().equals("keypair")) {
            result = new EC_Keypair(id.getTextContent(), curve.getTextContent(), descs);
        } else {
            throw new SAXException("?");
        }

        InputStream csv = parseDataElement(dir, elem);
        if (!result.readCSV(csv)) {
            throw new IOException("Invalid CSV data. " + id.getTextContent());
        }
        csv.close();

        return result;
    }

    private InputStream parseDataElement(String dir, Element elem) throws SAXException {
        NodeList file = elem.getElementsByTagName("file");
        NodeList inline = elem.getElementsByTagName("inline");

        InputStream csv;
        if (file.getLength() == 1) {
            csv = this.getClass().getResourceAsStream("/cz/crcs/ectester/data/" + dir + "/" + file.item(0).getTextContent());
        } else if (inline.getLength() == 1) {
            csv = new ByteArrayInputStream(inline.item(0).getTextContent().getBytes());
        } else {
            throw new SAXException("?");
        }
        return csv;
    }

    public Map<String, EC_Category> getCategories() {
        return Collections.unmodifiableMap(categories);
    }

    public EC_Category getCategory(String category) {
        return categories.get(category);
    }

    public Map<String, EC_Data> getObjects(String category) {
        EC_Category cat = categories.get(category);
        if (cat != null) {
            return cat.getObjects();
        }
        return null;
    }

    public <T extends EC_Data> Map<String, T> getObjects(Class<T> objClass, String category) {
        EC_Category cat = categories.get(category);
        if (cat != null) {
            return cat.getObjects(objClass);
        }
        return null;
    }

    public <T extends EC_Data> T getObject(Class<T> objClass, String category, String id) {
        EC_Category cat = categories.get(category);
        if (cat != null) {
            return cat.getObject(objClass, id);
        }
        return null;
    }

    public <T extends EC_Data> T getObject(Class<T> objClass, String query) {
        int split = query.indexOf("/");
        if (split < 0) {
            return null;
        }
        return getObject(objClass, query.substring(0, split), query.substring(split + 1));
    }

    private static <T extends EC_Data> Map<EC_Curve, List<T>> mapKeyToCurve(Collection<T> data, Function<T, String> getter) {
        Map<EC_Curve, List<T>> curves = new TreeMap<>();
        for (T item : data) {
            EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, getter.apply(item));
            List<T> curveKeys = curves.getOrDefault(curve, new LinkedList<>());
            curveKeys.add(item);
            curves.putIfAbsent(curve, curveKeys);
        }
        for (List<T> keyList : curves.values()) {
            Collections.sort(keyList);
        }
        return curves;
    }

    public static <T extends EC_Key> Map<EC_Curve, List<T>> mapKeyToCurve(Collection<T> keys) {
        return mapKeyToCurve(keys, EC_Key::getCurve);
    }

    public static Map<EC_Curve, List<EC_KAResult>> mapResultToCurve(Collection<EC_KAResult> results) {
        return mapKeyToCurve(results, EC_KAResult::getCurve);
    }

    public static <T extends EC_Data> Map<String, List<T>> mapToPrefix(Collection<T> data) {
        Map<String, List<T>> groups = new TreeMap<>();
        for (T item : data) {
            String prefix = item.getId().split("/")[0];
            List<T> group = groups.getOrDefault(prefix, new LinkedList<>());
            group.add(item);
            groups.putIfAbsent(prefix, group);
        }
        for (List<T> itemList : groups.values()) {
            Collections.sort(itemList);
        }
        return groups;
    }

    public static EC_Store getInstance() {
        if (instance == null) {
            instance = new EC_Store();
        }
        return instance;
    }

}


text:
<?php

abstract class PrecheckBase {

/**
 * CakeMigration instance
 *
 * @var CakeMigration
 */
	protected $_migration;

/**
 * Perform check before field create.
 *
 * @param string $table Table to look for
 * @param string $field Field to look for
 * @return bool
 */
	abstract public function checkAddField($table, $field);

/**
 * Perform check before table create.
 *
 * @param string $table Table to look for
 * @return bool
 */
	abstract public function checkCreateTable($table);

/**
 * Perform check before table drop.
 *
 * @param string $table Table to look for
 * @return bool
 */
	abstract public function checkDropTable($table);

/**
 * Perform check before field drop.
 *
 * @param string $table Table to look for
 * @param string $field Field to look for
 * @return bool
 */
	abstract public function checkDropField($table, $field);

/**
 * Check that table exists.
 *
 * @param string $table Table to look for
 * @return bool
 */
	public function tableExists($table) {
		$this->_migration->db->cacheSources = false;
		$tables = $this->_migration->db->listSources();
		return in_array($this->_migration->db->fullTableName($table, false, false), $tables);
	}

/**
 * Check that field exists.
 *
 * @param string $table Table to look for
 * @param string $field Field to look for
 * @return bool
 */
	public function fieldExists($table, $field) {
		if (!$this->tableExists($table)) {
			return false;
		}
		$fields = $this->_migration->db->describe($table);
		return !empty($fields[$field]);
	}

/**
 * Before action precheck callback.
 *
 * @param CakeMigration $migration Migration to perform
 * @param string $type Type of action being performed
 * @param array $data Data passed to action
 * @throws MigrationException
 * @return bool
 */
	public function beforeAction($migration, $type, $data) {
		$this->_migration = $migration;
		switch ($type) {
			case 'create_table':
				return $this->checkCreateTable($data['table']);
			case 'drop_table':
				return $this->checkDropTable($data['table']);
			case 'rename_table':
				return $this->checkCreateTable($data['new_name']) && $this->checkDropTable($data['old_name']);
			case 'add_field':
				return $this->checkAddField($data['table'], $data['field']);
			case 'drop_field':
				return $this->checkDropField($data['table'], $data['field']);
			case 'change_field':
				return true;
			case 'rename_field':
				return $this->checkAddField($data['table'], $data['new_name']) && $this->checkDropField($data['table'], $data['old_name']);
			case 'add_index':
			case 'drop_index':
				return true;
			default:
				throw new MigrationException($this->_migration, sprintf(
					__d('migrations', 'Migration action type (%s) is not one of valid actions type.'), $type
				), E_USER_NOTICE);
		}
	}

}


text:
> [ONLY SPANISH]

### URL:
https://gangsthub.github.io/layout-or-get-out/

## Taller CSS

Charla de CSS orientada a programadores/as que quieren aprender a usar CSS.

* No es una introducción a CSS para diseñadores/as.

* Tampoco pensada para gente con cero conocimientos en la materia.

En 40 minutos, a ver qué entra. ^__^

### Instalación
Instalar con `npm i`

### Uso
Lanzar con `npm start`


text:
import { UI_COMPONENTS } from 'rev-ui/lib/config';

import { MUIListView } from './views/MUIListView';
import { MUIDetailView } from './views/MUIDetailView';
import { MUISearchView } from './views/MUISearchView';

import { MUIActionButton } from './actions/MUIActionButton';

import { MUITextField } from './fields/MUITextField';
import { MUIBooleanField } from './fields/MUIBooleanField';
import { MUIDateField } from './fields/MUIDateField';
import { MUISelectField } from './fields/MUISelectField';
import { MUIMultiSelectField } from './fields/MUIMultiSelectField';
import { MUIRelatedModelField } from './fields/MUIRelatedModelField';

import { MUITextSearchField } from './searchFields/MUITextSearchField';
import { MUISelectSearchField } from './searchFields/MUISelectSearchField';
import { MUIDateSearchField } from './searchFields/MUIDateSearchField';
import { MUIBooleanSearchField } from './searchFields/MUIBooleanSearchField';

export function registerComponents() {

    UI_COMPONENTS.views.ListView = MUIListView;
    UI_COMPONENTS.views.DetailView = MUIDetailView;
    UI_COMPONENTS.views.SearchView = MUISearchView;

    UI_COMPONENTS.actions.PostAction = MUIActionButton;
    UI_COMPONENTS.actions.SaveAction = MUIActionButton;
    UI_COMPONENTS.actions.RemoveAction = MUIActionButton;
    UI_COMPONENTS.actions.SearchAction = MUIActionButton;

    UI_COMPONENTS.fields.TextField = MUITextField;
    UI_COMPONENTS.fields.EmailField = MUITextField;
    UI_COMPONENTS.fields.URLField = MUITextField;
    UI_COMPONENTS.fields.PasswordField = MUITextField;
    UI_COMPONENTS.fields.NumberField = MUITextField;
    UI_COMPONENTS.fields.IntegerField = MUITextField;
    UI_COMPONENTS.fields.AutoNumberField = MUITextField;
    UI_COMPONENTS.fields.BooleanField = MUIBooleanField;
    UI_COMPONENTS.fields.SelectField = MUISelectField;
    UI_COMPONENTS.fields.MultiSelectField = MUIMultiSelectField;
    UI_COMPONENTS.fields.DateField = MUIDateField;
    UI_COMPONENTS.fields.TimeField = MUITextField;
    UI_COMPONENTS.fields.DateTimeField = MUITextField;
    UI_COMPONENTS.fields.RelatedModelField = MUIRelatedModelField;
    UI_COMPONENTS.fields.RelatedModelListField = MUITextField;

    UI_COMPONENTS.searchFields.TextField = MUITextSearchField;
    UI_COMPONENTS.searchFields.EmailField = MUITextSearchField;
    UI_COMPONENTS.searchFields.URLField = MUITextSearchField;
    UI_COMPONENTS.searchFields.PasswordField = MUITextSearchField;
    UI_COMPONENTS.searchFields.NumberField = MUITextSearchField;
    UI_COMPONENTS.searchFields.IntegerField = MUITextSearchField;
    UI_COMPONENTS.searchFields.AutoNumberField = MUITextSearchField;
    UI_COMPONENTS.searchFields.BooleanField = MUIBooleanSearchField;
    UI_COMPONENTS.searchFields.SelectField = MUISelectSearchField;
    UI_COMPONENTS.searchFields.MultiSelectField = MUISelectSearchField;
    UI_COMPONENTS.searchFields.DateField = MUIDateSearchField;
    UI_COMPONENTS.searchFields.TimeField = MUITextSearchField;
    UI_COMPONENTS.searchFields.DateTimeField = MUITextSearchField;
    UI_COMPONENTS.searchFields.RelatedModelField = MUITextSearchField;
    UI_COMPONENTS.searchFields.RelatedModelListField = MUITextSearchField;

}


text:
<component
	id="ChangeLog_databound_res"
	title="Databound - Community Common"
	path="databound/res"
	handlerType="div"
	group="ScnCommunityFramework"
	filterStart="org.scn.community."
>

</component>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Returns the number of inputs in each of the training patterns in the train data</title>

fann_merge_train_data

fann_num_output_train_data

Fann Functions

PHP Manual

fann_num_input_train_data

(PECL fann >= 1.0.0)

fann_num_input_train_data — Returns the number of inputs in each of the training patterns in the train data

Description

   int fann_num_input_train_data
    ( resource $data
   )

   Returns the number of inputs in each of the training patterns in the train data resource.

Parameters

data

Neural network training data resource.

Return Values

    The number of inputs, or FALSE on error.

See Also

fann_length_train_data() - Returns the number of training patterns in the train data

fann_num_output_train_data() - Returns the number of outputs in each of the training patterns in the train data

fann_merge_train_data

fann_num_output_train_data

Fann Functions

PHP Manual


text:
package com.vladmihalcea.book.hpjp.hibernate.time;

import com.vladmihalcea.book.hpjp.util.AbstractMySQLIntegrationTest;
import org.hibernate.cfg.AvailableSettings;
import org.junit.Test;

import jakarta.persistence.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Properties;

import static org.junit.Assert.assertEquals;

/**
 * @author Vlad Mihalcea
 */
public class JavaUtilDateTest extends AbstractMySQLIntegrationTest {

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[]{
            Post.class,
            UserAccount.class
        };
    }

    @Override
    protected void additionalProperties(Properties properties) {
        properties.setProperty(AvailableSettings.JDBC_TIME_ZONE, "UTC");
    }

    @Test
    public void test() {
        doInJPA(entityManager -> {
            UserAccount user = new UserAccount()
                .setId(1L)
                .setFirstName("Vlad")
                .setLastName("Mihalcea")
                .setSubscribedOn(
                    parseDate("2020-05-01")
                );

            Post post = new Post()
                .setId(1L)
                .setTitle("High-Performance Java Persistence")
                .setCreatedBy(user)
                .setPublishedOn(
                    parseTimestamp("2020-05-01 12:30:00")
                );

            entityManager.persist(user);

            entityManager.persist(post);
        });

        doInJPA(entityManager -> {
            Post post = entityManager.find(
                Post.class, 1L
            );

            assertEquals(
                parseTimestamp("2020-05-01 12:30:00"),
                post.getPublishedOn()
            );

            UserAccount userAccount = post.getCreatedBy();

            assertEquals(
                parseDate("2020-05-01"),
                userAccount.getSubscribedOn()
            );
        });
    }

    private final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    private final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private java.util.Date parseDate(String date) {
        try {
            return DATE_FORMAT.parse(date);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }

    private java.util.Date parseTimestamp(String timestamp) {
        try {
            return DATE_TIME_FORMAT.parse(timestamp);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }

    @Entity(name = "Post")
    @Table(name = "post")
    public static class Post {

        @Id
        private Long id;

        @Column(length = 100)
        private String title;

        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "user_account_id")
        private UserAccount createdBy;

        @Column(name = "published_on")
        @Temporal(TemporalType.TIMESTAMP)
        private java.util.Date publishedOn;

        public Long getId() {
            return id;
        }

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

        public String getTitle() {
            return title;
        }

        public Post setTitle(String title) {
            this.title = title;
            return this;
        }

        public UserAccount getCreatedBy() {
            return createdBy;
        }

        public Post setCreatedBy(UserAccount createdBy) {
            this.createdBy = createdBy;
            return this;
        }

        public java.util.Date getPublishedOn() {
            return publishedOn;
        }

        public Post setPublishedOn(java.util.Date publishedOn) {
            this.publishedOn = publishedOn;
            return this;
        }
    }

    @Entity(name = "UserAccount")
    @Table(name = "user_account")
    public static class UserAccount {

        @Id
        private Long id;

        @Column(name = "first_name", length = 50)
        private String firstName;

        @Column(name = "last_name", length = 50)
        private String lastName;

        @Column(name = "subscribed_on")
        @Temporal(TemporalType.DATE)
        private java.util.Date subscribedOn;

        public Long getId() {
            return id;
        }

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

        public String getFirstName() {
            return firstName;
        }

        public UserAccount setFirstName(String firstName) {
            this.firstName = firstName;
            return this;
        }

        public String getLastName() {
            return lastName;
        }

        public UserAccount setLastName(String lastName) {
            this.lastName = lastName;
            return this;
        }

        public java.util.Date getSubscribedOn() {
            return subscribedOn;
        }

        public UserAccount setSubscribedOn(java.util.Date subscribedOn) {
            this.subscribedOn = subscribedOn;
            return this;
        }
    }
}


text:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Kuno.Domain;
using Kuno.Logging;
using Kuno.Validation;

namespace Kuno.Search
{
    /// <summary>
    /// Manages a search index with methods to immediately add an item to the index.
    /// </summary>
    /// <typeparam name="TSearchResult">The type of the search result.</typeparam>
    /// <seealso cref="ISearchIndex{TSearchResult}" />
    public class SearchIndex<TSearchResult> : ISearchIndex<TSearchResult> where TSearchResult : class, ISearchResult
    {
        private readonly ISearchContext _context;

        /// <summary>
        /// Initializes a new instance of the <see cref="SearchIndex{TSearchResult}" /> class.
        /// </summary>
        /// <param name="context">The configured requestContext.</param>
        public SearchIndex(ISearchContext context)
        {
            Argument.NotNull(context, nameof(context));

            _context = context;
        }

        /// <summary>
        /// Gets or sets the configured <see cref="IDomainFacade" />.
        /// </summary>
        /// <value>The configured <see cref="IDomainFacade" />.</value>
        public IDomainFacade Domain { get; set; }

        /// <summary>
        /// Gets or sets the configured <see cref="ILogger" />.
        /// </summary>
        /// <value>The configured <see cref="ILogger" />.</value>
        public ILogger Logger { get; set; }

        /// <summary>
        /// Adds the specified instances to the index immediately. Add is similar to Update, but skips a check to see if the
        /// item already exists.
        /// </summary>
        /// <param name="instances">The instances to add immediately.</param>
        /// <returns>A task for asynchronous programming.</returns>
        public virtual Task AddAsync(params TSearchResult[] instances)
        {
            Argument.NotNull(instances, nameof(instances));

            this.Logger.Verbose($"Adding {instances.Count()} items of type {typeof(TSearchResult)} using {_context.GetType()}.");

            return _context.AddAsync(instances);
        }

        /// <summary>
        /// Clears all instances of the specified type.
        /// </summary>
        /// <returns>A task for asynchronous programming.</returns>
        public virtual Task ClearAsync()
        {
            this.Logger.Verbose($"Clearing all items of type {typeof(TSearchResult)} using {_context.GetType()}.");

            return _context.ClearAsync<TSearchResult>();
        }

        /// <summary>
        /// Opens a query that can be used to filter and project.
        /// </summary>
        /// <param name="text">The text to use for search.</param>
        /// <returns>An IQueryable<TSearchResult> that can be used to filter and project.</returns>
        public virtual IQueryable<TSearchResult> Search(string text = null)
        {
            this.Logger.Verbose($"Opening a query for type {typeof(TSearchResult)} using {_context.GetType()}.");

            return _context.Search<TSearchResult>(text);
        }

        /// <summary>
        /// Removes all instances that match the specified predicate.
        /// </summary>
        /// <param name="predicate">The predicate to match.</param>
        /// <returns>A task for asynchronous programming.</returns>
        public virtual Task RemoveAsync(Expression<Func<TSearchResult, bool>> predicate)
        {
            this.Logger.Verbose($"Removing items of type {typeof(TSearchResult)} using {_context.GetType()}.");

            return _context.RemoveAsync(predicate);
        }

        /// <inheritdoc />
        public virtual Task Index(params string[] ids)
        {
            return Task.FromResult(0);
        }

        /// <summary>
        /// Removes the specified instances.
        /// </summary>
        /// <param name="instances">The instances to remove.</param>
        /// <returns>A task for asynchronous programming.</returns>
        public virtual Task RemoveAsync(params TSearchResult[] instances)
        {
            Argument.NotNull(instances, nameof(instances));

            this.Logger.Verbose($"Removing {instances.Count()} items of type {typeof(TSearchResult)} using {_context.GetType()}.");

            return _context.RemoveAsync(instances);
        }

        /// <summary>
        /// Finds the instance with the specified identifier.
        /// </summary>
        /// <param name="id">The instance identifier.</param>
        /// <returns>Returns the instance with the specified identifier.</returns>
        public virtual Task<TSearchResult> FindAsync(int id)
        {
            this.Logger.Verbose($"Finding item of type {typeof(TSearchResult)} with ID {id} using {_context.GetType()}.");

            return _context.FindAsync<TSearchResult>(id);
        }

        /// <summary>
        /// Rebuilds the search index.
        /// </summary>
        /// <returns>A task for asynchronous programming.</returns>
        public virtual Task RebuildIndexAsync()
        {
            this.Logger.Verbose($"Rebuilding index for items of type {typeof(TSearchResult)} using {_context.GetType()}.");

            return Task.FromResult(0);
        }

        /// <summary>
        /// Updates the specified instances immediately. Update is similar to Add, but Add skips a check to see if the
        /// item already exists.
        /// </summary>
        /// <param name="instances">The instances to update immediately.</param>
        /// <returns>A task for asynchronous programming.</returns>
        public virtual Task UpdateAsync(params TSearchResult[] instances)
        {
            Argument.NotNull(instances, nameof(instances));

            this.Logger.Verbose($"Updating {instances.Count()} items of type {typeof(TSearchResult)} using {_context.GetType()}.");

            return _context.UpdateAsync(instances);
        }

        /// <summary>
        /// Updates all instances found using the specified predicate and uses the provided expression for the update.
        /// </summary>
        /// <param name="predicate">The predicate to match.</param>
        /// <param name="expression">The update to make.</param>
        /// <returns>A task for asynchronous programming.</returns>
        /// <exception cref="System.NotSupportedException"></exception>
        public virtual Task UpdateAsync(Expression<Func<TSearchResult, bool>> predicate, Expression<Func<TSearchResult, TSearchResult>> expression)
        {
            throw new NotSupportedException();
        }
    }
}


text:
<?php

namespace OG\Account\Domain\Identity\Model;

/**
 * Specification for an alias.
 */
interface AliasSpecification
{
    /**
     * Check to see if the specification is satisfied.
     *
     * @param Email $email
     *
     * @return bool
     */
    public function isSatisfiedBy(Email $email);
}


text:
import os
import pdb
import platform
import warnings
import sysconfig
import ctypes as ct
import numpy as np
from cudamat import generate_exception

if platform.system() == 'Windows':
    os.environ['PATH'] += ";" + os.path.dirname(__file__)
    _cudalearn = ct.cdll.LoadLibrary('libcudalearn.dll')
else:
    _cudalearn = ct.cdll.LoadLibrary(os.path.join(os.path.dirname(__file__) or os.path.curdir,
                                                  'libcudalearn' + sysconfig.get_config_var('SO')))

_cudalearn.mult_by_sigmoid_deriv.restype = ct.c_int

def mult_by_sigmoid_deriv(target, acts):
    """
    target = target * acts * (1 - acts)

    Useful for doing backprop in neural networks with logistic units.
    """

    err_code = _cudalearn.mult_by_sigmoid_deriv(target.p_mat, acts.p_mat)
    if err_code:
        raise generate_exception(err_code)


text:
import os, sys
os.chdir("../")
sys.setrecursionlimit(100000)
sys.path.append(os.path.abspath(""))
os.chdir("./Utility")
from Utility.Utils import getWordTag

def compare(taggedCorpus, goldenCorpus):
    """
    To calculate the the performance on POS tagging
    """
    outputTokens = open(taggedCorpus, "r").read().split()
    standardTokens = open(goldenCorpus, "r").read().split()
    if len(outputTokens) != len(standardTokens):
        print "The numbers of tokens are not equal!"
        return 0
    numwords = 0
    count = 0
    for i in xrange(len(outputTokens)):
        numwords += 1
        word1, tag1 = getWordTag(outputTokens[i])
        word2, tag2 = getWordTag(standardTokens[i])
        if word1 != word2:
            print "Data not equal in position", i
            print outputTokens[i], standardTokens[i-1], standardTokens[i], standardTokens[i+1]
            return 0
        if tag1.lower() == tag2.lower():
            count += 1
        #else:
        #   print outputTokens[i-1], outputTokens[i], outputTokens[i+1], "<=>", standardTokens[i-1], standardTokens[i], standardTokens[i+1]
    return count * 100 / float(len(outputTokens))

if __name__ == "__main__":
    print compare(sys.argv[1:][0], sys.argv[1:][1]), "%"
    pass


text:
require 'toy_robot'
require 'rspec'

RSpec.configure do |config|
  config.before(:suite) do
  end

  config.before(:each) do
  end

  config.after(:each) do
  end
end


text:
(function () {
  var app = angular.module('nya-chan', ['angular-loading-bar', 'ngCookies', 'vcRecaptcha', 'toastr','ui.bootstrap'])
    .config(['cfpLoadingBarProvider', function (cfpLoadingBarProvider) {
      cfpLoadingBarProvider.includeSpinner = false
    }])

  app.controller('tagController', function ($scope, $http, $window, $cookies, $cookieStore, vcRecaptchaService, toastr) {

    $scope.init = function () {
      $scope.isUserLogged = false
      $scope.isUserAdmin = false
      if ($cookies.get('user') !== undefined) {
        var user = JSON.parse($cookies.get('user'))
        $scope.userName = user.login
        $scope.userImage = user.avatar
        $scope.isUserLogged = true
        $scope.isUserAdmin = user.role === 'admin'
      } else {
        $scope.userName = 'Anon'
      }
    }

    $scope.reportPost = function(threadIdReport, postIdReport){
      var dataReport = {
        reason: null,
        threadId: threadIdReport,
        postId: postIdReport
      }
      $http({
        method: 'POST',
        url: 'https://nyachan-server.herokuapp.com/api/reportPost',
        // url: "http://localhost:3000/api/reportPost",
        data: dataReport,
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(function mySucces (response) {
        toastr.success('Report completed', 'Success')
      }, function myError (response) {
        console.log('Error ' + response.body)
      })
    }

    $scope.banIP = function(){
      // var dataReport = {
      //   reason: null,
      //   threadId: threadIdReport,
      //   postId: postIdReport
      // }
      // $http({
      //   method: 'POST',
      //   // url: 'https://nyachan-server.herokuapp.com/api/reportPost',
      //   url: "http://localhost:3000/api/reportPost",
      //   data: dataReport,
      //   headers: {
      //     'Content-Type': 'application/json'
      //   }
      // }).then(function mySucces (response) {
      //   toastr.success('Report completed', 'Success')
      // }, function myError (response) {
      //   console.log('Error ' + response.body)
      // })
    }

    $scope.deleteThread = function(threadId){
      var dataDelete = {
        user: JSON.parse($cookies.get('user')),
        thread: threadId
      }
      $http({
        method: 'DELETE',
        url: 'https://nyachan-server.herokuapp.com/api/delete/thread',
        // url: "http://localhost:3000/api/delete/thread",
        data: dataDelete,
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(function mySucces (response) {
        $scope.threads = $scope.search()
        toastr.success('Thread deleted', 'Success')
      }, function myError (response) {
        console.log('Error ' + response.body)
      })
    }

    $scope.time_zone = new Date().getTimezoneOffset()
    var url = $(location).attr('href')
    var searchTag = url.substring(url.lastIndexOf('/') + 1)
    var tagName = 'Anime'

    switch (searchTag) {
      case 'a':
        tagName = 'Anime & Manga'
        break
      case 'c':
        tagName = 'Cartoon & Comics'
        break
      case 'g':
        tagName = 'Gif & Webm'
        break
      case 'h':
        tagName = 'History & Humanities'
        break
      case 'm':
        tagName = 'Music'
        break
      case 't':
        tagName = 'Tecnology'
        break
      case 'tv':
        tagName = 'Movies & Television'
        break
      case 'v':
        tagName = 'Video Games'
        break
      case 'b':
        tagName = 'Random'
        break
      case 'p':
        tagName = 'Politically Incorrect'
        break
      default:
        tagName = 'Random'
    }
    $scope.tag = searchTag
    $scope.tagName = tagName

    $scope.response = null
    $scope.widgetId = null

    $scope.setResponse = function (response) {
      console.info('Response available')
      $scope.response = response
    }

    $scope.model = {
      key: '6LfogRgUAAAAACNUIiCwMJPsPJ0NxiS7tafx-B55'
    }

    $scope.setWidgetId = function (widgetId) {
      console.info('Created widget ID: %s', widgetId)
      $scope.widgetId = widgetId
    }

    $scope.cbExpiration = function () {
      console.info('Captcha expired. Resetting response object')
      vcRecaptchaService.reload($scope.widgetId)
      $scope.response = null
    }

    $scope.setResponse = function (response) {
      console.info('Response available')
      $scope.response = response
    }

    $scope.search = function () {
      $http({
        method: 'GET',
        url: 'https://nyachan-server.herokuapp.com/api/tag/' + searchTag + '?sortType=lastDate&archived=false'
                // url: "http://localhost:3000/api/tag/" + searchTag + '?sortType=lastDate&archived=false'
      }).then(function mySucces (response) {
        $scope.threads = response.data
      }, function myError (response) {
        $window.location.href = 'https://nyachan-server.herokuapp.com/404'
      })
    }
    $scope.threads = $scope.search()

    $scope.createThread = function (post) {
      $http({
        url: 'https://nyachan-server.herokuapp.com/recaptcha',
        method: 'POST',
        data: {'response': $scope.response},
        headers: {
          'Content-Type': 'application/json; charset=utf-8'
        }
      }).then(function successCallback (response) {
        validatedPost(JSON.parse(response.data.body).success)
      }, function errorCallback (response) {
        console.log(response)
      })

      function validatedPost (valid) {
        if (valid) {

        } else {
          vcRecaptchaService.reload($scope.widgetId)
          return
        }
        var selectedOptions = $('#selectTags option:selected')
        // console.log(selectedOptions[0].value);
        if (selectedOptions.lenght === 0) {
          alert('Selecione ao menos uma Tag')
          return // Mensagem erro
        }
        var selectTags = []
        for (var i = 0; i < selectedOptions.length; i++) {
          selectTags.push(selectedOptions[i].value)
        }

        var files = $('#file')[0].files
        if (post === undefined) {
          post = {}
          post.body = ' '
        }

        if (!validarPost(post, files)) {
          return
        }

        if (files !== undefined && files.length > 0) {
          if (!validFile(files[0].name)) {
            alert('Arquivo Invalido')
            return
          }
        }
        var uploadedFiles = []
        if (files !== undefined && files.length > 0) {

          var sendFilesToDropbox = function (i, files, uploadedFiles) {
            var formData = new FormData()
            formData.append('fileData', files[i])
            var xhr = new XMLHttpRequest()
            xhr.onreadystatechange = function () {
              if (xhr.readyState === XMLHttpRequest.DONE) {
                var uploadedFile = JSON.parse(xhr.response)
                uploadedFiles[i] = uploadedFile
                if (i >= files.length - 1) {
                  $('#loader').width('90%')
                  sendThread(files, uploadedFiles)
                } else {
                  sendFilesToDropbox(i + 1, files, uploadedFiles)
                }
              }
            }
            xhr.upload.addEventListener('progress', function (evt) {
              if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total
                percentComplete = (percentComplete / files.length) * (i + 1)
                $('#loader').width(Math.round(percentComplete * 75) + '%')
              }
            }, false)
            xhr.open('post', '/dbxPost/1/0', true)
            xhr.send(formData)
            console.log('UPLOAD ' + i)
          }
          sendFilesToDropbox(0, files, uploadedFiles)
        } else {
          sendThread(undefined, undefined)
        }

        function sendThread (files, uploadedFiles) {
          if (files !== undefined && files.length > 0) {
            var dataPost = {
              body: post.body,
              date: '2016-01-02 19:33:00',
              archived: false,
              subject: post.title,
              userName: $scope.userName,
              tags: selectTags,
              file: filesToJSON(files, uploadedFiles)
            }
          } else {
            var dataPost = {
              body: post.body,
              date: '2016-01-02 19:33:00',
              archived: false,
              subject: post.title,
              userName: $scope.userName,
              tags: selectTags
            }
          }

          $http({
            method: 'POST',
            url: 'https://nyachan-server.herokuapp.com/api/thread/newThread',
            // url: "http://localhost:3000/api/thread/newThread",
            data: dataPost,
            headers: {
              'Content-Type': 'application/json'
            }
          }).then(function mySucces (response) {
            $('#loader').width('100%')
            setTimeout(function(){
              $scope.threads = $scope.search()
              vcRecaptchaService.reload($scope.widgetId)
              $('#newThreadModal').modal('hide')
              $('#loader').width('0%')
            }, 1500)
            toastr.success('Nice Thread created', 'Success')
          }, function myError (response) {
            console.log(response || 'Request failed')
            if(response.data === "User is banned"){
              toastr.error('You were banned!', 'Error')
            }else{
              toastr.error('OMG, its dead!', 'Error')
            }
          })
        }
      }
    }

    $scope.downloadFiles = function(imgFiles)
    {
      var getSingleBinCont = function (zip, value) {
          var deferred = $.Deferred()
          var trueLink = value.source.replace("www.dropbox.com", "dl.dropboxusercontent.com")
          JSZipUtils.getBinaryContent(trueLink, function (err, data){
              if(err){
                  deferred.reject(err)
              }
              else{
                  zip.file(value.name, data, {binary:true})
                  deferred.resolve(data)
              }
          });
          return deferred
      }
      var downloadZip = function (){
        var zip = new JSZip()
        var deferreds = []

        angular.forEach(imgFiles, function (value, key){
            deferreds.push(getSingleBinCont(zip, value))
        });
        $.when.apply($, deferreds).done(function () {
            var blob = zip.generateAsync({type:"blob"}).then(function(content) {
                saveAs(content, "images.zip");
            });
        });
      }
      downloadZip()
    }

    $scope.logoutUser = function () {
      $http({
        method: 'GET',
        url: 'https://nyachan-server.herokuapp.com/logout',
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(function mySucces (response) {
        $scope.isUserLogged = false
        $cookies.remove('user', { path:'/' })
        toastr.success('Goodbye', 'See you soon')
      }, function myError (response) {
        console.log(response || 'Request failed')
      })
    }
  })
})()


text:
/**
 * Created by CnJon on 16/1/21.
 */
'use strict';

import React,{Component, PropTypes} from 'react';
import {
    NativeModules,
    View,
} from 'react-native';

const RCTDateTimePicker = NativeModules.DateTimePicker;

export default class DateTimePicker extends Component {
    static propTypes = {
        cancelText: PropTypes.string,
        okText:  PropTypes.string
    };

    static defaultProps = {
        cancelText: 'Cancel',
        okText: 'Ok'
    };

    constructor(props) {
        super(props);
    }

    showDatePicker(date, callback) {
        date = date || new Date();
        var options = {
            ...this.props,
            year:date.getFullYear(),
            month:date.getMonth(),
            day:date.getDate()
        };
        RCTDateTimePicker.showDatePicker(options, function (year, month, day) {
            date.setFullYear(year);
            date.setMonth(month);
            date.setDate(day);
            callback(date);
        });
    }

    showTimePicker(date, callback) {
        date = date || new Date();
        var options = {
            ...this.props,
            hour:date.getHours(),
            minute:date.getMinutes()
        };
        RCTDateTimePicker.showTimePicker(options, function (hour, minute) {
            date.setHours(hour);
            date.setMinutes(minute);
            callback(date);
        });
    }

    showDateTimePicker(date, callback) {
        date = date || new Date();
        var options = {
            ...this.props,
            year:date.getFullYear(),
            month:date.getMonth(),
            day:date.getDate(),
            hour:date.getHours(),
            minute:date.getMinutes()
        };
        RCTDateTimePicker.showDateTimePicker(options, function (year, month, day, hour, minute) {
            date.setFullYear(year);
            date.setMonth(month);
            date.setDate(day);
            date.setHours(hour);
            date.setMinutes(minute);
            callback(date);
        });
    }

    render() {
        return null;
    }
}