text:
package resource_test

import (
	"io/ioutil"
	"os"
	"path/filepath"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/concourse/github-release-resource"
	"github.com/concourse/github-release-resource/fakes"

	"github.com/zachgersh/go-github/github"
)

func file(path, contents string) {
	Ω(ioutil.WriteFile(path, []byte(contents), 0644)).Should(Succeed())
}

var _ = Describe("Out Command", func() {
	var (
		command      *resource.OutCommand
		githubClient *fakes.FakeGitHub

		sourcesDir string

		request  resource.OutRequest
		response resource.OutResponse
	)

	BeforeEach(func() {
		var err error

		githubClient = &fakes.FakeGitHub{}
		command = resource.NewOutCommand(githubClient, ioutil.Discard)

		sourcesDir, err = ioutil.TempDir("", "github-release")
		Ω(err).ShouldNot(HaveOccurred())

		githubClient.CreateReleaseStub = func(gh github.RepositoryRelease) (*github.RepositoryRelease, error) {
			createdRel := gh
			createdRel.ID = github.Int(112)
			createdRel.HTMLURL = github.String("http://google.com")
			createdRel.Name = github.String("release-name")
			createdRel.Body = github.String("*markdown*")
			return &createdRel, nil
		}

		githubClient.UpdateReleaseStub = func(gh github.RepositoryRelease) (*github.RepositoryRelease, error) {
			return &gh, nil
		}
	})

	JustBeforeEach(func() {
		var err error
		response, err = command.Run(sourcesDir, request)
		Ω(err).ShouldNot(HaveOccurred())
	})

	AfterEach(func() {
		Ω(os.RemoveAll(sourcesDir)).Should(Succeed())
	})

	Context("when the release has already been created", func() {
		existingAssets := []github.ReleaseAsset{
			{
				ID:   github.Int(456789),
				Name: github.String("unicorns.txt"),
			},
			{
				ID:   github.Int(3450798),
				Name: github.String("rainbows.txt"),
			},
		}

		BeforeEach(func() {
			githubClient.ListReleasesReturns([]github.RepositoryRelease{
				{
					ID:      github.Int(112),
					TagName: github.String("some-tag-name"),
					Assets:  existingAssets,
				},
			}, nil)

			namePath := filepath.Join(sourcesDir, "name")
			bodyPath := filepath.Join(sourcesDir, "body")
			tagPath := filepath.Join(sourcesDir, "tag")

			file(namePath, "v0.3.12")
			file(bodyPath, "this is a great release")
			file(tagPath, "some-tag-name")

			request = resource.OutRequest{
				Params: resource.OutParams{
					NamePath: "name",
					BodyPath: "body",
					TagPath:  "tag",
				},
			}
		})

		It("deletes the existing assets", func() {
			Ω(githubClient.DeleteReleaseAssetCallCount()).Should(Equal(2))

			Ω(githubClient.DeleteReleaseAssetArgsForCall(0)).Should(Equal(existingAssets[0]))
			Ω(githubClient.DeleteReleaseAssetArgsForCall(1)).Should(Equal(existingAssets[1]))
		})

		Context("when a commitish is not supplied", func() {
			It("updates the existing release", func() {
				Ω(githubClient.UpdateReleaseCallCount()).Should(Equal(1))

				updatedRelease := githubClient.UpdateReleaseArgsForCall(0)
				Ω(*updatedRelease.Name).Should(Equal("v0.3.12"))
				Ω(*updatedRelease.Body).Should(Equal("this is a great release"))
				Ω(updatedRelease.TargetCommitish).Should(Equal(github.String("")))
			})
		})

		Context("when a commitish is supplied", func() {
			BeforeEach(func() {
				commitishPath := filepath.Join(sourcesDir, "commitish")
				file(commitishPath, "1z22f1")
				request.Params.CommitishPath = "commitish"
			})

			It("updates the existing release", func() {
				Ω(githubClient.UpdateReleaseCallCount()).Should(Equal(1))

				updatedRelease := githubClient.UpdateReleaseArgsForCall(0)
				Ω(*updatedRelease.Name).Should(Equal("v0.3.12"))
				Ω(*updatedRelease.Body).Should(Equal("this is a great release"))
				Ω(updatedRelease.TargetCommitish).Should(Equal(github.String("1z22f1")))
			})
		})
	})

	Context("when the release has not already been created", func() {
		BeforeEach(func() {
			namePath := filepath.Join(sourcesDir, "name")
			tagPath := filepath.Join(sourcesDir, "tag")

			file(namePath, "v0.3.12")
			file(tagPath, "0.3.12")

			request = resource.OutRequest{
				Params: resource.OutParams{
					NamePath: "name",
					TagPath:  "tag",
				},
			}
		})

		Context("with a commitish", func() {
			BeforeEach(func() {
				commitishPath := filepath.Join(sourcesDir, "commitish")
				file(commitishPath, "a2f4a3")
				request.Params.CommitishPath = "commitish"
			})

			It("creates a release on GitHub with the commitish", func() {
				Ω(githubClient.CreateReleaseCallCount()).Should(Equal(1))
				release := githubClient.CreateReleaseArgsForCall(0)

				Ω(release.TargetCommitish).Should(Equal(github.String("a2f4a3")))
			})
		})

		Context("without a commitish", func() {
			It("creates a release on GitHub without the commitish", func() {
				Ω(githubClient.CreateReleaseCallCount()).Should(Equal(1))
				release := githubClient.CreateReleaseArgsForCall(0)

				// GitHub treats empty string the same as not suppying the field.
				Ω(release.TargetCommitish).Should(Equal(github.String("")))
			})
		})

		Context("with a body", func() {
			BeforeEach(func() {
				bodyPath := filepath.Join(sourcesDir, "body")
				file(bodyPath, "this is a great release")
				request.Params.BodyPath = "body"
			})

			It("creates a release on GitHub", func() {
				Ω(githubClient.CreateReleaseCallCount()).Should(Equal(1))
				release := githubClient.CreateReleaseArgsForCall(0)

				Ω(*release.Name).Should(Equal("v0.3.12"))
				Ω(*release.TagName).Should(Equal("0.3.12"))
				Ω(*release.Body).Should(Equal("this is a great release"))
			})
		})

		Context("without a body", func() {
			It("works", func() {
				Ω(githubClient.CreateReleaseCallCount()).Should(Equal(1))
				release := githubClient.CreateReleaseArgsForCall(0)

				Ω(*release.Name).Should(Equal("v0.3.12"))
				Ω(*release.TagName).Should(Equal("0.3.12"))
				Ω(*release.Body).Should(Equal(""))
			})
		})

		Context("with file globs", func() {
			BeforeEach(func() {
				globMatching := filepath.Join(sourcesDir, "great-file.tgz")
				globNotMatching := filepath.Join(sourcesDir, "bad-file.txt")

				file(globMatching, "matching")
				file(globNotMatching, "not matching")

				request = resource.OutRequest{
					Params: resource.OutParams{
						NamePath: "name",
						BodyPath: "body",
						TagPath:  "tag",

						Globs: []string{
							"*.tgz",
						},
					},
				}

				bodyPath := filepath.Join(sourcesDir, "body")
				file(bodyPath, "*markdown*")
				request.Params.BodyPath = "body"
			})

			It("uploads matching file globs", func() {
				Ω(githubClient.UploadReleaseAssetCallCount()).Should(Equal(1))
				release, name, file := githubClient.UploadReleaseAssetArgsForCall(0)

				Ω(*release.ID).Should(Equal(112))
				Ω(name).Should(Equal("great-file.tgz"))
				Ω(file.Name()).Should(Equal(filepath.Join(sourcesDir, "great-file.tgz")))
			})

			It("has some sweet metadata", func() {
				outResponse, err := command.Run(sourcesDir, request)
				Ω(err).ShouldNot(HaveOccurred())

				Ω(outResponse.Metadata).Should(ConsistOf(
					resource.MetadataPair{Name: "url", Value: "http://google.com"},
					resource.MetadataPair{Name: "name", Value: "release-name", URL: "http://google.com"},
					resource.MetadataPair{Name: "body", Value: "*markdown*", Markdown: true},
				))
			})

			It("returns an error if a glob is provided that does not match any files", func() {
				request.Params.Globs = []string{
					"*.tgz",
					"*.gif",
				}

				_, err := command.Run(sourcesDir, request)
				Ω(err).Should(HaveOccurred())
				Ω(err).Should(MatchError("could not find file that matches glob '*.gif'"))
			})
		})
	})
})


text:
Examples Overview
=================

.. customgalleryitem::
   :tooltip: Build a simple parameter server using Ray.
   :description: :doc:`/auto_examples/plot_parameter_server`

.. customgalleryitem::
   :tooltip: Asynchronous Advantage Actor Critic agent using Ray.
   :description: :doc:`/auto_examples/plot_example-a3c`

.. customgalleryitem::
   :tooltip: Simple parallel asynchronous hyperparameter evaluation.
   :description: :doc:`/auto_examples/plot_hyperparameter`

.. customgalleryitem::
   :tooltip: Parallelizing a policy gradient calculation on OpenAI Gym Pong.
   :description: :doc:`/auto_examples/plot_pong_example`

.. customgalleryitem::
   :tooltip: Walkthrough of parallelizing the L-BFGS algorithm.
   :description: :doc:`/auto_examples/plot_lbfgs`

.. customgalleryitem::
   :tooltip: Implementing a simple news reader using Ray.
   :description: :doc:`/auto_examples/plot_newsreader`

.. customgalleryitem::
   :tooltip: Using Ray to train ResNet across multiple GPUs.
   :description: :doc:`/auto_examples/plot_resnet`

.. customgalleryitem::
   :tooltip: Implement a simple streaming application using Ray's actors.
   :description: :doc:`/auto_examples/plot_streaming`

redpajama_set_name: RedPajamaGithub


text:
var gulp = require('gulp');
var collect = require('gulp-rev-collector');
var config = require('../../config').revCollect;

gulp.task('rev:collect', function () {
  return gulp
    .src(config.src)
    .pipe(collect())
    .pipe(gulp.dest(config.dest));
});


text:
<?php
//global $app;

define('DS', DIRECTORY_SEPARATOR);
define('BASE_PATH', dirname(__FILE__) . DS);

//define('BASE_PLUGIN_PATH', $app->getBasePath());
define('BASE_PLUGIN_PATH', dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . DS);
define('DIRECTORY_APP_NAME', 'app');
define('DIRECTORY_APP', BASE_PLUGIN_PATH . DIRECTORY_APP_NAME . DS);
define('DIRECTORY_APP_PLUGINS', BASE_PLUGIN_PATH . DIRECTORY_APP_NAME . DS . 'Plugins' . DS);
define('DIRECTORY_APP_CONFIG', DIRECTORY_APP . 'Config' . DS);
define('DIRECTORY_APP_VIEWS', DIRECTORY_APP . 'Views' . DS);
define('DIRECTORY_APP_STORAGE', BASE_PLUGIN_PATH . 'storage' . DS);
define('DIRECTORY_APP_CACHE', DIRECTORY_APP_STORAGE . 'cache' . DS);
define('DIRECTORY_APP_CACHE_VIEWS', DIRECTORY_APP_STORAGE . 'views');


text:
package org.mrgeo.geometry.splitter;

import java.util.Map;

public class GeometrySplitterFactory
{
  public static final String OUTPUT_NAME_PREFIX = ".outputName.";

  /**
   * Create a new geometry splitter instance based on the splitterName passed
   * in and the splitterProperties (for configuring it). If outputNames is
   * null, then the splitter output names are created (using generated UUIDs
   * if uuiOutputNames is true or some other unique name that each type of
   * splitter determines for itself). If outputNames is non-null, it is used
   * as the output names for the splitter.
   *
   * @param splitterName
   * @param splitterProperties
   * @param uuidOutputNames
   * @param outputNames
   * @return
   */
  public static GeometrySplitter createGeometrySplitter(final String splitterName,
      final Map<String, String> splitterProperties, final boolean uuidOutputNames,
      final String[] outputNames)
  {
    GeometrySplitter splitter = null;
    if (splitterName.equals("timeSpan"))
    {
      splitter = new TimeSpanGeometrySplitter();
    }

    if (splitter != null)
    {
      splitter.initialize(splitterProperties, uuidOutputNames, outputNames);
      return splitter;
    }
    else
    {
      throw new IllegalArgumentException("Invalid geometry splitter name: " + splitterName);
    }
  }
}


text:
_This bull-like creature seems to be made of interlocking metallic plates. Faint plumes of green smoke puff from its mouth._

**Gorgon CR 8**

**XP 4,800**

N Large [magical beast](creatureTypes#_magical-beast)

**Init** +4; **Senses** darkvision 60 ft., low-light vision, [scent](universalMonsterRules#_scent); [Perception](../skills/perception#_perception) +17

**Defense**

**AC** 20, touch 9, flat-footed 20 (+11 natural, –1 size)

**hp** 100 (8d10+56)

**Fort** +13, **Ref** +6, **Will** +7

**Offense**

**Speed** 30 ft.

**Melee** gore +14 (2d8+7), 2 hooves +9 (1d6+3)

**Space** 10 ft.; **Reach** 5 ft.

**Special Attacks** [breath weapon](universalMonsterRules#_breath-weapon) (60-foot cone, turn to stone, Fortitude DC 21 negates), [trample](universalMonsterRules#_trample) (2d8+10, DC 21)

**Statistics**

**Str** 24, **Dex** 10, **Con** 24, **Int** 2, **Wis** 16, **Cha** 9

**Base Atk** +8; **CMB** +16; **CMD** 26

**Feats** [Improved Initiative](../feats#_improved-initiative), [Iron Will](../feats#_iron-will), [Power Attack](../feats#_power-attack), [Skill Focus](../feats#_skill-focus) ( [Perception](../skills/perception#_perception))

**Skills** [Perception](../skills/perception#_perception) +17

**Ecology**

**Environment** temperate plains, rocky hills, and underground

**Organization** solitary, pair, pack (3–4), or herd (5–12)

**Treasure** none

**Special Abilities**

**Breath Weapon** A gorgon can use its breath weapon once every 1d4+1 rounds to create a 60-foot cone of green gas. Those caught in the area of the gas can attempt a DC 21 Fortitude save to resist the effects, but those who fail the save are immediately petrified. This petrification is temporary—each round, a petrified creature can attempt a new DC 21 Fortitude save to recover from the petrification as long as it is not caught within the area of effect of the gorgon's breath weapon a second time while petrified. A creature exposed to the gorgon's breath a second time while already petrified becomes permanently petrified, and can no longer attempt to make additional Fortitude saves to recover naturally. The save DC is Constitution-based.

Gorgons are magical, foul-tempered creatures—while they might appear to be constructs at first glance, beneath their artifical-looking armor plates they are made of flesh and bone. Like aggressive bulls, they challenge any unfamiliar creature they encounter, often trampling their opponent's corpse or shattering its stony remnants until the creature is unrecognizable. The females are just as dangerous as the males, and the two sexes appear identical. A typical gorgon stands 6 feet tall and 8 feet long. It weighs 4,000 pounds.

Gorgons derive nutrients from the consumption of minerals, particularly the stone of their petrified victims, and any statues they create are likely to be gnawed thoroughly. They cannot digest metal or gems, so their dung (which resembles bitter-smelling gray powder) often contains small, raw crystals and nuggets of ore. Their aggression toward all other creatures means that there are few to no predators or other prey animals in their grazing grounds. Each herd is led by a dominant bull; solitary gorgons are usually adolescent bulls driven out of their herd by the lead bull.

Their flesh is tough but beefy (once the armored hide is removed), and to those who acquire the taste, quite filling. Many stone giant tribes believe eating gorgon meat enhances their own natural armor. Powdered gorgon horn is worth 250 gp as an alternate material component for magic items using _ [bull's strength](../spells/bullSStrength#_bull-s-strength)_, _ [stoneskin](../spells/stoneskin#_stoneskin)_, _ [flesh to stone](../spells/fleshToStone#_flesh-to-stone)_, _ [statue](../spells/statue#_statue)_, and similar magic.


text:
step /^Click the (.+) button$/ do |button_name|
  # do stuff here
end

step /^Fill in the (.+) field with (.+)$/ do |field_name, value|
  # do stuff here
end

step /^I am logged out$/ do
  # do stuff here
end

step /^The (.+) button should be enabled$/ do |button_name|
  # do stuff here
end

step /^Visit the (.+) page$/ do |page|
  # do stuff here
end


text:
<!DOCTYPE html>

    <title>P8-8积分</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <link href="resources/css/jquery-ui-themes.css" type="text/css" rel="stylesheet"/>
    <link href="resources/css/axure_rp_page.css" type="text/css" rel="stylesheet"/>
    <link href="data/styles.css" type="text/css" rel="stylesheet"/>
    <link href="files/p8-8__/styles.css" type="text/css" rel="stylesheet"/>

积分

579

!

积分明细

积分兑换

流程说明

1.上方为用户获得的总积分,积分旁边的感叹号为积分的获取方式和规则

2.下方为积分明细和积分兑换两块

跳转说明

效果说明

备注


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

package com.company;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;

import java.io.*;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main
{
    // The authentication key (API Key).
    // Get your own by registering at https://app.pdf.co
    final static String API_KEY = "***********************************";

    // Source file name
    final static Path SourceFile = Paths.get(".\\sample.pdf");

    // Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
    final static String Pages = "";

    // PDF document password. Leave empty for unprotected documents.
    final static String Password = "";

    // Search string.
    final static String SearchString = "\\d{1,}\\.\\d\\d"; // Regular expression to find numbers like '100.00'
    // Note: do not use `+` char in regex, but use `{1,}` instead.
    // `+` char is valid for URL and will not be escaped, and it will become a space char on the server side.

    // Enable regular expressions (Regex)
    final static boolean RegexSearch = true;

    // (!) Make asynchronous job
    final static  boolean Async = true;

    public static void main(String[] args) throws IOException
    {
        // Create HTTP client instance
        OkHttpClient webClient = new OkHttpClient();

        // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE.
        // * If you already have a direct file URL, skip to the step 3.

        // Prepare URL for `Get Presigned URL` API call
        String query = String.format(
                "https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=%s",
                SourceFile.getFileName());

        // Prepare request
        Request request = new Request.Builder()
                .url(query)
                .addHeader("x-api-key", API_KEY) // (!) Set API Key
                .build();
        // Execute request
        Response response = webClient.newCall(request).execute();

        if (response.code() == 200)
        {
            // Parse JSON response
            JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();

            boolean error = json.get("error").getAsBoolean();
            if (!error)
            {
                // Get URL to use for the file upload
                String uploadUrl = json.get("presignedUrl").getAsString();
                // Get URL of uploaded file to use with later API calls
                String uploadedFileUrl = json.get("url").getAsString();

                // 2. UPLOAD THE FILE TO CLOUD.

                if (uploadFile(webClient, uploadUrl, SourceFile.toFile()))
                {
                    // 3. SEARCH TEXT FROM UPLOADED PDF FILE

                    searchTextFromPDF(webClient, uploadedFileUrl);
                }
            }
            else
            {
                // Display service reported error
                System.out.println(json.get("message").getAsString());
            }
        }
        else
        {
            // Display request error
            System.out.println(response.code() + " " + response.message());
        }
    }

    public static void searchTextFromPDF(OkHttpClient webClient, String uploadedFileUrl) throws IOException {

        // Prepare URL for PDF text search API call.
        // See documentation: https://apidocs.pdf.co
        String query = "https://api.pdf.co/v1/pdf/find";

        // Make correctly escaped (encoded) URL
        URL url = null;
        try
        {
            url = new URI(null, query, null).toURL();
        }
        catch (URISyntaxException e)
        {
            e.printStackTrace();
        }

        // Create JSON payload
		String jsonPayload = String.format("{\"password\": \"%s\", \"pages\": \"%s\", \"url\": \"%s\", \"searchString\": \"%s\", \"regexSearch\": \"%s\", \"async\": \"%s\"}",
                Password,
                Pages,
                uploadedFileUrl,
                SearchString,
                RegexSearch,
                Async);
        // Prepare request body
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);

        // Prepare request
        Request request = new Request.Builder()
            .url(url)
            .addHeader("x-api-key", API_KEY) // (!) Set API Key
            .addHeader("Content-Type", "application/json")
            .post(body)
            .build();

        // Execute request
        Response response = webClient.newCall(request).execute();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");

        if (response.code() == 200)
        {
            // Parse JSON response
            JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();

            boolean error = json.get("error").getAsBoolean();
            if (!error)
            {
                // Asynchronous job ID
                String jobId = json.get("jobId").getAsString();

                System.out.println("Job#" + jobId + ": has been created. - " + dtf.format(LocalDateTime.now()));

                // URL of generated json file that will available after the job completion
                String resultFileUrl = json.get("url").getAsString();

                // Check the job status in a loop.
                // If you don't want to pause the main thread you can rework the code
                // to use a separate thread for the status checking and completion.
                do {
                    String status = CheckJobStatus(webClient, jobId);  // Possible statuses: "working", "failed", "aborted", "success".

                    System.out.println("Job#" + jobId + ": " + status + " - " + dtf.format(LocalDateTime.now()));

                    if(status.compareToIgnoreCase("success") == 0){

                        // Build request for job url
                        request = new Request.Builder()
                                .url(resultFileUrl)
                                .build();

                        // Execute request
                        response =  webClient.newCall(request).execute();

                        // Parse JSON response
                        JsonArray jsonArray = new JsonParser().parse(response.body().string()).getAsJsonArray();

                        // Display found items in console
                        for (JsonElement element : jsonArray)
                        {
                            JsonObject item = (JsonObject) element;
                            System.out.println("Found text " + item.get("text") + " at coordinates " + item.get("left") + ", "+ item.get("top"));
                        }

                        break;
                    }
                    else if (status.compareToIgnoreCase("working") == 0){
                        // Pause for a few seconds
                        try{
                            Thread.sleep(3000);
                        }
                        catch (InterruptedException ex){
                            Thread.currentThread().interrupt(); // restore interrupted status
                        }
                    }
                    else{
                        System.out.println(status);
                        break;
                    }
                }while (true);
            }
            else
            {
                // Display service reported error
                System.out.println(json.get("message").getAsString());
            }
        }
        else
        {
            // Display request error
            System.out.println(response.code() + " " + response.message());
        }
    }

    public static boolean uploadFile(OkHttpClient webClient, String url, File sourceFile) throws IOException
    {
        // Prepare request body
        RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), sourceFile);

        // Prepare request
        Request request = new Request.Builder()
                .url(url)
                .addHeader("x-api-key", API_KEY) // (!) Set API Key
                .addHeader("content-type", "application/octet-stream")
                .put(body)
                .build();

        // Execute request
        Response response = webClient.newCall(request).execute();

        return (response.code() == 200);
    }

    // Check Job Status
    private  static String CheckJobStatus(OkHttpClient webClient, String jobId) throws IOException {

        String url = "https://api.pdf.co/v1/job/check?jobid=" + jobId;

        // Prepare request
        Request request = new Request.Builder()
                .url(url)
                .addHeader("x-api-key", API_KEY) // (!) Set API Key
                .build();

        // Execute request
        Response response = webClient.newCall(request).execute();

        if (response.code() == 200)
        {
            // Parse JSON response
            JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();

            return json.get("status").getAsString();
        }
        else
        {
            // Display request error
            System.out.println(response.code() + " " + response.message());
        }

        return "Failed";
    }

}


text:
using Nito.AsyncEx.Synchronous;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nito.AsyncEx
{
    /// <summary>
    /// A base type for custom tasks. This task will propagate the completion of its source task.
    /// </summary>
    public class TaskBase : Task
    {
        /// <summary>
        /// Constructs the base task type. This task will propagate the completion of its source task.
        /// </summary>
        /// <param name="source">The source task used to complete this task.</param>
        protected TaskBase(Task source)
            : base(s => ((Task)s).WaitAndUnwrapException(), source)
        {
            source.ContinueWith(_ => RunSynchronously(), TaskContinuationOptions.ExecuteSynchronously);
        }
    }

    /// <summary>
    /// A base type for custom tasks. This task will propagate the completion of its source task.
    /// </summary>
    /// <typeparam name="TResult">The type of the task result.</typeparam>
    public class TaskBase<TResult> : Task<TResult>
    {
        /// <summary>
        /// Constructs the base task type. This task will propagate the completion of its source task.
        /// </summary>
        /// <param name="source">The source task used to complete this task.</param>
        protected TaskBase(Task<TResult> source)
            : base(s => ((Task<TResult>)s).WaitAndUnwrapException(), source)
        {
            source.ContinueWith(_ => RunSynchronously(), TaskContinuationOptions.ExecuteSynchronously);
        }
    }
}


text:
package uk.ac.gla.terrier.probos;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import jnr.posix.POSIX;
import jnr.posix.POSIXFactory;

import org.apache.commons.io.IOUtils;

public class Utils {

	public static String padRight(String s, int n) {
		if (s.length() > n)
			return s.substring(0, n-1);
		return String.format("%1$-" + n + "s", s);
	}

	public static String padLeft(String s, int n) {
		if (s.length() > n)
			return s.substring(0, n-1);
		return String.format("%1$" + n + "s", s);
	}

	public static String getHostname() throws IOException {
        String OS = System.getProperty("os.name").toLowerCase();
        //System.err.println(OS);
        String hostname = null;
        if (OS.indexOf("win") >= 0) {
        	hostname = System.getenv("COMPUTERNAME");
        	if (hostname == null)
        		hostname = execReadToString("hostname");
        } else {
            if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.equals("mac os x")) {
            	hostname = System.getenv("HOSTNAME");
            	if (hostname == null)
            		hostname = execReadToString("hostname");
            	if (hostname == null)
            		hostname = execReadToString("cat /etc/hostname");
            }
        }

        assert hostname != null;

        return hostname;
    }

	static final POSIX posix = POSIXFactory.getPOSIX();

	public static String getGroup()
	{
		String rtr ;
		try {
			rtr = posix.getgrgid(posix.getegid()).getName();
		} catch (IllegalStateException ise) {
			//JNR-posix is playing silly buggers.
			try{
				rtr = execReadToString("/usr/bin/id -g -n");
			} catch (IOException ioe) {
				throw new IllegalStateException("Could not get group name from /usr/bin/id or from POSIX", ioe);
			}
		}
		return rtr;
	}

    public static String execReadToString(String execCommand) throws IOException {
        Process proc = Runtime.getRuntime().exec(execCommand);
        try (InputStream stream = proc.getInputStream()) {
            try (Scanner s = new Scanner(stream).useDelimiter("\\A")) {
                return s.hasNext() ? s.next().trim() : "";
            }
        }
    }

    public static byte[] slurpBytes (final File file) throws IOException {
    	BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    	byte[] rtr = IOUtils.toByteArray(bis);
    	bis.close();
    	return rtr;
	}

	public static String[] slurpString (final File file) throws IOException {
	    List<String> l = new ArrayList<String>();
	    BufferedReader br = null;
	    try {
	        br = new BufferedReader(new FileReader(file));
	        String line = null;
	        while((line = br.readLine()) != null)
	        {
	        	l.add(line);
	        }
	    }
	    finally {
	    	if (br != null)
	    		br.close();
	    }

	    return l.toArray(new String[l.size()]);
	}

	/* http://stackoverflow.com/questions/6118922/convert-seconds-value-to-hours-minutes-seconds-android-java */
	public static String makeTime(long seconds) {

	    long hours = seconds / 3600;
	    long minutes = (seconds % 3600) / 60;
	    seconds = seconds % 60;

	    return twoDigitString(hours) + ":" + twoDigitString(minutes) + ":" + twoDigitString(seconds);
	}

	public static String twoDigitString(long number) {
	    if (number == 0) {
	        return "00";
	    }
	    if (number / 10 == 0) {
	        return "0" + number;
	    }
	    return String.valueOf(number);
	}

	public static long parseTime(String timeExpression)
	{
		/** format: [[hours:]minutes:]seconds[.milliseconds] */
		String[] parts = timeExpression.split(":");
		long duration = 0;
		if (parts.length == 1)
		{
			duration = Integer.parseInt(parts[0]);
		}
		else if (parts.length == 2)
		{
			duration = Integer.parseInt(parts[1])
				+ 60l * Integer.parseInt(parts[0]);
		}
		else if (parts.length == 3)
		{
			duration = Integer.parseInt(parts[2])
				+ 60l * Integer.parseInt(parts[1])
				+ 3600l * Integer.parseInt(parts[0]);
		}
		else
		{
			throw new IllegalArgumentException("Invalid time format:" + timeExpression);
		}
		return duration;
	}

	public static String readStringOrNull(DataInput in) throws IOException {
		if (! in.readBoolean())
			return null;
		return in.readUTF();
	}

	public static void writeStringOrNull(DataOutput out, String s) throws IOException
	{
		if (s == null)
		{
			out.writeBoolean(false);
		}
		else
		{
			out.writeBoolean(true);
			out.writeUTF(s);
		}
	}
}


text:
@implementation YFFunction

+(void)saveValue:(BOOL)value forKey:(NSString *)key{

    [[NSUserDefaults standardUserDefaults] setBool:value forKey:key];

    [[NSUserDefaults standardUserDefaults]synchronize];

}

@end


text:
+ app.registerRoute
+ app.registerController


text:
/* Author: Wolfgang Bangerth, University of Heidelberg, 2001 */

/*    $Id: step-11.cc 27657 2012-11-21 13:19:08Z bangerth $       */
/*                                                                */
/*    Copyright (C) 2001-2004, 2006, 2009, 2011-2012 by the deal.II authors */
/*                                                                */
/*    This file is subject to QPL and may not be  distributed     */
/*    without copyright and license information. Please refer     */
/*    to the file deal.II/doc/license.html for the  text  and     */
/*    further information on this license.                        */

// As usual, the program starts with a rather long list of include files which
// you are probably already used to by now:
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/function.h>
#include <deal.II/base/logstream.h>
#include <deal.II/base/table_handler.h>
#include <deal.II/lac/vector.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/constraint_matrix.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/tria_boundary_lib.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/fe/mapping_q.h>
#include <deal.II/numerics/vector_tools.h>
#include <deal.II/numerics/matrix_tools.h>

// Just this one is new: it declares a class
// CompressedSparsityPattern, which we will use and explain
// further down below.
#include <deal.II/lac/compressed_sparsity_pattern.h>

// We will make use of the std::find algorithm of the C++ standard library, so
// we have to include the following file for its declaration:
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cmath>

// The last step is as in all previous programs:
namespace Step11
{
  using namespace dealii;

  // Then we declare a class which represents the solution of a Laplace
  // problem. As this example program is based on step-5, the class looks
  // rather the same, with the sole structural difference that the functions
  // assemble_system now calls solve itself, and is
  // thus called assemble_and_solve, and that the output function
  // was dropped since the solution function is so boring that it is not worth
  // being viewed.
  //
  // The only other noteworthy change is that the constructor takes a value
  // representing the polynomial degree of the mapping to be used later on,
  // and that it has another member variable representing exactly this
  // mapping. In general, this variable will occur in real applications at the
  // same places where the finite element is declared or used.
  template <int dim>
  class LaplaceProblem
  {
  public:
    LaplaceProblem (const unsigned int mapping_degree);
    void run ();

  private:
    void setup_system ();
    void assemble_and_solve ();
    void solve ();

    Triangulation<dim>   triangulation;
    FE_Q<dim>            fe;
    DoFHandler<dim>      dof_handler;
    MappingQ<dim>        mapping;

    SparsityPattern      sparsity_pattern;
    SparseMatrix<double> system_matrix;
    ConstraintMatrix     mean_value_constraints;

    Vector<double>       solution;
    Vector<double>       system_rhs;

    TableHandler         output_table;
  };

  // Construct such an object, by initializing the variables. Here, we use
  // linear finite elements (the argument to the fe variable
  // denotes the polynomial degree), and mappings of given order. Print to
  // screen what we are about to do.
  template <int dim>
  LaplaceProblem<dim>::LaplaceProblem (const unsigned int mapping_degree) :
    fe (1),
    dof_handler (triangulation),
    mapping (mapping_degree)
  {
    std::cout << "Using mapping with degree " << mapping_degree << ":"
              << std::endl
              << "============================"
              << std::endl;
  }

  // The first task is to set up the variables for this problem. This includes
  // generating a valid DoFHandler object, as well as the
  // sparsity patterns for the matrix, and the object representing the
  // constraints that the mean value of the degrees of freedom on the boundary
  // be zero.
  template <int dim>
  void LaplaceProblem<dim>::setup_system ()
  {
    // The first task is trivial: generate an enumeration of the degrees of
    // freedom, and initialize solution and right hand side vector to their
    // correct sizes:
    dof_handler.distribute_dofs (fe);
    solution.reinit (dof_handler.n_dofs());
    system_rhs.reinit (dof_handler.n_dofs());

    // Next task is to construct the object representing the constraint that
    // the mean value of the degrees of freedom on the boundary shall be
    // zero. For this, we first want a list of those nodes which are actually
    // at the boundary. The DoFTools class has a function that
    // returns an array of boolean values where true indicates
    // that the node is at the boundary. The second argument denotes a mask
    // selecting which components of vector valued finite elements we want to
    // be considered. This sort of information is encoded using the
    // ComponentMask class (see also @ref GlossComponentMask). Since we have a
    // scalar finite element anyway, this mask in reality should have only one
    // entry with a true value. However, the ComponentMask class
    // has semantics that allow it to represents a mask of indefinite size
    // whose every element equals true when one just default
    // constructs such an object, so this is what we'll do here.
    std::vector<bool> boundary_dofs (dof_handler.n_dofs(), false);
    DoFTools::extract_boundary_dofs (dof_handler,
                                     ComponentMask(),
                                     boundary_dofs);

    // Now first for the generation of the constraints: as mentioned in the
    // introduction, we constrain one of the nodes on the boundary by the
    // values of all other DoFs on the boundary. So, let us first pick out the
    // first boundary node from this list. We do that by searching for the
    // first true value in the array (note that
    // std::find returns an iterator to this element), and
    // computing its distance to the overall first element in the array to get
    // its index:
    const unsigned int first_boundary_dof
      = std::distance (boundary_dofs.begin(),
                       std::find (boundary_dofs.begin(),
                                  boundary_dofs.end(),
                                  true));

    // Then generate a constraints object with just this one constraint. First
    // clear all previous content (which might reside there from the previous
    // computation on a once coarser grid), then add this one line
    // constraining the first_boundary_dof to the sum of other
    // boundary DoFs each with weight -1. Finally, close the constraints
    // object, i.e. do some internal bookkeeping on it for faster processing
    // of what is to come later:
    mean_value_constraints.clear ();
    mean_value_constraints.add_line (first_boundary_dof);
    for (unsigned int i=first_boundary_dof+1; i<dof_handler.n_dofs(); ++i)
      if (boundary_dofs[i] == true)
        mean_value_constraints.add_entry (first_boundary_dof,
                                          i, -1);
    mean_value_constraints.close ();

    // Next task is to generate a sparsity pattern. This is indeed a tricky
    // task here. Usually, we just call
    // DoFTools::make_sparsity_pattern and condense the result
    // using the hanging node constraints. We have no hanging node constraints
    // here (since we only refine globally in this example), but we have this
    // global constraint on the boundary. This poses one severe problem in
    // this context: the SparsityPattern class wants us to state
    // beforehand the maximal number of entries per row, either for all rows
    // or for each row separately. There are functions in the library which
    // can tell you this number in case you just have hanging node constraints
    // (namely DoFHandler::max_coupling_between_dofs), but how is
    // this for the present case? The difficulty arises because the
    // elimination of the constrained degree of freedom requires a number of
    // additional entries in the matrix at places that are not so simple to
    // determine. We would therefore have a problem had we to give a maximal
    // number of entries per row here.
    //
    // Since this can be so difficult that no reasonable answer can be given
    // that allows allocation of only a reasonable amount of memory, there is
    // a class CompressedSparsityPattern, that can help us out
    // here. It does not require that we know in advance how many entries rows
    // could have, but allows just about any length. It is thus significantly
    // more flexible in case you do not have good estimates of row lengths,
    // however at the price that building up such a pattern is also
    // significantly more expensive than building up a pattern for which you
    // had information in advance. Nevertheless, as we have no other choice
    // here, we'll just build such an object by initializing it with the
    // dimensions of the matrix and calling another function
    // DoFTools::make_sparsity_pattern to get the sparsity
    // pattern due to the differential operator, then condense it with the
    // constraints object which adds those positions in the sparsity pattern
    // that are required for the elimination of the constraint.
    CompressedSparsityPattern csp (dof_handler.n_dofs(),
                                   dof_handler.n_dofs());
    DoFTools::make_sparsity_pattern (dof_handler, csp);
    mean_value_constraints.condense (csp);

    // Finally, once we have the full pattern, we can initialize an object of
    // type SparsityPattern from it and in turn initialize the
    // matrix with it. Note that this is actually necessary, since the
    // CompressedSparsityPattern is so inefficient compared to
    // the SparsityPattern class due to the more flexible data
    // structures it has to use, that we can impossibly base the sparse matrix
    // class on it, but rather need an object of type
    // SparsityPattern, which we generate by copying from the
    // intermediate object.
    //
    // As a further sidenote, you will notice that we do not explicitly have
    // to compress the sparsity pattern here. This, of course, is
    // due to the fact that the copy_from function generates a
    // compressed object right from the start, to which you cannot add new
    // entries anymore. The compress call is therefore implicit
    // in the copy_from call.
    sparsity_pattern.copy_from (csp);
    system_matrix.reinit (sparsity_pattern);
  }

  // The next function then assembles the linear system of equations, solves
  // it, and evaluates the solution. This then makes three actions, and we
  // will put them into eight true statements (excluding declaration of
  // variables, and handling of temporary vectors). Thus, this function is
  // something for the very lazy. Nevertheless, the functions called are
  // rather powerful, and through them this function uses a good deal of the
  // whole library. But let's look at each of the steps.
  template <int dim>
  void LaplaceProblem<dim>::assemble_and_solve ()
  {

    // First, we have to assemble the matrix and the right hand side. In all
    // previous examples, we have investigated various ways how to do this
    // manually. However, since the Laplace matrix and simple right hand sides
    // appear so frequently in applications, the library provides functions
    // for actually doing this for you, i.e. they perform the loop over all
    // cells, setting up the local matrices and vectors, and putting them
    // together for the end result.
    //
    // The following are the two most commonly used ones: creation of the
    // Laplace matrix and creation of a right hand side vector from body or
    // boundary forces. They take the mapping object, the
    // DoFHandler object representing the degrees of freedom and
    // the finite element in use, a quadrature formula to be used, and the
    // output object. The function that creates a right hand side vector also
    // has to take a function object describing the (continuous) right hand
    // side function.
    //
    // Let us look at the way the matrix and body forces are integrated:
    const unsigned int gauss_degree
      = std::max (static_cast<unsigned int>(std::ceil(1.*(mapping.get_degree()+1)/2)),
                  2U);
    MatrixTools::create_laplace_matrix (mapping, dof_handler,
                                        QGauss<dim>(gauss_degree),
                                        system_matrix);
    VectorTools::create_right_hand_side (mapping, dof_handler,
                                         QGauss<dim>(gauss_degree),
                                         ConstantFunction<dim>(-2),
                                         system_rhs);
    // That's quite simple, right?
    //
    // Two remarks are in order, though: First, these functions are used in a
    // lot of contexts. Maybe you want to create a Laplace or mass matrix for
    // a vector values finite element; or you want to use the default Q1
    // mapping; or you want to assembled the matrix with a coefficient in the
    // Laplace operator. For this reason, there are quite a large number of
    // variants of these functions in the MatrixCreator and
    // MatrixTools classes. Whenever you need a slightly
    // different version of these functions than the ones called above, it is
    // certainly worthwhile to take a look at the documentation and to check
    // whether something fits your needs.
    //
    // The second remark concerns the quadrature formula we use: we want to
    // integrate over bilinear shape functions, so we know that we have to use
    // at least a Gauss2 quadrature formula. On the other hand, we want to
    // have the quadrature rule to have at least the order of the boundary
    // approximation. Since the order of Gauss-r is 2r, and the order of the
    // boundary approximation using polynomials of degree p is p+1, we know
    // that 2r@>=p+1. Since r has to be an integer and (as mentioned above)
    // has to be at least 2, this makes up for the formula above computing
    // gauss_degree.
    //
    // Since the generation of the body force contributions to the right hand
    // side vector was so simple, we do that all over again for the boundary
    // forces as well: allocate a vector of the right size and call the right
    // function. The boundary function has constant values, so we can generate
    // an object from the library on the fly, and we use the same quadrature
    // formula as above, but this time of lower dimension since we integrate
    // over faces now instead of cells:
    Vector<double> tmp (system_rhs.size());
    VectorTools::create_boundary_right_hand_side (mapping, dof_handler,
                                                  QGauss<dim-1>(gauss_degree),
                                                  ConstantFunction<dim>(1),
                                                  tmp);
    // Then add the contributions from the boundary to those from the interior
    // of the domain:
    system_rhs += tmp;
    // For assembling the right hand side, we had to use two different vector
    // objects, and later add them together. The reason we had to do so is
    // that the VectorTools::create_right_hand_side and
    // VectorTools::create_boundary_right_hand_side functions
    // first clear the output vector, rather than adding up their results to
    // previous contents. This can reasonably be called a design flaw in the
    // library made in its infancy, but unfortunately things are as they are
    // for some time now and it is difficult to change such things that
    // silently break existing code, so we have to live with that.

    // Now, the linear system is set up, so we can eliminate the one degree of
    // freedom which we constrained to the other DoFs on the boundary for the
    // mean value constraint from matrix and right hand side vector, and solve
    // the system. After that, distribute the constraints again, which in this
    // case means setting the constrained degree of freedom to its proper
    // value
    mean_value_constraints.condense (system_matrix);
    mean_value_constraints.condense (system_rhs);

    solve ();
    mean_value_constraints.distribute (solution);

    // Finally, evaluate what we got as solution. As stated in the
    // introduction, we are interested in the H1 semi-norm of the
    // solution. Here, as well, we have a function in the library that does
    // this, although in a slightly non-obvious way: the
    // VectorTools::integrate_difference function integrates the
    // norm of the difference between a finite element function and a
    // continuous function. If we therefore want the norm of a finite element
    // field, we just put the continuous function to zero. Note that this
    // function, just as so many other ones in the library as well, has at
    // least two versions, one which takes a mapping as argument (which we
    // make us of here), and the one which we have used in previous examples
    // which implicitly uses MappingQ1.  Also note that we take a
    // quadrature formula of one degree higher, in order to avoid
    // superconvergence effects where the solution happens to be especially
    // close to the exact solution at certain points (we don't know whether
    // this might be the case here, but there are cases known of this, and we
    // just want to make sure):
    Vector<float> norm_per_cell (triangulation.n_active_cells());
    VectorTools::integrate_difference (mapping, dof_handler,
                                       solution,
                                       ZeroFunction<dim>(),
                                       norm_per_cell,
                                       QGauss<dim>(gauss_degree+1),
                                       VectorTools::H1_seminorm);
    // Then, the function just called returns its results as a vector of
    // values each of which denotes the norm on one cell. To get the global
    // norm, a simple computation shows that we have to take the l2 norm of
    // the vector:
    const double norm = norm_per_cell.l2_norm();

    // Last task -- generate output:
    output_table.add_value ("cells", triangulation.n_active_cells());
    output_table.add_value ("|u|_1", norm);
    output_table.add_value ("error", std::fabs(norm-std::sqrt(3.14159265358/2)));
  }

  // The following function solving the linear system of equations is copied
  // from step-5 and is explained there in some detail:
  template <int dim>
  void LaplaceProblem<dim>::solve ()
  {
    SolverControl           solver_control (1000, 1e-12);
    SolverCG<>              cg (solver_control);

    PreconditionSSOR<> preconditioner;
    preconditioner.initialize(system_matrix, 1.2);

    cg.solve (system_matrix, solution, system_rhs,
              preconditioner);
  }

  // Finally the main function controlling the different steps to be
  // performed. Its content is rather straightforward, generating a
  // triangulation of a circle, associating a boundary to it, and then doing
  // several cycles on subsequently finer grids. Note again that we have put
  // mesh refinement into the loop header; this may be something for a test
  // program, but for real applications you should consider that this implies
  // that the mesh is refined after the loop is executed the last time since
  // the increment clause (the last part of the three-parted loop header) is
  // executed before the comparison part (the second one), which may be rather
  // costly if the mesh is already quite refined. In that case, you should
  // arrange code such that the mesh is not further refined after the last
  // loop run (or you should do it at the beginning of each run except for the
  // first one).
  template <int dim>
  void LaplaceProblem<dim>::run ()
  {
    GridGenerator::hyper_ball (triangulation);
    static const HyperBallBoundary<dim> boundary;
    triangulation.set_boundary (0, boundary);

    for (unsigned int cycle=0; cycle<6; ++cycle, triangulation.refine_global(1))
      {
        setup_system ();
        assemble_and_solve ();
      };

    // After all the data is generated, write a table of results to the
    // screen:
    output_table.set_precision("|u|_1", 6);
    output_table.set_precision("error", 6);
    output_table.write_text (std::cout);
    std::cout << std::endl;
  }
}

// Finally the main function. It's structure is the same as that used in
// several of the previous examples, so probably needs no more explanation.
int main ()
{
  try
    {
      dealii::deallog.depth_console (0);
      std::cout.precision(5);

      // This is the main loop, doing the computations with mappings of linear
      // through cubic mappings. Note that since we need the object of type
      // LaplaceProblem@<2@> only once, we do not even name it,
      // but create an unnamed such object and call the run
      // function of it, subsequent to which it is immediately destroyed
      // again.
      for (unsigned int mapping_degree=1; mapping_degree<=3; ++mapping_degree)
        Step11::LaplaceProblem<2>(mapping_degree).run ();
    }
  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Exception on processing: " << std::endl
                << exc.what() << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;
      return 1;
    }
  catch (...)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Unknown exception!" << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;
      return 1;
    };

  return 0;
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <link href="assets/css/bootstrap.min.css" rel="stylesheet">
        <link href="assets/css/bootstrap-theme.min.css" rel="stylesheet">
        <link href="assets/css/bootstrap-theme.min.css.map" rel="stylesheet">
        <link href="assets/css/bootstrap.min.css.map" rel="stylesheet">
        <link href="assets/css/custom.css" rel="stylesheet">
        <title>Soy Donante</title>

Ayuda inicio de sesión

                Seleccione

                  <select name="day" size="1" class="form-control">
                    <option selected>Opciones</option>
                    <option>Recordar contraseña</option>
                    <option>Recordar usuario</option>
                    <option>Recordar usuario y contraseña</option>
                  </select>

                  <button class="btn btn-sm btn-info" type="button" id="volver">Volver</button>
                  <button class="btn btn-sm btn-primary pull-right" type="button" id="registro">Enviar recordatorio</button>

Se ha enviado un correo electrónico a la cuenta registrada con la información solicitada.


text:
<?php
namespace Concrete\Core\Console\Command;

use Concrete\Core\Package\Routine\AttachModeCompatibleRoutineInterface;
use Doctrine\DBAL\Connection;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Exception;
use Database;
use Config;
use Core;
use StartingPointPackage;

class InstallCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('c5:install')
            ->setDescription('Install concrete5')
            ->addOption('db-server', null, InputOption::VALUE_REQUIRED, 'Location of database server')
            ->addOption('db-username', null, InputOption::VALUE_REQUIRED, 'Database username')
            ->addOption('db-password', null, InputOption::VALUE_REQUIRED, 'Database password')
            ->addOption('db-database', null, InputOption::VALUE_REQUIRED, 'Database name')
            ->addOption('site', null, InputOption::VALUE_REQUIRED, 'Name of the site', 'concrete5 Site')
            ->addOption('starting-point', null, InputOption::VALUE_REQUIRED, 'Starting point to use', 'elemental_blank')
            ->addOption('admin-email', null, InputOption::VALUE_REQUIRED, 'Email of the admin user of the install', 'admin@example.com')
            ->addOption('admin-password', null, InputOption::VALUE_REQUIRED, 'Password of the admin user of the install')
            ->addOption('demo-username', null, InputOption::VALUE_REQUIRED, 'Additional user username', 'demo')
            ->addOption('demo-password', null, InputOption::VALUE_REQUIRED, 'Additional user password')
            ->addOption('demo-email', null, InputOption::VALUE_REQUIRED, 'Additional user email', 'demo@example.com')
            ->addOption('default-locale', null, InputOption::VALUE_REQUIRED, 'The default site locale (eg en_US)')
            ->addOption('config', null, InputOption::VALUE_REQUIRED, 'Use configuration file for installation')
            ->addOption('attach', null, InputOption::VALUE_NONE, 'Attach if database contains an existing concrete5 instance')
            ->addOption('force-attach', null, InputOption::VALUE_NONE, 'Always attach')
            ->setHelp(<<<EOT
Returns codes:
  0 operation completed successfully
  1 errors occurred
EOT
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $rc = 0;
        try {
            $options = $input->getOptions();
            if (isset($options['config'])) {
                if (!is_file($options['config'])) {
                    throw new Exception('Unable to find the configuration file '.$options['config']);
                }
                $configOptions = include $options['config'];
                if (!is_array($configOptions)) {
                    throw new Exception('The configuration file did not returned an array.');
                }
                foreach ($configOptions as $k => $v) {
                    if (!$input->hasParameterOption("--$k")) {
                        $options[$k] = $v;
                    }
                }
            }
            if (file_exists(DIR_CONFIG_SITE.'/database.php')) {
                throw new Exception('concrete5 is already installed.');
            }
            if (isset($options['default-locale'])) {
                if ($options['default-locale'] === 'en_US') {
                    $options['default-locale'] = null;
                } else {
                    $availableLocales = array_filter(
                        scandir(DIR_BASE . '/application/languages'),
                        function ($item) {
                            if (strpos($item, '.') === 0) {
                                return false;
                            }
                            $fullPath = DIR_BASE . '/application/languages/' . $item;
                            if (!is_dir($fullPath)) {
                                return false;
                            }
                            if (!is_file($fullPath . '/LC_MESSAGES/messages.mo')) {
                                return false;
                            }

                            return true;
                        }
                    );
                    if (!in_array($options['default-locale'], $availableLocales, true)) {
                        throw new Exception("'{$options['default-locale']}' is not a valid locale identifier.\nAvailable locales: " . ($availableLocales ? implode(', ', $availableLocales) : 'no locale found'));
                    }
                }
            }
            Database::extend('install', function () use ($options) {
                return Database::getFactory()->createConnection(array(
                    'host' => $options['db-server'],
                    'user' => $options['db-username'],
                    'password' => $options['db-password'],
                    'database' => $options['db-database'],
                ));
            });
            Database::setDefaultConnection('install');
            Config::set('database.connections.install', array());

            $cnt = new \Concrete\Controller\Install();

            $force_attach = $input->getOption('force-attach');
            $auto_attach = $force_attach || $input->getOption('attach');
            $cnt->setAutoAttach($auto_attach);

            $cnt->on_start();
            $fileWriteErrors = clone $cnt->fileWriteErrors;
            $e = Core::make('helper/validation/error');
            /* @var $e \Concrete\Core\Error\Error */
            if (!$cnt->get('imageTest')) {
                $e->add('GD library must be enabled to install concrete5.');
            }
            if (!$cnt->get('mysqlTest')) {
                $e->add($cnt->getDBErrorMsg());
            }
            if (!$cnt->get('xmlTest')) {
                $e->add('SimpleXML and DOM must be enabled to install concrete5.');
            }
            if (!$cnt->get('phpVtest')) {
                $e->add('concrete5 requires PHP '.$cnt->getMinimumPhpVersion().' or greater.');
            }
            if (is_object($fileWriteErrors)) {
                $e->add($fileWriteErrors);
            }
            $spl = StartingPointPackage::getClass($options['starting-point']);
            if ($spl === null) {
                $e->add('Invalid starting-point: '.$options['starting-point']);
            }
            if (!$e->has()) {
                $_POST['DB_SERVER'] = $options['db-server'];
                $_POST['DB_USERNAME'] = $options['db-username'];
                $_POST['DB_PASSWORD'] = $options['db-password'];
                $_POST['DB_DATABASE'] = $options['db-database'];
                $_POST['SITE'] = $options['site'];
                $_POST['SAMPLE_CONTENT'] = $options['starting-point'];
                $_POST['uEmail'] = $options['admin-email'];
                $_POST['uPasswordConfirm'] = $_POST['uPassword'] = $options['admin-password'];
                $e = $cnt->configure();
            }
            if ($e->has()) {
                throw new Exception(implode("\n", $e->getList()));
            }
            try {
                $attach_mode = $force_attach;

                if (!$force_attach && $cnt->isAutoAttachEnabled()) {
                    /** @var Connection $db */
                    $db = \Core::make('database')->connection();

                    if ($db->query('show tables')->rowCount()) {
                        $attach_mode = true;
                    }
                }

                require DIR_CONFIG_SITE . '/site_install.php';
                require DIR_CONFIG_SITE . '/site_install_user.php';
                $routines = $spl->getInstallRoutines();
                foreach ($routines as $r) {
                    // If we're
                    if ($attach_mode && !$r instanceof AttachModeCompatibleRoutineInterface) {
                        $output->writeln("{$r->getProgress()}%: {$r->getText()} (Skipped)");
                        continue;
                    }

                    $output->writeln($r->getProgress() . '%: ' . $r->getText());
                    call_user_func(array($spl, $r->getMethod()));
                }
            } catch (Exception $ex) {
                $cnt->reset();
                throw $ex;
            }
            if (isset($options['default-locale'])) {
                Config::save('concrete.locale', $options['default-locale']);
            }
            if (
                isset($options['demo-username']) && isset($options['demo-password']) && isset($options['demo-email'])
                &&
                is_string($options['demo-username']) && is_string($options['demo-password']) && is_string($options['demo-email'])
                &&
                ($options['demo-username'] !== '') && ($options['demo-password'] !== '') && ($options['demo-email'] !== '')
            ) {
                $output->write('Adding demo user... ');
                \UserInfo::add(array(
                    'uName' => $options['demo-username'],
                    'uEmail' => $options['demo-email'],
                    'uPassword' => $options['demo-password'],
                ))->getUserObject()->enterGroup(
                    \Group::getByID(ADMIN_GROUP_ID)
                );
                $output->writeln('done.');
            }
            $output->writeln('<info>Installation Complete!</info>');
        } catch (Exception $x) {
            $output->writeln('<error>'.$x->getMessage().'</error>');
            $rc = 1;
        }

        return $rc;
    }
}


text:
exports.models = {
  "User":{
    "id":"User",
    "required": ["username","password"],
    "properties":{
      "username":{
        "type":"string",
        "description": "A user of the application"
      },
      "password":{
        "type":"string",
        "description":"Password for the user"
      }
    }
  }
}


text:
using System;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using DGGF.Objects;
using DGGF.Drawing;
using System.Drawing;

namespace ProjectBreakout.Objects.Beaters
{
	/// <summary>
	/// Summary description for BeaterSimple.
	/// </summary>
	public class BeaterSimple : Beater
	{
		#region Members of Data
		private static DGGFTexture globalTexture = null;
		#endregion

		public static void LoadResources(Device videoDevice)
		{
			BeaterSimple.globalTexture = new DGGFTexture(TextureLoader.FromFile(videoDevice, "Images/Beaters/beaterSimple.png"));
		}

		#region Constructors
		public BeaterSimple(Device videoDevice, Microsoft.DirectX.DirectSound.Device soundDevice, Sprite sprite, Rectangle area) : base(videoDevice, soundDevice, sprite, area, BeaterSimple.globalTexture, 3, 1)
		{
			this.AnimationDelay = 75;
			this.CycleType = AnimatedObjectCycleType.Circular;
		}
		#endregion
	}
}


text:
/* define supported features */
;(function ($, _, undefined)
{
	'use strict';

	_.support = {
		transition: {},
		animation: {}
	};

	if (_.prefix.lowercase === 'webkit')
	{
		_.support.transition.end = 'webkitTransitionEnd';
		_.support.animation.end = 'webkitAnimationEnd';
	}
	else
	{
		_.support.transition.end = 'transitionend';
		_.support.animation.end = 'animationend';
	}
})(window.jQuery, window._);


text:
import { Point } from "fcore/dist/index";
import { IDisplayObjectContainerWrapper } from "./IDisplayObjectContainerWrapper";
export interface ISpriteWrapper extends IDisplayObjectContainerWrapper {
    isSpriteWrapper: boolean;
    texture: any;
    anchor: Point;
}


text:
**Note** - The API of this client is still considered unstable as the Sidecar Platform API continues to be worked on.  If there is an unexpected error, please file an issue with as many details as you can reasonably provide.

---------------------------------------

The Sidecar Java client wraps the full Sidecar REST API and handles event ingestion, authenticaion and queries.

What is Sidecar?

Sidecar is a data platform purpose built to consume and analyze sensor-based data streams so that the owners and developers of IoT hardware do not need to be concerned with the large infrastructure and development overhead associated with the long term persistence and meaningful computation of that data.  Once device data is stored in Sidecar, the platform is capable of:

- Returning the raw source data
- Generating Insights
- Propagating notifications that are executed based on rules defined by device owners
- Aggregation of inbound data sources
- Allowing developers to write interactive ad hoc queries whose results can be used in reporting web and mobile applications

For more information visit the Sidecar website.


text:
package com.googlecode._4s_web.client.ui;

import java.util.Comparator;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.googlecode._4s_web.client.entity.EventEntity;
import com.googlecode._4s_web.client.entity.LocalCache;
import com.googlecode._4s_web.shared.Interval;

public class NetworkComplexity extends Composite {

	private static NetworkComplexityUiBinder uiBinder = GWT
			.create(NetworkComplexityUiBinder.class);

	interface NetworkComplexityUiBinder extends
			UiBinder<Widget, NetworkComplexity> {
	}

	/**
	 * 자바 스크립트로 입력 자료 만들어서 분석 요청하기
	 */
	public native void callShiny(Element thisScope, String data) /*-{
		var shinyframe = thisScope.getElementsByTagName("iframe")[0];
		var msg = "{\"type\": \"str.comp\", \"data\":" + data + "}";
		shinyframe.contentWindow.postMessage(msg, shinyframe.src);
	}-*/;

	/*
	 * 캐시에서 읽어들일 엔티티 배열형
	 */
	final EventEntity[] eventArrayType = new EventEntity[0];

	public NetworkComplexity() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	class SimpleEvent {
		public long id;
		public int storyOrder;
		public double discourseTime;
	};

	public	void analyze() {
		SortedSet<SimpleEvent> storySequence = new TreeSet<SimpleEvent>(new Comparator<SimpleEvent>() {
			@Override
			public int compare(SimpleEvent arg0, SimpleEvent arg1) {
				return Integer.compare(arg0.storyOrder, arg1.storyOrder);
			}
		});
		SortedSet<SimpleEvent> plotSequence = new TreeSet<SimpleEvent>(new Comparator<SimpleEvent>() {
			@Override
			public int compare(SimpleEvent arg0, SimpleEvent arg1) {
				return Double.compare(arg0.discourseTime, arg1.discourseTime);
			}
		});
		for (EventEntity e : LocalCache.entities(EventEntity.class, eventArrayType)) {
			if (e.isOnStoryTime() && e.isPlotted()){
				for (Interval inter : e.getDiscourseInOut()) {
					SimpleEvent se = new SimpleEvent();
					se.id = e.getId();
					se.storyOrder = e.getOrdinalStoryIn();
					se.discourseTime = inter.getBegin();
					storySequence.add(se);
					plotSequence.add(se);
				}
			}
		}
		if (storySequence.size() > 0) {
			Iterator<SimpleEvent> is = storySequence.iterator();
			Iterator<SimpleEvent> ip = plotSequence.iterator();
			String eventSeq = "[" + Long.toString(is.next().id);
			String plotSeq = "[" + Long.toString(ip.next().id);
			while (is.hasNext()) {
				eventSeq += "," + is.next().id;
				plotSeq += "," + ip.next().id;
			}
			eventSeq += "]";
			plotSeq += "]";
			String data = "{ \"event_seq\": " + eventSeq + ", \"plot_seq\": " + plotSeq + " }";
			callShiny(DOM.asOld(getElement()), data);
		}
	}

}


text:
package travelapp.config;

import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import travelapp.hotel.entity.Booking;
import travelapp.session.ManagerSession;

@SuppressWarnings("serial")
public class RetrieveAllBookingsServlet extends HttpServlet {

    @EJB
    private ManagerSession managerSession;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        List<Booking> bookings = managerSession.getBookings();
	req.setAttribute("bookings", bookings);

	try {
            req.getRequestDispatcher("bookings.jsp").forward(req, resp);
	} catch (ServletException e) {
            // redirect to home page
            resp.sendRedirect("index.jsp");
	}
    }
}


text:
using Discord;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CSSBot.Reminders;
using Discord.Commands;
using System.Reflection;
using CSSBot.Counters;
using CSSBot.Models;
using LiteDB;
using CSSBot.Tags;
using CSSBot.Services.TheSpookening;
using CSSBot.Services;
using CSSBot.Services.Courses;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.ApplicationInsights;
using System.Runtime.CompilerServices;

namespace CSSBot
{
    public static class LogSeverityExtensions
    {
        public static LogLevel ToLogLevel(this LogSeverity severity)
        {
            switch (severity)
            {
                case LogSeverity.Critical:
                    return LogLevel.Critical;
                case LogSeverity.Error:
                    return LogLevel.Error;
                case LogSeverity.Warning:
                    return LogLevel.Warning;
                case LogSeverity.Info:
                    return LogLevel.Information;
                case LogSeverity.Debug:
                    return LogLevel.Debug;
                case LogSeverity.Verbose:
                default:
                    return LogLevel.Trace;
            }
        }
    }

    public class Bot
    {

        private static TelemetryClient telemetryClient = null; // app insights logging

        private DiscordSocketClient m_client;
        private CommandService _commands;
        private IServiceProvider _services;
        private LiteDatabase _database;
        private MessageRetryService messageRetry;
        private static ILogger logger;

        private void SetupLogging()
        {
            using var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder
                    .AddFilter(x => true) // enable it all
                    .SetMinimumLevel(LogLevel.Trace)
                    .AddConsole()
                    .AddDebug();

                if (!string.IsNullOrWhiteSpace(Program.GlobalConfiguration.Data.AppInsightsInstrumentationKey))
                {
                    builder.AddApplicationInsights(Program.GlobalConfiguration.Data.AppInsightsInstrumentationKey,
                        x =>
                        {
                            x.IncludeScopes = true;
                            x.TrackExceptionsAsExceptionTelemetry = true;
                            x.TrackExceptionsAsExceptionTelemetry = true;
                        });
                }
            });
            logger = loggerFactory.CreateLogger<Bot>();
            logger.LogDebug("Logger initialized.");

            // TODO: migrate away from DIY config and use IHostBuilder supported config
            // TODO: consider moving entry point from calling and waiting forever to using stuff that Host can do
        }

        public async Task Start()
        {
            SetupLogging();
            // only set the telemetryClient if the key is set
            if (Program.GlobalConfiguration.Data.AppInsightsInstrumentationKey != null)
            {
                var config = new TelemetryConfiguration(Program.GlobalConfiguration.Data.AppInsightsInstrumentationKey);
                telemetryClient = new TelemetryClient(config);
                telemetryClient.TrackTrace("App logging initialized.", SeverityLevel.Information);
            }

            // open or create our database (if it doesn't exist)
            _database = new LiteDatabase(Program.GlobalConfiguration.Data.LiteDatabasePath);

            // add our startup date
            var startup = _database.GetCollection<StartupEvent>("startup");
            startup.Insert(new StartupEvent() { Time = DateTime.Now });

            // starts our client
            // we use LogSeverity.Debug because more info the better
            m_client = new DiscordSocketClient(new DiscordSocketConfig() { LogLevel = Discord.LogSeverity.Verbose, AlwaysDownloadUsers = true });

            _commands = new CommandService();
            messageRetry = new MessageRetryService(m_client);

            // log in as a bot using our connection token
            await m_client.LoginAsync(TokenType.Bot, Program.GlobalConfiguration.Data.ConnectionToken);
            await m_client.StartAsync();

            // dependency injection
            _services = new ServiceCollection()
                .AddSingleton(m_client)
                .AddSingleton(_commands)
                .AddSingleton(_database)
                .AddSingleton(logger)
                .AddSingleton(new CounterService(_database, m_client))
                .AddSingleton(new ReminderService(m_client, _database))
                .AddSingleton(new TagService(_database))
                .AddSingleton(new SpookeningService(m_client, _database, Program.GlobalConfiguration.Data.SpookyConfigJson, logger))
                .AddSingleton(messageRetry)
                .AddSingleton(new MinesweeperSolutionService())
                .AddSingleton(new CourseService(m_client, logger))
                .BuildServiceProvider();

            await InstallCommandsAsync();
            messageRetry.OnCommandRetryHandler += commandMessageUpdated;

            // set up our logging function
            m_client.Log += Log;
            m_client.Log += async (logMessage) => {
                logger.Log(logMessage.Severity.ToLogLevel(), exception: logMessage.Exception, message: logMessage.Message, logMessage.Source, logMessage.Exception);
            };

            // show an invite link when we are ready to go
            m_client.Ready += Client_Ready;

            // set some help text
            await m_client.SetGameAsync($"Type {GlobalConfiguration.CommandPrefix}Help");

            // wait indefinitely
            await Task.Delay(-1);
        }

        private async Task commandMessageUpdated(SocketMessage arg)
        {
            // todo clean up copied and pasted code
            // Don't handle the command if it is a system message
            var message = arg as SocketUserMessage;
            if (message == null) return;

            // Mark where the prefix ends and the command begins
            int argPos = 0;
            // Determine if the message has a valid prefix, adjust argPos

            if (!(message.HasMentionPrefix(m_client.CurrentUser, ref argPos) || message.HasCharPrefix(GlobalConfiguration.CommandPrefix, ref argPos))) return;

            // Create a Command Context
            var context = new CommandContext(m_client, message);
            // Execute the Command, store the result
            try
            {
                var result = await _commands.ExecuteAsync(context, argPos, _services);

                // If the command failed
                if (!result.IsSuccess)
                {
                    // log the error
                    Discord.LogMessage errorMessage = new Discord.LogMessage(Discord.LogSeverity.Warning, "CommandHandler", result.ErrorReason);
                    await Log(errorMessage);
                    // don't actually reply back with the error

                    // todo reply back with an error message that corresponds to the closest matching command name
                }
            }
            catch (Exception e)
            {
                var error = new LogMessage(LogSeverity.Error, "CommandHandler", "Caught exception", e);
                await Log(error);
            }
        }

        private async Task InstallCommandsAsync()
        {
            m_client.MessageReceived += commandMessageReceived;
            await _services.GetRequiredService<CommandService>().AddModulesAsync(Assembly.GetEntryAssembly(), _services);
        }

        private async Task commandMessageReceived(SocketMessage arg)
        {
            // Don't handle the command if it is a system message
            var message = arg as SocketUserMessage;
            if (message == null) return;

            // Mark where the prefix ends and the command begins
            int argPos = 0;
            // Determine if the message has a valid prefix, adjust argPos

            if (!(message.HasMentionPrefix(m_client.CurrentUser, ref argPos) || message.HasCharPrefix(GlobalConfiguration.CommandPrefix, ref argPos)))
            {
                // messageRetry.RegisterFailedCommand(arg.Id);
                return;
            }

            // Create a Command Context
            var context = new CommandContext(m_client, message);
            // Execute the Command, store the result
            var result = await _commands.ExecuteAsync(context, argPos, _services);

            try
            {
                // If the command failed
                if (!result.IsSuccess)
                {
                    if (result is ExecuteResult exeResult)
                    {
                        logger.LogError(exeResult.Exception, result.ErrorReason);
                    }

                    // log the error
                    Discord.LogMessage errorMessage = new Discord.LogMessage(Discord.LogSeverity.Warning, "CommandHandler", result.ErrorReason);
                    await Log(errorMessage);
                    // don't actually reply back with the error

                    // todo reply back with an error message that corresponds to the closest matching command name
                }
            }
            catch (Exception e)
            {
                var error = new LogMessage(LogSeverity.Error, "CommandHandler", "Caught exception", e);
                await Log(error);
            }
        }

        private async Task Client_Ready()
        {
            // display a helpful invite url in the log when the bot is ready
            var application = await m_client.GetApplicationInfoAsync();
            await Log(new LogMessage(LogSeverity.Info, "Program",
                $"Invite URL: <https://discordapp.com/oauth2/authorize?client_id={application.Id}&scope=bot>"));
        }

        // todo: remove this and use DI instead of statics
        public async static Task Log(Discord.LogMessage arg)
        {
            logger?.Log(arg.Severity.ToLogLevel(), exception: arg.Exception, message: arg.Message, arg.Source, arg.Exception);
            var appInsightsSeverity = ConvertLogSeverity(arg.Severity);
            if (appInsightsSeverity != null && telemetryClient != null)
            {
                // this should be initialized once, clean it up later
                var properties = new Dictionary<string, string>()
                {
                    {nameof(arg.Exception), arg.Exception?.ToString() },
                    {nameof(arg.Message), arg.Message?.ToString() },
                    {nameof(arg.Severity), arg.Severity.ToString() },
                    {nameof(arg.Source), arg.Source?.ToString() },
                };

                if (arg.Exception != null)
                {
                    telemetryClient.TrackException(arg.Exception, properties: properties);
                }

                telemetryClient.TrackTrace(arg.Message, appInsightsSeverity.Value, properties: properties);
            }

            if (arg.Severity <= Discord.LogSeverity.Debug)
            {
                // log stuff to console
                // could also log to a file if needed later on
                Console.WriteLine(arg.ToString());
            }
        }

        private static SeverityLevel? ConvertLogSeverity(Discord.LogSeverity discordSeverity)
        {
            var dict = new Dictionary<Discord.LogSeverity, SeverityLevel>()
            {
                { Discord.LogSeverity.Critical, SeverityLevel.Critical },
                // do not log Debug
                // { Discord.LogSeverity.Debug, SeverityLevel.Verbose },
                { Discord.LogSeverity.Error, SeverityLevel.Error },
                { Discord.LogSeverity.Info, SeverityLevel.Information },
                { Discord.LogSeverity.Verbose, SeverityLevel.Verbose },
                { Discord.LogSeverity.Warning, SeverityLevel.Warning },
            };

            if (dict.ContainsKey(discordSeverity))
            {
                return dict[discordSeverity];
            }
            return null;
        }
    }
}


text:
(function() {
  'use strict';

  angular
    .module('app')
    .directive('propCurve', CurveDirective);

  CurveDirective.$inject = ['$parse', '$compile'];
  function CurveDirective($parse, $compile) {
    var directive = {
      require     : 'ngModel',
      restrict    : 'E',
      templateUrl : 'properties/curve.property.html',
      link        : linkFunction,
    };
    return directive;

    function linkFunction($scope, $element, $attrs, $ctrl) {
      // VARIABLES ------------------------------------------------------------
      var modalElement = null;
      var modalTemplate = null;

      // The property model
      var model = $parse($attrs.ngModel)($scope);

      // On change callback (from propertiespanel controller)
      var onChange = $parse($attrs.ngChange)($scope);

      // INITIALIZE -----------------------------------------------------------
      var initialize = function() {
        $scope.model = model;
        $scope.tempData = null;
        modalTemplate = $element.find('modal');
        modalTemplate.remove();
        modalTemplate = modalTemplate.html();

      };

      var copy = function(d) {
        return JSON.parse(JSON.stringify(d));
      };

      // EVENTS ---------------------------------------------------------------
      $scope.doChange = function() {
        // change value
        if (onChange) onChange();
      };
      $scope.openEditor = function() {
        $scope.tempData = {
          type: model.type,
          data: copy(model.data),
          xDomain: copy(model.xDomain),
          yDomain: copy(model.yDomain),
        };

        modalElement = $compile(modalTemplate)($scope);
        document.body.appendChild(modalElement[0]);
      };
      $scope.closeEditor = function() {
        modalElement.remove();
      };
      $scope.saveEditor = function() {
        model.type = $scope.tempData.type;
        model.data = $scope.tempData.data;
        model.xDomain = $scope.tempData.xDomain;
        model.yDomain = $scope.tempData.yDomain;
        modalElement.remove();
        $scope.doChange();
      };

      // DO INITIALIZE --------------------------------------------------------
      initialize();
    }
  }

})();