text:
package com.percolate.foam;

import android.content.Context;
import android.os.Build;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.http.GET;
import retrofit.http.Header;
import retrofit.http.Multipart;
import retrofit.http.POST;
import retrofit.http.Part;
import retrofit.http.Path;
import retrofit.mime.TypedFile;

/**
 * {@inheritDoc}
 */
class HockeyApp extends ServiceImpl implements CrashReportingService {

    private String apiKey;
    private SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
    protected HockeyAppService hockeyAppService;

    HockeyApp(Context context) {
        super(context);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void enable(String apiKey) {
        this.apiKey = apiKey;
   }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isEnabled() {
        return utils.isNotBlank(apiKey);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ServiceType getServiceType() {
        return ServiceType.HOCKEYAPP;
    }

    /**
     * {@inheritDoc}
     */
    public void logEvent(final StoredException storedException, final Callback<Object> deleteStoredExceptionCallback) {
        createService().getApps(apiKey, new Callback<HockeyAppsDTO>() {
            @Override
            public void success(HockeyAppsDTO appsList, Response response) {
                String appId = getAppIDFromResponse(appsList);
                if (utils.isNotBlank(appId)) {
                    createLogEvent(appId, storedException, deleteStoredExceptionCallback);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                utils.logIssue("Error getting HockeyApp list of apps", error);
            }
        });
    }

    /**
     * Lazy load instance of {@link HockeyAppService}
     * @return Instance of {@link HockeyAppService}.  Never null.
     */
    public HockeyAppService createService(){
        if(hockeyAppService == null) {
            RestAdapter restAdapter = new RestAdapter.Builder()
                    .setEndpoint("https://rink.hockeyapp.net")
                    .build();

            hockeyAppService = restAdapter.create(HockeyAppService.class);
        }
        return hockeyAppService;
    }

    /**
     * Return `apps[].public_identifier` for app where app.bundle_identifier == <package-name>
     * @param appsList List of application data returned from HockeyApp.
     * @return HockeyApp's public identifier for the current application.
     */
    protected String getAppIDFromResponse(HockeyAppsDTO appsList) {
        final String applicationPackageName = utils.getApplicationPackageName(context);
        String hockeyAppApplicationId = null;
        if (appsList != null && appsList.apps != null && !appsList.apps.isEmpty()) {
            for (HockeyAppDTO app : appsList.apps) {
                if (app.bundle_identifier != null && app.public_identifier != null) {
                    if ("Android".equalsIgnoreCase(app.platform)) {
                        if (app.bundle_identifier.equals(applicationPackageName)) {
                            hockeyAppApplicationId = app.public_identifier;
                            break;
                        }
                    }
                }
            }
        }
        return hockeyAppApplicationId;
    }

    /**
     * HockeyApp requires data to be in files uploaded via multipart POST request.
     * Here we create a file containing the log data.
     * @param appId HockeyApp application ID
     * @param storedException Data to place in a log file.
     * @param deleteStoredExceptionCallback Retrofit callback that will delete the exception file
     *                                      after it is uploaded.
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    void createLogEvent(String appId, StoredException storedException,
                                final Callback<Object> deleteStoredExceptionCallback) {
        final File logFile = writeHockeyAppCrashLog(storedException.stackTrace);
        if(logFile != null && logFile.exists()) {
            final TypedFile log = new TypedFile("text/plain", logFile);
            createService().createEvent(
                appId,
                log,
                createLogEventCallback(deleteStoredExceptionCallback, logFile)
            );
        }
    }

    /**
     * Callback that executes after we send data to HockeyApp.
     * Successful calls to HockeyApp will result in us removing the backing error & temp files.
     * Failed calls to HockeyApp will remove temp files, but leave error files.
     *
     * @param deleteStoredExceptionCallback Callback to remove backing error file.
     * @param logFile Temp log file containing data sent to HockeyApp.
     * @return Retrofit callback with implemented success/failure methods.
     */
    Callback<Response> createLogEventCallback(final Callback<Object> deleteStoredExceptionCallback, final File logFile) {
        return new Callback<Response>() {
            @Override
            public void success(Response resp, Response response) {
                if(!logFile.delete()){
                    utils.logIssue("Unable to clean up temp HockeyApp file", null);
                }
                if(deleteStoredExceptionCallback != null) {
                    deleteStoredExceptionCallback.success(resp, response);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                if(!logFile.delete()){
                    utils.logIssue("Unable to clean up temp HockeyApp file", null);
                }
                if(deleteStoredExceptionCallback != null) {
                    deleteStoredExceptionCallback.failure(error);
                }
            }
        };
    }

    /**
     * Write log file in format expected by hockey app.
     * see http://support.hockeyapp.net/kb/api/api-crashes#post-custom-crashes
     * @param stackTrace Stack track to include the log file.
     * @return File object containing data that can be sent to HockeyApp.
     */
    File writeHockeyAppCrashLog(String stackTrace) {
        File logFile = null;
        BufferedWriter writer;
        try {
            File outputDir = context.getCacheDir();
            logFile = File.createTempFile("hockey_app_crash_", ".log", outputDir);
            writer = new BufferedWriter(new FileWriter(logFile));
            writer.write("Package: " + utils.getApplicationPackageName(context) + "\n");
            writer.write("Version Code: " + utils.getVersionCode(context) + "\n");
            writer.write("Version Name: " + utils.getVersionName(context) + "\n");
            writer.write("Android: " + Build.VERSION.RELEASE + "\n");
            writer.write("Manufacturer: " + Build.MANUFACTURER + "\n");
            writer.write("Model: " + Build.MODEL + "\n");
            writer.write("Date: " + getTimestamp() + "\n");
            writer.write("\n");
            writer.write(stackTrace);
            writer.close();
        } catch (Exception ex) {
            utils.logIssue("Error writing crash report to temp log file", ex);
        }
        return logFile;
    }

    /**
     * Return current date & time in format expected by HockeyApp
     * @return timestamp in HockeyApp log file format.
     */
    String getTimestamp(){
        return df.format(new Date());
    }

    /**
     * Retrofit hockeyAppService
     */
    protected interface HockeyAppService {

        @GET("/api/2/apps")
        void getApps(@Header("X-HockeyAppToken") String apiKey,
                     Callback<HockeyAppsDTO> callback
        );

        @Multipart
        @POST("/api/2/apps/{APP_ID}/crashes/upload")
        void createEvent(@Path("APP_ID") String appId,
                         @Part("log") TypedFile log,
                         Callback<Response> callback
        );

    }

    /**
     * Object representation of JSON returned from HockeyApp
     */
    class HockeyAppsDTO {
        List<HockeyAppDTO> apps;
    }

    /**
     * Object representation of JSON returned from HockeyApp
     */
    @SuppressWarnings("UnusedDeclaration")
    class HockeyAppDTO {
        protected Integer id;
        protected String bundle_identifier;
        protected String public_identifier;
        protected String platform;
        protected Integer release_type;
        protected String custom_release_type;
        protected String created_at;
        protected String updated_at;
        protected String minimum_os_version;
        protected Integer status;
        protected String owner;
        protected String owner_token;
        protected String company;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

  <include layout="@layout/ir_toolbar_view"/>

  <!--This is the layout 4 add GLView from Vuforia-->
  <RelativeLayout
      android:id="@+id/layoutContentVuforiaGL"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="@android:color/transparent">

    <!--This is a OverlayLayout 4 put the Ox Watermark-->
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="@dimen/watermark_margin"
        android:layout_marginRight="@dimen/watermark_margin"
        android:gravity="end"
        style="@style/irCustomizationScanWaterMark"
        android:contentDescription="@null"
        />
  </RelativeLayout>

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
using Calcular.CoreApi.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Calcular.CoreApi.Models
{
    public class Log
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public LogTypeEnum Type { get; set; }
        public User User { get; set; }
        public DateTime CreatedAt { get; set; }
    }
}


text:
This is osquery, with logstash and filebeat, shipping into AWS Athena.

## Install

```shell
git clone <repo_url>
cd osquery-demo/aws-athena/ubuntu16
vagrant up
vagrant ssh
```

## Links

https://www.elastic.co/guide/en/logstash/current/plugins-outputs-s3.html

## Logs

```shell
/var/log/osquery/osqueryd.WARNING
/var/log/osquery/osqueryd.INFO
/var/log/osquery/osqueryd.results.log
cat /var/log/osquery/osqueryd.results.log | jq '.'

# filebeat
/var/log/filebeat/filebeat.log

# logstash
/var/log/logstash/logstash.log
/var/log/logstash/logstash.stdout
/var/log/logstash/logstash.err
```


text:
using System;
using Azure.Core;

namespace Azure.Communication.CallAutomation
{
    /// <summary> Configuration of Media streaming. </summary>
    internal partial class MediaStreamingOptionsInternal
    {
        /// <summary> Initializes a new instance of MediaStreamingOptionsInternal. </summary>
        /// <param name="transportUrl"> Transport URL for media streaming. </param>
        /// <param name="transportType"> The type of transport to be used for media streaming, eg. Websocket. </param>
        /// <param name="contentType"> Content type to stream, eg. audio, audio/video. </param>
        /// <param name="audioChannelType"> Audio channel type to stream, eg. unmixed audio, mixed audio. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="transportUrl"/> is null. </exception>
        public MediaStreamingOptionsInternal(string transportUrl, MediaStreamingTransport transportType, MediaStreamingContent contentType, MediaStreamingAudioChannel audioChannelType)
        {
            Argument.AssertNotNull(transportUrl, nameof(transportUrl));

            TransportUrl = transportUrl;
            TransportType = transportType;
            ContentType = contentType;
            AudioChannelType = audioChannelType;
        }

        /// <summary> Transport URL for media streaming. </summary>
        public string TransportUrl { get; }
        /// <summary> The type of transport to be used for media streaming, eg. Websocket. </summary>
        public MediaStreamingTransport TransportType { get; }
        /// <summary> Content type to stream, eg. audio, audio/video. </summary>
        public MediaStreamingContent ContentType { get; }
        /// <summary> Audio channel type to stream, eg. unmixed audio, mixed audio. </summary>
        public MediaStreamingAudioChannel AudioChannelType { get; }
    }
}


text:
/**
Interface describing a message dispatcher.
@interface IPacketDispatcher
@memberof Stormancer
*/
/**
Adds a packet processor to the dispatcher.
@method Stormancer.IPacketDispatcher#addProcessor
@param {Stormancer.IPacketProcessor} processor An `IPacketProcessor` object
*/
/**
Dispatches a packet to the system.
@method Stormancer.IPacketDispatcher#dispatchPacket
@param {Stormancer.Packet} packet Packet to dispatch.
*/

/*export*/ interface IPacketDispatcher {

    addProcessor(processor: IPacketProcessor): void;

    dispatchPacket(packet: Packet<IConnection>): void;
}


text:
import java.util.Map;

/**
 * The Java back end uses properties
 * instead of environment variables.
 * This wrapper loads the env variables
 * into the standard set of properties.
 */
public class Reg029Wrapper {
  public static void main(String args[]) {
    Map<String, String> env = System.getenv();
    for (String key : env.keySet()) {
      System.setProperty(key, env.get(key));
    }
    reg029.main(args);
  }
}


text:
import { getDefaultAxisLength, getGridSize } from "../index";
import { WebAppConfig } from "farmbot/dist/resources/configs/web_app";

describe("getDefaultAxisLength()", () => {
  it("returns axis lengths", () => {
    const axes = getDefaultAxisLength(() => false);
    expect(axes).toEqual({ x: 2900, y: 1400 });
  });
});

describe("getGridSize()", () => {
  it("returns default grid size", () => {
    const grid = getGridSize(
      k => ({ dynamic_map: false } as WebAppConfig)[k], {
        x: { value: 100, isDefault: false },
        y: { value: 200, isDefault: false }
      });
    expect(grid).toEqual({ x: 2900, y: 1400 });
  });

  it("returns custom grid size", () => {
    const grid = getGridSize(
      k => ({
        dynamic_map: false, map_size_x: 300, map_size_y: 400
      } as WebAppConfig)[k], {
        x: { value: 100, isDefault: false },
        y: { value: 200, isDefault: false }
      });
    expect(grid).toEqual({ x: 300, y: 400 });
  });

  it("returns grid size using bot size", () => {
    const grid = getGridSize(
      k => ({ dynamic_map: true } as WebAppConfig)[k], {
        x: { value: 100, isDefault: false },
        y: { value: 200, isDefault: false }
      });
    expect(grid).toEqual({ x: 100, y: 200 });
  });
});


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.hyperledger.api;

import org.hyperledger.common.Address;
import org.hyperledger.common.PrivateKey;
import org.junit.Test;

import java.io.*;

import static org.junit.Assert.assertEquals;

/**
 *
 */
public class AddressSerializationTest {

    @Test
    public void testAddressSerialization() throws IOException, ClassNotFoundException {
        Address address = PrivateKey.createNew(true).getAddress();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(baos);
        out.writeObject(address);
        out.flush();

        byte[] bytes = baos.toByteArray();
        Address address2 = (Address) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();

        assertEquals(address, address2);
    }
}


text:
"""
This module is the login command of ink.

Created on 16 February 2014
@author: Charlie Lewis
"""

class login(object):
    """
    This class is responsible for the login command of the cli.
    """
    @classmethod
    def main(self, args):
        # !! TODO
        print args


text:
class EngComponent {
public:
    virtual         ~EngComponent();
    virtual void    update() = 0;
};

#endif


text:
.gold {
    background: transparent !important;
    color: #b68d4c !important;
}


text:
package drt.client.components

import drt.client.logger.{Logger, LoggerFactory}
import drt.shared.SDateLike
import drt.shared.redlist.{ApiIndirectRedListPax, RedList}
import japgolly.scalajs.react.component.Scala.Component
import japgolly.scalajs.react.vdom.html_<^._
import japgolly.scalajs.react.{CtorType, ScalaComponent}

object NationalityFinderComponent {
  def isRedListCountry(country: String, date: SDateLike): Boolean =
    RedList.countryCodesByName(date.millisSinceEpoch).keys.exists(_.toLowerCase == country.toLowerCase)

  val log: Logger = LoggerFactory.getLogger(getClass.getName)
  val component: Component[ApiIndirectRedListPax, Unit, Unit, CtorType.Props] = ScalaComponent.builder[ApiIndirectRedListPax]("FlightChart")
    .render_P { props =>
      <.span(
        props.maybeNationalities match {
          case Some(nats) if nats.values.sum > 0 =>
            NationalityFinderChartComponent(
              NationalityFinderChartComponent.Props(nats, <.span(^.className := "badge", nats.values.sum))
            )
          case Some(_) => 0
          case None => EmptyVdom
        }
      )
    }
    .build

  def apply(apiIndirectRedListPax: ApiIndirectRedListPax): VdomElement = component(apiIndirectRedListPax)

}


text:
.. _developing:

Developing for spin-docker
==========================

Contributing to spin-docker development is easy! `Fork the GitHub repository <https://github.com/atbaker/spin-docker>`_ and you're halfway there!

Development environment setup
-----------------------------

The easiest way to set up a spin-docker development environment is to follow the instructions in :ref:`vagrant_setup`.

Once you have provisioned your vagrant box, you can run the Flask development server with these steps:

#. ``vagrant ssh`` into the box
#. Switch to the root user (necessary to start the development server on port 80, which is forwarded by Vagrant)
#. Stop the nginx, gunicorn, and celery services:

    .. code-block:: bash

        $ service nginx stop
        $ service gunicorn stop
        $ service celery stop

#. ``cd`` to the ``/var/www``
#. Activate the spin-docker virutal environment: ``source venv/bin/activate``
#. ``cd`` into the ``spin-docker`` directory
#. Apply the spin-docker environment variables with ``source .env``
#. Start the Flask development server: ``python runserver.py``

Activity monitoring, stopping, and deleting containers are managed by Celery. You can start the Celery worker in a separate terminal session (but still as root, because docker is currently configured only for root):

#. ``cd`` to the ``/var/www``
#. Activate the spin-docker virutal environment: ``source venv/bin/activate``
#. ``cd`` into the ``spin-docker`` directory
#. Apply the spin-docker environment variables with ``source .env``
#. Run the command ``celery -A spindocker.tasks.celery worker -l info``

Running tests
-------------

To run the spin-docker tests and view current code coverage, follow these steps (again as root):

#. ``cd`` to the ``/var/www``
#. Activate the spin-docker virutal environment: ``source venv/bin/activate``
#. ``cd`` into the ``spin-docker`` directory
#. Apply the spin-docker environment variables with ``source .env``
#. Install the test requirements in you haven't already: ``pip install -r requirements/test.txt``
#. Run the command ``coverage run --source=spindocker tests.py``

After the tests run, you can view current coverage with ``coverage report`` and generate an HTML report with ``coverage html``.

Building the docs
-----------------

If you make changes to the spin-docker documentation, you can check your work by building the docs with ``make html`` in the ``docs`` directory.


text:
@extends('muffincms::layouts.admin')

@section('title', 'Creating Image')

@section('content')

Creating New Image

	<form method="POST" action="{{url('/admin/image/store')}}" class="form">
		{{ csrf_field() }}

			Url
			<input type="text" id="image-url" name="url" value="{{old('url', $url)}}" readonly="readonly" class="form-control">
			Location
			<input type="text" id="image-location" name="location" value="{{old('location', $location)}}" readonly="readonly" class="form-control">

	          		 Choose Image

	      	<input id="thumbnail" class="form-control" type="text" name="image" value="{{old('image')}}">

has('alt') ? ' has-error' : '' }}">
			Alt
			<input type="text" id="image-alt" name="alt" value="{{old('alt')}}" class="form-control">
			@if ($errors->has('alt'))

		            {{ $errors->first('alt') }}

		    @endif

				<input type="checkbox" name="global" @if(old('global'))checked="checked" @endif> Show on all ({{$location}}) regardless of the url.

			<input type="submit" name="submit" value="Submit" class="btn btn-primary">
			Cancel

	</form>

@endsection

@section('script')

@endsection


text:
package com.oregonscientific.meep.message.common;

public class RunSqlResultMessage {
	private int mErrCode = 0;
	private String mError  = null;

	public RunSqlResultMessage(){
		setErrCode(0);
		setErrorString("");
	}

	public RunSqlResultMessage(int errorCode, String errorString){
		setErrCode(errorCode);
		setErrorString(errorString);
	}

	public int getErrCode() {
		return mErrCode;
	}

	public void setErrCode(int mErrCode) {
		this.mErrCode = mErrCode;
	}

	public String getErrorString() {
		return mError;
	}

	public void setErrorString(String mError) {
		this.mError = mError;
	}
}


text:
import java.util.function.Function;
class Test {

  Function<String, Runnable> f = (str) -> () -> foo(<selection>""</selection>);

  void foo(String s) {}
}


text:
layout: page
title: Hendricks 40th Anniversary
date: 2016-05-24
author: Linda Myers
tags: weekly links, java
status: published
summary: Proin interdum pretium metus. Duis vitae mauris non.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 06/02/2018
  endDate: 06/06/2018
  ctyhocn: ATLELHX
  groupCode: H4A
published: true
---
Nulla suscipit fringilla felis, quis iaculis ligula mollis varius. Duis id ante odio. Ut vitae mauris eu nisi feugiat aliquam vel nec eros. Mauris at eros et purus dapibus pulvinar in ac mauris. Vestibulum non diam maximus, lacinia leo ut, feugiat lorem. Aliquam quis eleifend mauris. Proin vel metus varius, porta mi vel, commodo odio. Donec sed consequat orci, vitae scelerisque dui. Praesent turpis orci, convallis sit amet erat eu, faucibus semper dui. Phasellus a nibh convallis, venenatis velit quis, venenatis elit. Quisque tellus lectus, luctus eget eros a, ultrices consequat magna. Sed lacinia tempus sapien, luctus eleifend ante semper id.

* Fusce sit amet erat porttitor, gravida enim aliquam, venenatis elit.

Aliquam erat volutpat. Sed vel laoreet quam. Pellentesque quam risus, tincidunt at velit vel, varius dictum quam. Cras ultrices viverra ultrices. Donec mauris arcu, pretium sit amet rutrum sed, accumsan sit amet tortor. Duis fringilla ut magna quis tincidunt. Aliquam nec viverra tellus, a pretium enim. Maecenas id lorem non mi cursus mollis.


text:
// This file is automatically generated.

package adila.db;

/*
 * Huawei X2
 *
 * DEVICE: HWGemini
 * MODEL: GEM-703LT
 */
final class hwgemini_gem2d703lt {
    public static final String DATA = "Huawei|X2|";
}


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

namespace Microsoft.CodeAnalysis.PooledObjects
{
    internal partial class ArrayBuilder<T> : IPooled
    {
        public static PooledDisposer<ArrayBuilder<T>> GetInstance(out ArrayBuilder<T> instance)
        {
            instance = GetInstance();
            return new PooledDisposer<ArrayBuilder<T>>(instance);
        }

        public static PooledDisposer<ArrayBuilder<T>> GetInstance(int capacity, out ArrayBuilder<T> instance)
        {
            instance = GetInstance(capacity);
            return new PooledDisposer<ArrayBuilder<T>>(instance);
        }

        public static PooledDisposer<ArrayBuilder<T>> GetInstance(int capacity, T fillWithValue, out ArrayBuilder<T> instance)
        {
            instance = GetInstance(capacity, fillWithValue);
            return new PooledDisposer<ArrayBuilder<T>>(instance);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "DTD/xhtml1-strict.dtd">

    <title>elita.models.DataService : API documentation</title>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
    <link href="apidocs.css" type="text/css" rel="stylesheet" />

e.m.DataService : class documentation

      Part of elita.models

      View In Hierarchy

DataService is an object that holds all the data-layer handling objects.
A DataService instance is part of the request object and also passed to
async jobs, etc. It is the main internal API for data handling.

    Method
    __init__
    No summary

    Method
    GetAppKeys
    Undocumented

    Method
    GetGlobalKeys
    Undocumented

    def
    __init__(self, settings, db, root, job_id=None):

    def
    GetAppKeys(self, app):

Undocumented

    def
    GetGlobalKeys(self):

Undocumented

    <address>
      API Documentation for elita, generated by pydoctor at 2014-09-25 10:44:58.
    </address>


text:
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rapidsms_tut.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)


text:
namespace diagnostics {

// This is the count of diagnostic tests on each platform.  This should
// only be used by testing code.
#if defined(OS_WIN)
const int DiagnosticsModel::kDiagnosticsTestCount = 18;
#elif defined(OS_MACOSX)
const int DiagnosticsModel::kDiagnosticsTestCount = 14;
#elif defined(OS_POSIX)
#if defined(OS_CHROMEOS)
const int DiagnosticsModel::kDiagnosticsTestCount = 18;
#else
const int DiagnosticsModel::kDiagnosticsTestCount = 16;
#endif
#endif

namespace {

// Embodies the commonalities of the model across platforms. It manages the
// list of tests and can loop over them. The main job of the platform specific
// code becomes:
// 1- Inserting the appropriate tests into |tests_|
// 2- Overriding RunTest() to wrap it with the appropriate fatal exception
//    handler for the OS.
// This class owns the all the tests and will only delete them upon
// destruction.
class DiagnosticsModelImpl : public DiagnosticsModel {
 public:
  DiagnosticsModelImpl() : tests_run_(0) {}

  ~DiagnosticsModelImpl() override { STLDeleteElements(&tests_); }

  int GetTestRunCount() const override { return tests_run_; }

  int GetTestAvailableCount() const override { return tests_.size(); }

  void RunAll(DiagnosticsModel::Observer* observer) override {
    size_t test_count = tests_.size();
    bool continue_running = true;
    for (size_t i = 0; i != test_count; ++i) {
      // If one of the diagnostic steps returns false, we want to
      // mark the rest of them as "skipped" in the UMA stats.
      if (continue_running) {
        continue_running = RunTest(tests_[i], observer, i);
        ++tests_run_;
      } else {
#if defined(OS_CHROMEOS)  // Only collecting UMA stats on ChromeOS
        RecordUMATestResult(static_cast<DiagnosticsTestId>(tests_[i]->GetId()),
                            RESULT_SKIPPED);
#else
        // On other platforms, we can just bail out if a diagnostic step returns
        // false.
        break;
#endif
      }
    }
    if (observer)
      observer->OnAllTestsDone(this);
  }

  void RecoverAll(DiagnosticsModel::Observer* observer) override {
    size_t test_count = tests_.size();
    bool continue_running = true;
    for (size_t i = 0; i != test_count; ++i) {
      // If one of the recovery steps returns false, we want to
      // mark the rest of them as "skipped" in the UMA stats.
      if (continue_running) {
        continue_running = RunRecovery(tests_[i], observer, i);
      } else {
#if defined(OS_CHROMEOS)  // Only collecting UMA stats on ChromeOS
        RecordUMARecoveryResult(
            static_cast<DiagnosticsTestId>(tests_[i]->GetId()), RESULT_SKIPPED);
#else
        // On other platforms, we can just bail out if a recovery step returns
        // false.
        break;
#endif
      }
    }
    if (observer)
      observer->OnAllRecoveryDone(this);
  }

  const TestInfo& GetTest(size_t index) const override {
    return *tests_[index];
  }

  bool GetTestInfo(int id, const TestInfo** result) const override {
    DCHECK(id < DIAGNOSTICS_TEST_ID_COUNT);
    DCHECK(id >= 0);
    for (size_t i = 0; i < tests_.size(); i++) {
      if (tests_[i]->GetId() == id) {
        *result = tests_[i];
        return true;
      }
    }
    return false;
  }

 protected:
  // Run a particular diagnostic test. Return false if no other tests should be
  // run.
  virtual bool RunTest(DiagnosticsTest* test,
                       Observer* observer,
                       size_t index) {
    return test->Execute(observer, this, index);
  }

  // Recover from a particular diagnostic test. Return false if no further
  // recovery should be run.
  virtual bool RunRecovery(DiagnosticsTest* test,
                           Observer* observer,
                           size_t index) {
    return test->Recover(observer, this, index);
  }

  typedef std::vector<DiagnosticsTest*> TestArray;
  TestArray tests_;
  int tests_run_;

 private:
  DISALLOW_COPY_AND_ASSIGN(DiagnosticsModelImpl);
};

// Each platform can have their own tests. For the time being there is only
// one test that works on all platforms.
#if defined(OS_WIN)
class DiagnosticsModelWin : public DiagnosticsModelImpl {
 public:
  DiagnosticsModelWin() {
    tests_.push_back(MakeOperatingSystemTest());
    tests_.push_back(MakeConflictingDllsTest());
    tests_.push_back(MakeInstallTypeTest());
    tests_.push_back(MakeVersionTest());
    tests_.push_back(MakeUserDirTest());
    tests_.push_back(MakeLocalStateFileTest());
    tests_.push_back(MakeDictonaryDirTest());
    tests_.push_back(MakeResourcesFileTest());
    tests_.push_back(MakeDiskSpaceTest());
    tests_.push_back(MakePreferencesTest());
    tests_.push_back(MakeLocalStateTest());
    tests_.push_back(MakeBookMarksTest());
    tests_.push_back(MakeSqliteWebDataDbTest());
    tests_.push_back(MakeSqliteCookiesDbTest());
    tests_.push_back(MakeSqliteFaviconsDbTest());
    tests_.push_back(MakeSqliteHistoryDbTest());
    tests_.push_back(MakeSqliteTopSitesDbTest());
    tests_.push_back(MakeSqliteWebDatabaseTrackerDbTest());
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DiagnosticsModelWin);
};

#elif defined(OS_MACOSX)
class DiagnosticsModelMac : public DiagnosticsModelImpl {
 public:
  DiagnosticsModelMac() {
    tests_.push_back(MakeInstallTypeTest());
    tests_.push_back(MakeUserDirTest());
    tests_.push_back(MakeLocalStateFileTest());
    tests_.push_back(MakeDictonaryDirTest());
    tests_.push_back(MakeDiskSpaceTest());
    tests_.push_back(MakePreferencesTest());
    tests_.push_back(MakeLocalStateTest());
    tests_.push_back(MakeBookMarksTest());
    tests_.push_back(MakeSqliteWebDataDbTest());
    tests_.push_back(MakeSqliteCookiesDbTest());
    tests_.push_back(MakeSqliteFaviconsDbTest());
    tests_.push_back(MakeSqliteHistoryDbTest());
    tests_.push_back(MakeSqliteTopSitesDbTest());
    tests_.push_back(MakeSqliteWebDatabaseTrackerDbTest());
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DiagnosticsModelMac);
};

#elif defined(OS_POSIX)
class DiagnosticsModelPosix : public DiagnosticsModelImpl {
 public:
  DiagnosticsModelPosix() {
    tests_.push_back(MakeInstallTypeTest());
    tests_.push_back(MakeVersionTest());
    tests_.push_back(MakeUserDirTest());
    tests_.push_back(MakeLocalStateFileTest());
    tests_.push_back(MakeDictonaryDirTest());
    tests_.push_back(MakeResourcesFileTest());
    tests_.push_back(MakeDiskSpaceTest());
    tests_.push_back(MakePreferencesTest());
    tests_.push_back(MakeLocalStateTest());
    tests_.push_back(MakeBookMarksTest());
    tests_.push_back(MakeSqliteWebDataDbTest());
    tests_.push_back(MakeSqliteCookiesDbTest());
    tests_.push_back(MakeSqliteFaviconsDbTest());
    tests_.push_back(MakeSqliteHistoryDbTest());
    tests_.push_back(MakeSqliteTopSitesDbTest());
    tests_.push_back(MakeSqliteWebDatabaseTrackerDbTest());
#if defined(OS_CHROMEOS)
    tests_.push_back(MakeSqliteNssCertDbTest());
    tests_.push_back(MakeSqliteNssKeyDbTest());
#endif
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DiagnosticsModelPosix);
};

#endif

}  // namespace

DiagnosticsModel* MakeDiagnosticsModel(const base::CommandLine& cmdline) {
  base::FilePath user_data_dir =
      cmdline.GetSwitchValuePath(switches::kUserDataDir);
  if (!user_data_dir.empty())
    PathService::Override(chrome::DIR_USER_DATA, user_data_dir);
#if defined(OS_WIN)
  return new DiagnosticsModelWin();
#elif defined(OS_MACOSX)
  return new DiagnosticsModelMac();
#elif defined(OS_POSIX)
  return new DiagnosticsModelPosix();
#endif
}

}  // namespace diagnostics


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>ITimeoutEvent (JRuyi API 1.2.0)</title>
<meta name="date" content="2014-02-20">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jruyi.timeoutadmin

Interface ITimeoutEvent

public interface ITimeoutEvent

An event indicating that the time is out.

Method Summary

Methods

Modifier and Type
Method and Description

Object
getSubject()

Gets the subject of this event.

int
getTimeout()

Gets the time in seconds that is out.

Method Detail

getSubject

Object getSubject()

Gets the subject of this event.

Returns:

the subject

getTimeout

int getTimeout()

Gets the time in seconds that is out.

Returns:

the time is out

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2014 JRuyi.org. All rights reserved.


text:
var sliderControl = null;

var map = L.map('map').setView([51.9, 7.9], 9);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
	attribution: '© OpenStreetMap contributors'
}).addTo(map);

//Fetch some data from a GeoJSON file
$.getJSON("points.json", function(json) {

	var testlayer = L.geoJson(json);

	// Check into MCG Layer Support!
	// Add to map first before checking in.
	L.markerClusterGroup.layerSupport().addTo(map).checkIn(testlayer);

	var sliderControl = L.control.sliderControl({
		position: "topright",
		layer: testlayer,
		range: true
	});

	//Make sure to add the slider to the map ;-)
	map.addControl(sliderControl);
	//And initialize the slider
	sliderControl.startSlider();
});


text:
[jQuery Mobile](http://jquerymobile.com/) tag and attribute autocompletions in Atom. Install
[autocomplete-plus](https://github.com/atom-community/autocomplete-plus) before
installing this package.

This is powered by the list of HTML tags [here](https://raw.githubusercontent.com/chrisgriffith/jQuery-Mobile-Brackets-Extension/master/HtmlTags.json)
and HTML attributes [here](https://raw.githubusercontent.com/chrisgriffith/jQuery-Mobile-Brackets-Extension/master/HtmlAttributes.json)

You can update the prebuilt list of tags and attributes names and values by
running the `update.coffee` file at the root of the repository and then checking
in the changed `completions.json` file.


text:
@font-face {
	font-family: 'promafa';
	src: url('../font/promafa.eot?20486504');
	src: url('../font/promafa.eot?20486504#iefix') format('embedded-opentype'),
	     url('../font/promafa.woff?20486504') format('woff'),
	     url('../font/promafa.ttf?20486504') format('truetype'),
	     url('../font/promafa.svg?20486504#promafa') format('svg');
	font-weight: normal;
	font-style: normal;
}
/* Chrome hack: SVG is rendered more smooth in Windozze. 100% magic, uncomment if you need it. */
/* Note, that will break hinting! In other OS-es font will be not as sharp as it could be */
/*
@media screen and (-webkit-min-device-pixel-ratio:0) {
  @font-face {
    font-family: 'promafa';
    src: url('../font/promafa.svg?20486504#promafa') format('svg');
  }
}
*/

[class^="icon-"]:before, [class*=" icon-"]:before {
	font-family: "promafa";
	font-style: normal;
	font-weight: normal;
	speak: none;

	display: inline-block;
	text-decoration: inherit;
	width: 1em;
	margin-right: .2em;
	text-align: center;
	/* opacity: .8; */

	/* For safety - reset parent styles, that can break glyph codes*/
	font-variant: normal;
	text-transform: none;

	/* fix buttons height, for twitter bootstrap */
	line-height: 1em;

	/* Animation center compensation - margins should be symmetric */
	/* remove if not needed */
	margin-left: .2em;

	/* you can be more comfortable with increased icons size */
	/* font-size: 120%; */

	/* Font smoothing. That was taken from TWBS */
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;

	/* Uncomment for 3D effect */
	/* text-shadow: 1px 1px 1px rgba(127, 127, 127, 0.3); */
}

.icon-fax:before { content: '\e800'; } /* '' */
.icon-phone:before { content: '\e801'; } /* '' */
.icon-mail:before { content: '\e802'; } /* '' */
.icon-map:before { content: '\e803'; } /* '' */
.icon-menu:before { content: '\e804'; } /* '' */
.icon-align-right:before { content: '\e805'; } /* '' */
.icon-cancel:before { content: '\e806'; } /* '' */
.icon-globe:before { content: '\e807'; } /* '' */
.icon-right-open:before { content: '\e808'; } /* '' */
.icon-left-open:before { content: '\e809'; } /* '' */
.icon-lock:before { content: '\e80a'; } /* '' */
.icon-spin4:before { content: '\e80b'; } /* '' */
.icon-facebook:before { content: '\e80c'; } /* '' */
.icon-instagram:before { content: '\e80d'; } /* '' */
.icon-blogger:before { content: '\e80e'; } /* '' */
.icon-direction:before { content: '\e80f'; } /* '' */S


text:
package com.github.dan4ik95dv.famousartists.ui.view;

import com.github.dan4ik95dv.famousartists.ui.fragment.ArtistsFragment;

/**
 * Created by Daniil Celikin on 16.04.2016.
 * https://github.com/dan4ik95dv/famousartists
 */
public interface ArtistsMvpView extends FragmentMvpView {

    ArtistsFragment getFragment();

    void hideProgress();

    void empty();

    void success();

    void error();

}


text:
@interface Background()

-(void) updateLayer:(NSMutableArray *)layer index:(int)ind;
-(void) drawBackdrop;
-(void) clearScreenObjects:(NSMutableArray *)layer;

@end

@implementation Background

-(id) initWithScreen:(ContainerLayer *) screen BackDrop:(ContainerLayer *)backdrop {

	self = [super init];
	itemLayer = screen;
	backdropLayer = backdrop;

	screenWidth = GAME_SCREEN_WIDTH;
	screenHeight = GAME_SCREEN_HEIGHT;

	backdrops = [[NSMutableArray alloc] init];

	layer2 = [[NSMutableArray alloc] init];
	layer3 = [[NSMutableArray alloc] init];
	layer4 = [[NSMutableArray alloc] init];
	layer5 = [[NSMutableArray alloc] init];

	layerFront = [[NSMutableArray alloc] init];

	indexation = [[NSMutableArray alloc] init];
	[indexation addObject: [JPFloat create:1.0f]];
	[indexation addObject: [JPFloat create:2.0f]];
	[indexation addObject: [JPFloat create:3.5f]];
	[indexation addObject: [JPFloat create:6.0f]];
	[indexation addObject: [JPFloat create:9.0f]];
	[indexation addObject: [JPFloat create:13.0f]];

	started = FALSE;
	startedCharacter = FALSE;

	nextAnimationTick = 24;
	leftAnimationTick = 0;

	return self;
}

-(void) setSkyCharacter:(NSString *) ch {
	skyCharacter = ch;
}

-(void) setSkyCharacterColor:(Color *)clr {
	skyCharacterColor = clr;
}

-(void) setGroundCharacter:(NSString *) ch Color:(Color *)clr FocusRadio:(float)radio {

	groundCharacter = ch;
	groundCharacterColor = clr;
	focusRadio = radio;

	[indexation removeAllObjects];
	float index = 1.0f;
	for (int i = 0; i < 6; i ++) {
		[indexation addObject: [JPFloat create:index]];
		index *= radio; // [Common getRandomFrom:radio*0.9 To:radio*1.1];;
	}
}

-(void) clearAll {

	[self clearScreenObjects:backdrops];
	[self clearScreenObjects:layer2];
	[self clearScreenObjects:layer3];
	[self clearScreenObjects:layer4];
	[self clearScreenObjects:layer5];
}

-(void) clearScreenObjects:(NSMutableArray *)layer {

	for (int i=0; i < [layer count]; i++) {
		Sprite *sprite = [layer objectAtIndex:i];
		[sprite removeFromCurrentScene];
	}
	[layer removeAllObjects];
}

-(void) start {

	horizon = nextHorizon;
	upDelta = nextUpDelta;
	downDelta = nextDownDelta;
	angel = nextAngel;
	leftAnimationTick = 0;

	[self drawBackdrop];
	[self startCharacter];

	started = TRUE;
}

-(void) stop {
	[self stopCharacter];
	started = FALSE;
}

-(void) update {

	if (!started) {
		return;
	}
	// Move the view angel
	if (leftAnimationTick > 0) {

		//NSLog(@"Move View Angel...");
		upDelta += (nextUpDelta - upDelta) / leftAnimationTick;
		downDelta += (nextDownDelta - downDelta) / leftAnimationTick;
		horizon += (nextHorizon - horizon) / leftAnimationTick;
		angel += (nextAngel - angel) / leftAnimationTick;

		// redraw the backlop
		[self drawBackdrop];

		leftAnimationTick --;
	}

	[self updateLayer:layer2 index:1];
	[self updateLayer:layer3 index:2];
	[self updateLayer:layer4 index:3];
	[self updateLayer:layer5 index:4];
}

-(void) updateLayer:(NSMutableArray *)layer index:(int)ind {

	float index = [[indexation objectAtIndex:ind] getVal];

	if (startedCharacter) {

		//NSLog(@"Started Character");
		if([layer count] < 1 || [[layer lastObject] getEndPosition].x < screenWidth - [[layer lastObject] getSize].width * interval)
		{
			//NSLog(@"Add object to Layer");

			float dx = baseSpeed * index;
			//float size = focusRadio * index * 10;
			float size = index * 25;
			//float pY = horizon - (index - 1) * focusRadio * angel * 15;
			float pY = horizon - (index - 1) * angel * 15;

			Character *ch = [[Character alloc] initWithChar:groundCharacter Size:size];
			[ch setColor:groundCharacterColor];
			[ch setOpacity:(ind/5.0) * 255];
			[ch setPositionX:(screenWidth + [ch getSize].width + index * 40) Y:pY];
			[ch setSpeedX:-dx Y:0];
			[ch addToScene:itemLayer];
			[layer addObject:ch];
		}
	}
	if([layer count] > 0 && [[layer objectAtIndex:0] getEndPosition].x < 0) {
		[[layer objectAtIndex:0] removeFromCurrentScene];
		[layer removeObjectAtIndex:0];
	}

	// Move the view angel
	if (leftAnimationTick > 0) {

		// Adjust the character position
		//angel += (nextAngel - angel) / leftAnimationTick;
		//float pY = horizon - (index - 1) * focusRadio * angel * 15;
		float pY = horizon - (index - 1) * angel * 15;
		for (int i = 0; i < [layer count]; i++) {
			Character *ch = [layer objectAtIndex:i];
			[ch setPositionX:[ch getPosition].x Y:pY];
		}
	}
}

-(void) setScreen:(ContainerLayer *)screen BackDrop:(ContainerLayer *)backdrop {

	itemLayer= screen;
	backdropLayer = backdrop;
}

-(void) gamePause {

	NSLog(@"Backbround pause");
	[itemLayer pauseSchedulerAndActions];
	[backdropLayer pauseSchedulerAndActions];
}

-(void) gameResume {

	[itemLayer resumeSchedulerAndActions];
	[backdropLayer resumeSchedulerAndActions];
}

-(void) setAnimationTick:(int)tick {

	nextAnimationTick = tick;
	leftAnimationTick = tick;
}

-(void) addToBackdrop:(CGRect) rect Color:(Color *) clr {
}

-(void) removeAllfromBackdrop {

}

-(void) addCharacter:(Character *)ch {

}

@end


text:
/* ArduinoIcon.h bitmap file for GLCD library              */
/* This header file is provided mainly for backward        */
/* compatibility with the ks0108 library.                  */
/*                                                         */
/* It also provides for a "default" Arduino icon which is  */
/* 64 by 64 pixels.                                        */

#ifndef ArduinoIcon_H
#define ArduinoIcon_H

#define ArduinoIcon ArduinoIcon64x64
#include "bitmaps/ArduinoIcon64x64.h"

#endif


text:
package com.nomad_mystic_fragmentedmeals.fragmentedmeals;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * A simple {@link Fragment} subclass.
 */
public class MealFragment extends Fragment {

    public static final String MEAL_NAME_KEY = "Meal Name";
    public static final String MEAL_PICTURE_KEY = "Meal Picture";
    private MealItem mCurrentMeal;

    interface OnAttachMealFragment {
        public void onAttachMealFragment(MealFragment fragment);
    }

    public MealFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(savedInstanceState != null) {
            int mealPicture = savedInstanceState.getInt(MEAL_PICTURE_KEY, 0);
            if(mealPicture != 0) {
                String mealName = savedInstanceState.getString(MEAL_NAME_KEY);
                mCurrentMeal = new MealItem(mealName, mealPicture);
            }
        }
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_meal, container, false);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if(activity instanceof OnAttachMealFragment) {
            ((OnAttachMealFragment) activity).onAttachMealFragment(this);
        }
    }

    public void onStart() {
        super.onStart();
        if(mCurrentMeal != null) {
            setMeal(mCurrentMeal);
        }
    }

    public void setMeal(MealItem item) {
        mCurrentMeal = item;
        if(getView() != null ) {
            TextView nameText = (TextView) getView().findViewById(R.id.meal_name);
            ImageView mealPicture = (ImageView) getView().findViewById(R.id.meal_picture);
            nameText.setText(item.getName());
            mealPicture.setImageResource(item.getPicture());
        }
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        if (mCurrentMeal != null) {
            savedInstanceState.putString(MEAL_NAME_KEY, mCurrentMeal.getName());
            savedInstanceState.putInt(MEAL_PICTURE_KEY, mCurrentMeal.getPicture());
        }
    }
}


text:
module SimpleAudioPlayer

  # Extend the controller and add the custom helper
  def self.included(base)
    base.extend(ClassMethods)
    base.helper SimpleAudioPlayerHelper
  end

  # Provides methods which should be available to the controller
  module ClassMethods

    def uses_simple_audio_player(options = {})
      # Extract the audio player config from the default before_filter options
      config = options.delete(:config) || {}

      # Init the simple audio player
      init_simple_audio_player = Proc.new do |i|
        i.instance_variable_set(:@simple_audio_player_config, config)
        i.instance_variable_set(:@uses_simple_audio_player, true)
      end

      before_filter(init_simple_audio_player, options)
    end

  end

end


text:
[![Build Status](https://travis-ci.org/derfalx/VirtualMachine.svg?branch=master)](https://travis-ci.org/derfalx/VirtualMachine)

This repository contains the code for my own implementation of a java virtual machine. I'm going to blog about why and how I am programming it, so take a look at my [Blog](https://codingfalx.de) (currently only german).

Intro: [[Einleitung] Entwicklung einer Java Virtual Machine](https://codingfalx.de/de_DE/entwicklung-einer-jvm/)

Part I: [[Teil 1] Entwicklung einer JVM – Grundlagen](https://codingfalx.de/teil-1-entwicklung-einer-jvm-grundlagen/)


text:
. <caret>target.bash

echo "target.bash"
echo 'target.bash'


text:
namespace mediapipe {

void VisualizeRegionFlowImpl(const RegionFlowFrame& region_flow_frame,
                             cv::Mat* output) {
  // Just draw a green line for each feature.
  for (const auto& region_flow : region_flow_frame.region_flow()) {
    cv::Scalar color(0, 255, 0);

    for (const auto& feature : region_flow.feature()) {
      cv::Point p1(static_cast<int>(feature.x() + 0.5f),
                   static_cast<int>(feature.y() + 0.5f));

      cv::Point p2(static_cast<int>(feature.x() + feature.dx() + 0.5f),
                   static_cast<int>(feature.y() + feature.dy() + 0.5f));

      cv::line(*output, p1, p2, color);
    }
  }
}

void VisualizeRegionFlow(const RegionFlowFrame& region_flow_frame,
                         cv::Mat* output) {
  CHECK(output);
  VisualizeRegionFlowImpl(region_flow_frame, output);
}

void VisualizeRegionFlowFeaturesImpl(const RegionFlowFeatureList& feature_list,
                                     const cv::Scalar& color,
                                     const cv::Scalar& outlier,
                                     bool irls_visualization, float scale_x,
                                     float scale_y, cv::Mat* output) {
  const float kLineScaleOneRows = 1080.0;
  const int line_size =
      std::max(std::min<int>(output->rows / kLineScaleOneRows, 4), 1);

  const float text_scale = std::max(output->rows, output->cols) * 3e-4;
  for (const auto& feature : feature_list.feature()) {
    Vector2_i v1 = FeatureIntLocation(feature);
    Vector2_i v2 = FeatureMatchIntLocation(feature);
    cv::Point p1(v1.x() * scale_x, v1.y() * scale_y);
    cv::Point p2(v2.x() * scale_x, v2.y() * scale_y);

    float alpha = 0;
    if (irls_visualization) {
      if (feature.irls_weight() < 0) {
        continue;
      }

      if (feature.irls_weight() == 0.0f) {
        // Ignored feature, draw as circle.
        cv::circle(*output, p1, 4.0 * line_size, outlier, 2 * line_size);
        continue;
      }

      // Scale irls_weight, such that error of one pixel equals alpha of 0.5
      // (evenly mix inlier and outlier color).
      alpha = std::min(1.0f, feature.irls_weight() * 0.5f);

    } else {
      const float feature_stdev_l1 =
          PatchDescriptorColorStdevL1(feature.feature_descriptor());
      if (feature_stdev_l1 >= 0.0f) {
        // Normalize w.r.t. maximum per channel standard deviation (128.0)
        // and scale (scale could be user-defined and was chosen based on some
        // test videos such that only very low textured features are colored
        // with outlier color).
        alpha = std::min(1.0f, feature_stdev_l1 / 128.f * 6.f);
      } else {
        alpha = 0.5;  // Dummy value indicating, descriptor is not present.
      }
    }

#ifdef __APPLE__
    cv::Scalar color_scaled(color.mul(alpha) + outlier.mul(1.0f - alpha));
#else
    cv::Scalar color_scaled(color * alpha + outlier * (1.0f - alpha));
#endif
    cv::line(*output, p1, p2, color_scaled, line_size, cv::LINE_AA);
    cv::circle(*output, p1, 2.0 * line_size, color_scaled, line_size);

    if (feature.has_label()) {
      cv::putText(*output, absl::StrCat(" ", feature.label()), p1,
                  cv::FONT_HERSHEY_SIMPLEX, text_scale, color_scaled,
                  3.0 * text_scale, cv::LINE_AA);
    }
  }
}

void VisualizeRegionFlowFeatures(const RegionFlowFeatureList& feature_list,
                                 const cv::Scalar& color,
                                 const cv::Scalar& outlier,
                                 bool irls_visualization, float scale_x,
                                 float scale_y, cv::Mat* output) {
  CHECK(output);
  VisualizeRegionFlowFeaturesImpl(feature_list, color, outlier,
                                  irls_visualization, scale_x, scale_y, output);
}

void VisualizeLongFeatureStreamImpl(const LongFeatureStream& stream,
                                    const cv::Scalar& color,
                                    const cv::Scalar& outlier,
                                    int min_track_length,
                                    int max_points_per_track, float scale_x,
                                    float scale_y, cv::Mat* output) {
  const float text_scale = std::max(output->cols, output->rows) * 3e-4;
  for (const auto& track : stream) {
    std::vector<Vector2_f> pts;
    std::vector<float> irls_weights;
    stream.FlattenTrack(track.second, &pts, &irls_weights, nullptr);

    if (min_track_length > 0 && pts.size() < min_track_length) {
      continue;
    }
    CHECK_GT(pts.size(), 1);  // Should have at least two points per track.

    // Tracks are ordered with oldest point first, most recent one last.
    const int start_k =
        max_points_per_track > 0
            ? std::max<int>(0, pts.size() - max_points_per_track)
            : 0;
    // Draw points in last to first order.
    for (int k = start_k; k < pts.size(); ++k) {
      cv::Point p1(pts[k].x() * scale_x, pts[k].y() * scale_y);

      if (irls_weights[k] == 0.0f) {
        // Ignored feature, draw as circle.
        cv::circle(*output, p1, 4.0, outlier, 2);
        continue;
      }

      const float alpha = std::min(1.0f, irls_weights[k] * 0.5f);
#ifdef __APPLE__
      cv::Scalar color_scaled(color.mul(alpha) + outlier.mul(1.0f - alpha));
#else
      cv::Scalar color_scaled(color * alpha + outlier * (1.0f - alpha));
#endif

      if (k < pts.size() - 1) {
        // Draw line connecting points.
        cv::Point p2(pts[k + 1].x() * scale_x, pts[k + 1].y() * scale_y);
        cv::line(*output, p1, p2, color_scaled, 1.0, cv::LINE_AA);
      }
      if (k + 1 == pts.size()) {  // Last iteration.
        cv::circle(*output, p1, 2.0, color_scaled, 1.0);

        const RegionFlowFeature& latest_feature = track.second.back();
        if (latest_feature.has_label()) {
          cv::putText(*output, absl::StrCat(" ", latest_feature.label()), p1,
                      cv::FONT_HERSHEY_SIMPLEX, text_scale, color_scaled,
                      3 * text_scale, cv::LINE_AA);
        }
      }
    }
  }
}

void VisualizeLongFeatureStream(const LongFeatureStream& stream,
                                const cv::Scalar& color,
                                const cv::Scalar& outlier, int min_track_length,
                                int max_points_per_track, float scale_x,
                                float scale_y, cv::Mat* output) {
  CHECK(output);
  VisualizeLongFeatureStreamImpl(stream, color, outlier, min_track_length,

                                 max_points_per_track, scale_x, scale_y,
                                 output);
}

}  // namespace mediapipe


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="circles_multiple">
        <item quantity="other">%1$s cirkler</item>
        <item quantity="one">%1$s cirkler</item>
    </plurals>
    <plurals name="content_description_rated">
        <item quantity="other">Din bedømmelse: %1$s stjerner</item>
        <item quantity="one">Din bedømmelse: %1$s stjerner</item>
    </plurals>
    <plurals name="content_description_review_histogram_review_count">
        <item quantity="other">%1$d anmeldelser</item>
        <item quantity="one">%1$d anmeldelser</item>
    </plurals>
    <plurals name="content_description_review_histogram_row">
        <item quantity="other">%1$d anmeldelser for stjernebedømmelsen %2$d</item>
        <item quantity="one">%1$d anmeldelser for stjernebedømmelsen %2$d</item>
    </plurals>
    <plurals name="content_description_review_tip_review_count">
        <item quantity="other">%1$s fra %2$s anmeldelser</item>
        <item quantity="one">%1$s fra %2$s anmeldelser</item>
    </plurals>
    <plurals name="my_apps_selected">
        <item quantity="other">Der er valgt %1$d</item>
        <item quantity="one">Der er valgt %1$d</item>
    </plurals>
    <plurals name="notification_need_approval_message">
        <item quantity="other">%1$d opdateringer skal godkendes</item>
        <item quantity="one">%1$d opdateringer skal godkendes</item>
    </plurals>
    <plurals name="notification_new_updates_available_message">
        <item quantity="other">%1$d nye opdateringer</item>
        <item quantity="one">%1$d nye opdateringer</item>
    </plurals>
    <plurals name="notification_outstanding_updates_message">
        <item quantity="other">%1$d tilgængelige opdateringer</item>
        <item quantity="one">%1$d tilgængelige opdateringer</item>
    </plurals>
    <plurals name="notification_update_all_button_text">
        <item quantity="other">Opdater alle</item>
        <item quantity="one">Opdater alle</item>
    </plurals>
    <plurals name="notification_update_success_message">
        <item quantity="other">%1$d applikationer blev opdateret</item>
        <item quantity="one">%1$d applikationer blev opdateret</item>
    </plurals>
    <plurals name="review_author_stars">
        <item quantity="other">&lt;b>%1$s&lt;/b> %2$s stjerner</item>
        <item quantity="one">&lt;b>%1$s&lt;/b> %2$s stjerner</item>
    </plurals>
    <plurals name="review_author_stars_title">
        <item quantity="other">&lt;b>%1$s&lt;/b> %2$s stjerner – %3$s</item>
        <item quantity="one">&lt;b>%1$s&lt;/b> %2$s stjerner – %3$s</item>
    </plurals>
    <plurals name="review_author_stars_title_comment">
        <item quantity="other">&lt;b>%1$s&lt;/b> %2$s stjerner – %3$s – %4$s</item>
        <item quantity="one">&lt;b>%1$s&lt;/b> %2$s stjerner – %3$s – %4$s</item>
    </plurals>
    <plurals name="review_feedback_helpful_icon_description">
        <item quantity="other">%1$d brugere fandt denne anmeldelse nyttig. Markér kommentaren som nyttig</item>
        <item quantity="one">%1$d brugere fandt denne anmeldelse nyttig. Markér kommentaren som nyttig</item>
    </plurals>
    <plurals name="review_feedback_unmark_helpful_icon_description">
        <item quantity="other">%1$d brugere fandt denne anmeldelse nyttig. Fjern markeringen af kommentaren som nyttig</item>
        <item quantity="one">%1$d brugere fandt denne anmeldelse nyttig. Fjern markeringen af kommentaren som nyttig</item>
    </plurals>
    <plurals name="review_just_stars">
        <item quantity="other">Har givet &lt;b>%1$s stjerner&lt;/b></item>
        <item quantity="one">Har givet &lt;b>%1$s stjerner&lt;/b></item>
    </plurals>
    <plurals name="review_snippet_count">
        <item quantity="other">i %1$s anmeldelser</item>
        <item quantity="one">i %1$s anmeldelse</item>
    </plurals>
    <plurals name="review_stars_title">
        <item quantity="other">&lt;b>%1$s stjerner&lt;/b> %2$s</item>
        <item quantity="one">&lt;b>%1$s stjerner&lt;/b> %2$s</item>
    </plurals>
    <plurals name="setup_wizard_apps_loading_error_menu_title">
        <item quantity="other">Elementerne kan ikke indlæses. Prøv en anden sikkerhedskopi.</item>
        <item quantity="one">Elementerne kan ikke indlæses. Prøv en anden sikkerhedskopi.</item>
    </plurals>
    <plurals name="setup_wizard_device_last_used_message">
        <item quantity="other">Sidst brugt for %1$d dage siden</item>
        <item quantity="one">Sidst brugt for %1$d dage siden</item>
    </plurals>
    <plurals name="setup_wizard_selected_apps">
        <item quantity="other">Valgte apps</item>
        <item quantity="one">Valgte apps</item>
    </plurals>
    <plurals name="stars_without_numbers">
        <item quantity="other">stjerner</item>
        <item quantity="one">stjerner</item>
    </plurals>
    <plurals name="tip_header_subtitle">
        <item quantity="other">%1$s personer siger dette</item>
        <item quantity="one">%1$s personer siger dette</item>
    </plurals>
</resources>


text:
<?php namespace FOO; ?>

<div style="<?= $font ?>">
<form method="get" action="<?= $base_url ?>/alerts_redir.php">
  <?php require(__DIR__ . '/modules/alerts.php'); ?>

    <button type="submit" style="<?= $action_button_style ?>">Compare alerts</button>

</form>


text:
//-*-c++-*-
//=======================================================================
// Copyright 1997-2001 University of Notre Dame.
// Authors: Lie-Quan Lee
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

/*
  This file is to demo how to use minimum_degree_ordering algorithm.

  Important Note: This implementation requires the BGL graph to be
  directed.  Therefore, nonzero entry (i, j) in a symmetrical matrix
  A coresponds to two directed edges (i->j and j->i).

  The bcsstk01.rsa is an example graph in Harwell-Boeing format,
  and bcsstk01 is the ordering produced by Liu's MMD implementation.
  Link this file with iohb.c to get the harwell-boeing I/O functions.
  To run this example, type:

  ./minimum_degree_ordering bcsstk01.rsa bcsstk01

*/

#include <boost/config.hpp>
#include <fstream>
#include <iostream>
#include "boost/graph/adjacency_list.hpp"
#include "boost/graph/graph_utility.hpp"
#include "boost/graph/minimum_degree_ordering.hpp"

void terminate(const char* msg)
{
    std::cerr << msg << std::endl;
    abort();
}

// copy and modify from mtl harwell boeing stream
struct harwell_boeing
{
    harwell_boeing(char* filename)
    {
        int Nrhs;
        char* Type;
        Type = new char[4];
        isComplex = false;
        // Never called:
        // readHB_info(filename, &M, &N, &nonzeros, &Type, &Nrhs);
        colptr = (int*)malloc((N + 1) * sizeof(int));
        if (colptr == NULL)
            terminate("Insufficient memory for colptr.\n");
        rowind = (int*)malloc(nonzeros * sizeof(int));
        if (rowind == NULL)
            terminate("Insufficient memory for rowind.\n");

        if (Type[0] == 'C')
        {
            isComplex = true;
            val = (double*)malloc(nonzeros * sizeof(double) * 2);
            if (val == NULL)
                terminate("Insufficient memory for val.\n");
        }
        else
        {
            if (Type[0] != 'P')
            {
                val = (double*)malloc(nonzeros * sizeof(double));
                if (val == NULL)
                    terminate("Insufficient memory for val.\n");
            }
        }
        // Never called:
        // readHB_mat_double(filename, colptr, rowind, val);

        cnt = 0;
        col = 0;
        delete[] Type;
    }

    ~harwell_boeing()
    {
        free(colptr);
        free(rowind);
        free(val);
    }

    inline int nrows() const { return M; }

    int cnt;
    int col;
    int* colptr;
    bool isComplex;
    int M;
    int N;
    int nonzeros;
    int* rowind;
    double* val;
};

int main(int argc, char* argv[])
{
    using namespace std;
    using namespace boost;

    if (argc < 2)
    {
        cout << argv[0] << " HB file" << endl;
        return -1;
    }

    int delta = 0;

    if (argc >= 4)
        delta = atoi(argv[3]);

    harwell_boeing hbs(argv[1]);

    // must be BGL directed graph now
    typedef adjacency_list< vecS, vecS, directedS > Graph;

    int n = hbs.nrows();

    cout << "n is " << n << endl;

    Graph G(n);

    int num_edge = 0;

    for (int i = 0; i < n; ++i)
        for (int j = hbs.colptr[i]; j < hbs.colptr[i + 1]; ++j)
            if ((hbs.rowind[j - 1] - 1) > i)
            {
                add_edge(hbs.rowind[j - 1] - 1, i, G);
                add_edge(i, hbs.rowind[j - 1] - 1, G);
                num_edge++;
            }

    cout << "number of off-diagnal elements: " << num_edge << endl;

    typedef std::vector< int > Vector;

    Vector inverse_perm(n, 0);
    Vector perm(n, 0);

    Vector supernode_sizes(n, 1); // init has to be 1

    boost::property_map< Graph, vertex_index_t >::type id
        = get(vertex_index, G);

    Vector degree(n, 0);

    minimum_degree_ordering(G,
        make_iterator_property_map(&degree[0], id, degree[0]), &inverse_perm[0],
        &perm[0],
        make_iterator_property_map(&supernode_sizes[0], id, supernode_sizes[0]),
        delta, id);

    if (argc >= 3)
    {
        ifstream input(argv[2]);
        if (input.fail())
        {
            cout << argv[3] << " is failed to open!. " << endl;
            return -1;
        }
        int comp;
        bool is_correct = true;
        int i;
        for (i = 0; i < n; i++)
        {
            input >> comp;
            if (comp != inverse_perm[i] + 1)
            {
                cout << "at i= " << i << ": " << comp
                     << " ***is NOT EQUAL to*** " << inverse_perm[i] + 1
                     << endl;
                is_correct = false;
            }
        }
        for (i = 0; i < n; i++)
        {
            input >> comp;
            if (comp != perm[i] + 1)
            {
                cout << "at i= " << i << ": " << comp
                     << " ***is NOT EQUAL to*** " << perm[i] + 1 << endl;
                is_correct = false;
            }
        }
        if (is_correct)
            cout << "Permutation and inverse permutation are correct. " << endl;
        else
            cout << "WARNING -- Permutation or inverse permutation is not the "
                 << "same ones generated by Liu's " << endl;
    }
    return 0;
}


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.admanager.jaxws.v202211;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for TeamAccessType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="TeamAccessType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="NONE"/>
 *     <enumeration value="READ_ONLY"/>
 *     <enumeration value="READ_WRITE"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "TeamAccessType")
@XmlEnum
public enum TeamAccessType {

    /**
     *
     *                 The level of access in which team members cannot view or edit a team's
     *                 orders.
     *
     *
     */
    NONE,

    /**
     *
     *                 The level of access in which team members can only view a team's orders.
     *
     *
     */
    READ_ONLY,

    /**
     *
     *                 The level of access in which team members can view and edit a team's
     *                 orders.
     *
     *
     */
    READ_WRITE;

    public String value() {
        return name();
    }

    public static TeamAccessType fromValue(String v) {
        return valueOf(v);
    }

}


text:
bitcoin-seeder
==============

Bitcoin-seeder is a crawler for the Bitcoin Cash network, which exposes a list
of reliable nodes via a built-in DNS server. It is derived from Pieter Wuille's
bitcoin-seeder, modified for use on the Bitcoin Cash network.

Features:
* regularly revisits known nodes to check their availability
* bans nodes after enough failures, or bad behaviour
* uses the Cash Magic when establishing connections.
* keeps statistics over (exponential) windows of 2 hours, 8 hours,
  1 day and 1 week, to base decisions on.
* very low memory (a few tens of megabytes) and cpu requirements.
* crawlers run in parallel (by default 24 threads simultaneously).

REQUIREMENTS
------------

$ sudo apt-get install build-essential libboost-all-dev libssl-dev

USAGE
-----

Assuming you want to run a dns seed on dnsseed.example.com, you will
need an authoritative NS record in example.com's domain record, pointing
to for example vps.example.com:

$ dig -t NS dnsseed.example.com

;; ANSWER SECTION
dnsseed.example.com.   86400    IN      NS     vps.example.com.

On the system vps.example.com, you can now run dnsseed:

./bitcoin-seeder -host=dnsseed.example.com -ns=vps.example.com

If you want the DNS server to report SOA records, please provide an
e-mail address (with the @ part replaced by .) using -mbox.

RUNNING AS NON-ROOT
-------------------

Typically, you'll need root privileges to listen to port 53 (name service).

One solution is using an iptables rule (Linux only) to redirect it to
a non-privileged port:

$ iptables -t nat -A PREROUTING -p udp --dport 53 -j REDIRECT --to-port 5353

If properly configured, this will allow you to run dnsseed in userspace, using
the -port=5353 option.

Generate Seed Lists
-------------------

Bitcoin-seeder is also be used to generate the seed lists that are compiled
into every Bitcoin ABC release. It produces the `dnsseed.dump` files that are
used as inputs to the scripts in [contrib/seeds](/contrib/seeds) to generate
the seed lists. To generate seed lists, the seeder should be run continuously
for 30 days or more.


text:
package es.weso.utils

import com.hp.hpl.jena.rdf.model.LiteralRequiredException
import com.hp.hpl.jena.rdf.model.Model
import com.hp.hpl.jena.rdf.model.ModelFactory
import com.hp.hpl.jena.rdf.model.Resource
import com.hp.hpl.jena.rdf.model.ResourceRequiredException
import com.hp.hpl.jena.rdf.model.Statement
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import com.hp.hpl.jena.query.Query
import com.hp.hpl.jena.query.QueryExecutionFactory
import com.hp.hpl.jena.query.QueryFactory
import java.io.StringWriter
import com.hp.hpl.jena.rdf.model.RDFNode
import com.hp.hpl.jena.rdf.model.Property
import java.net.URI
import java.net.URL
import java.io.InputStream
import java.io.FileOutputStream
import org.apache.jena.atlas.AtlasException
import org.apache.jena.riot.RiotException
import com.hp.hpl.jena.query.ResultSet
import com.hp.hpl.jena.rdf.model.Literal
import es.weso.computex.PREFIXES
import com.hp.hpl.jena.rdf.model.ResourceFactory
import scala.collection.JavaConverters._
import java.io.FileNotFoundException
import scala.io.Source
import com.hp.hpl.jena.rdf.model.SimpleSelector
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype
import org.slf4j.LoggerFactory

sealed abstract class ParserReport[+A,+B]

final case class Parsed[A](info:A)
	extends ParserReport[A,Nothing]

final case class NotParsed[B](error: B)
	extends ParserReport[Nothing,B]

object JenaUtils {

  var bNodeCount    = 0
  val time = compat.Platform.currentTime
  val logger 		= LoggerFactory.getLogger("Application")

  lazy val RdfXML 		= "RDF/XML"
  lazy val RdfXMLAbbr 	= "RDF/XML-ABBREV"
  lazy val NTriple 		= "N-TRIPLE"
  lazy val Turtle 		= "TURTLE"
  lazy val TTL 			= "TTL"
  lazy val N3 			= "N3"

  // In Jena selectors, null represents any node
  lazy val any : RDFNode = null

  def emptyModel = ModelFactory.createDefaultModel

  def extractModel(resource: Resource, model: Model): Model = {
    val nModel = ModelFactory.createDefaultModel()

    def inner(resource: Resource): Model = {
      val iterator2 = model.listStatements(resource, null, null)

      while (iterator2.hasNext()) {
        val stmt = iterator2.nextStatement();
        val subject = stmt.getSubject();
        val predicate = stmt.getPredicate();
        val objec = stmt.getObject();
        nModel.add(subject, predicate, objec)
        if (objec.isAnon) {
          inner(objec.asResource())
        }
      }
      nModel
    }
    inner(resource)
  }

  def statementAsString(statement: Statement, model: Model, preffix: Boolean): String = {
    val resource = try {
      val uri = statement.getResource.toString
      val preffixUri = statement.getResource.getNameSpace
      val preffixNS = model.getNsURIPrefix(statement.getResource.getNameSpace)
      val suffix = statement.getResource.getLocalName
      if (preffix && preffixUri != null)
        preffixNS + ":" + suffix
      else uri
    } catch {
      case e: ResourceRequiredException => null
    }
    if (resource == null) {
      try {
        if (preffix)
          statement.getLiteral().getValue().toString
        else statement.getLiteral().toString
      } catch {
        case e: LiteralRequiredException => resource
      }
    } else resource
  }

  def dereferenceURI( uri: String ) : InputStream = {
    val url = new URL(uri)
    val urlCon = url.openConnection()
    urlCon.setConnectTimeout(4000)
    urlCon.setReadTimeout(2000)
    urlCon.getInputStream()
  }

  def parseFromURI(uri: String,
      base: String = "",
      syntax: String = Turtle) : Model = {
    uri2Model(uri,base,syntax) match {
      case Parsed(model) => model
      case NotParsed(err) =>
        throw new Exception(err)
    }
  }

  def parseFromString(
      content: String,
      base: String = "",
      syntax: String = Turtle) : Model = {
    str2Model(content,base,syntax) match {
      case Parsed(model) => model
      case NotParsed(err) =>
        throw new Exception("Cannot parse from string: " + content + ". Error: " + err + ". Syntax: " + syntax)
    }
  }

  def modelFromPath(path: String,
            		base: String = "",
            		syntax: String = Turtle): Model = {
    val model = ModelFactory.createDefaultModel()
    val inputStream = getClass.getClassLoader().getResourceAsStream(path)
    if (inputStream == null)
        throw new FileNotFoundException("File especified does not exist")
    model.read(inputStream,base,syntax)
  }

  def uri2Model(
      uriName: String,
      base: String = "",
      syntax: String = Turtle) : ParserReport[Model,String] = {
    try {
      val model = ModelFactory.createDefaultModel()
      Parsed(model.read(dereferenceURI(uriName),base,syntax))
    } catch {
      case e: AtlasException =>
        NotParsed("Error parsing URI " + uriName + " with syntax " + syntax + ".\n AtlasException: " + e.toString())
      case e: RiotException =>
        NotParsed("Exception parsing URI " + uriName + " with syntax " + syntax + ".\n RIOT Exception: " + e.toString())
      case e : Exception =>
        NotParsed("Exception parsing URI " + uriName + " with syntax " + syntax + ".\n Exception: " + e.toString())
    }
  }

  /**
   * Returns a RDF model after parsing a String
   */
  def str2Model(
      str: String,
	  base: String = "",
	  syntax: String = Turtle) : ParserReport[Model,String] = {
    try {
      val model = ModelFactory.createDefaultModel()
      val stream = new ByteArrayInputStream(str.getBytes("UTF-8"))
      Parsed(model.read(stream,base,syntax))
    } catch {
      case e@(_: AtlasException | _: RiotException) =>
        NotParsed("Bad formed with syntax " + syntax + ". " + e.getLocalizedMessage())
      case e : Exception =>
        NotParsed("Exception parsing from String " + str +
            " with syntax " + syntax + ". " + e.getLocalizedMessage())
    }
  }

  /**
   * Returns a RDF model after parsing an InputStream
   */
  def parseInputStream(
      stream: 	InputStream,
	  base: 	String = "",
	  syntax: 	String = Turtle) : ParserReport[Model,String] = {
    try {
      val model = ModelFactory.createDefaultModel()
      Parsed(model.read(stream,base,syntax))
    } catch {
      case e@(_: AtlasException | _: RiotException) =>
        NotParsed("Bad formed with syntax " + syntax + ". " + e.getLocalizedMessage())
      case e : Exception =>
        NotParsed("Exception parsing " +
            " with syntax " + syntax + ". " + e.getLocalizedMessage())
    }
  }

  def getLiteral(
       r : RDFNode,
       property: Property) : String = {
    if (r.isResource()) {
        val res = r.asResource
    	val stmt = res.getRequiredProperty(property)
    	stmt match {
    	  case null =>
    	    throw new Exception("getName: " + res + " doesn't have value for property " + property + ".\n" +
    	    					showResource(r.asResource) )
    	  case _ =>
    	    if (stmt.getObject.isLiteral) stmt.getObject.asLiteral.getString
    	    else
    	      throw new Exception("getName: " + stmt.getObject + " is not a literal")
    	}
    }
    else
      throw new Exception("getName: " + r + "is not a resource")
  }

  /*
   *
   */
  def getURI(r: RDFNode) : URI = {
    if (r.isResource) {
      new URI(r.asResource.getURI)
    }
    else
       throw new Exception("getURI: Node " + r + " is not a resource")
  }

  /*
   * If there is a triple <r,p,u> and u is a URI, returns u
   * @param r RDFNode
   * @param property
   */
  def getObjectURI(
		  r: RDFNode,
		  p: Property
	) : URI = {
    if (r.isResource()) {
    	val resUri = r.asResource().getPropertyResourceValue(p)
    	resUri match {
    	  case null =>
    	    throw new Exception("getURI: " + resUri + " doesn't have value for property " + p + ".\n" + showResource(r.asResource) )
    	  case _ =>
    	    getURI(resUri)
        }
     } else
       throw new Exception("getURI: Node " + r + " is not a resource")
  }

  /**
   * Shows infomation about a resource (list all the statements)
   */
  def showResource(resource: Resource) : String = {
   val sb = new StringBuilder
   val iter = resource.listProperties()
   sb ++= ("Infor about: " + resource + "\n")
   while (iter.hasNext) {
     val st = iter.next
     sb ++= (st.toString + "\n")
   }
   sb.toString
  }

  /*
   * Parse a string to obtain a query
   */
  def parseQuery(
      str: String
      ) : Option[Query] = {
   try {
     val query = QueryFactory.create(str)
     Some(query)
   } catch {
   	 case e: Exception => None
   }
  }

  def querySelectModel(query: Query, model:Model) : ResultSet = {
    val qexec = QueryExecutionFactory.create(query, model)
    qexec.execSelect()
  }

  def querySelectModel(queryStr: String, model:Model) : ResultSet = {
    val query = QueryFactory.create(queryStr)
    querySelectModel(query, model)
  }

  def queryConstructModel(queryStr: String, model:Model) : Model = {
    val query = QueryFactory.create(queryStr)
    queryConstructModel(query, model)
  }

  def queryConstructModel(query: Query, model:Model) : Model = {
	val resultModel = ModelFactory.createDefaultModel
    val qexec = QueryExecutionFactory.create(query, model)
    qexec.execConstruct
  }

  /*
   * Convert a model to a String
   */
  def model2Str(
		  model: Model,
		  syntax: String = Turtle) : String = {
    val strWriter = new StringWriter
    model.write(strWriter,syntax)
    strWriter.toString
  }

  /*
   * Write a model to a file
   */
  def model2File(
		  model: Model,
		  fileName : String,
		  syntax: String = Turtle) : Unit = {
    model.write(new FileOutputStream(fileName),syntax)
  }

 def getValuesOfType(r: Resource, m: Model) : Set[Resource] = {
  m.listResourcesWithProperty(PREFIXES.rdf_type,r).toSet.asScala.toSet
 }

 def findSubject(m: Model, obj:Resource, p: Property) : RDFNode = {
   val selector : SimpleSelector = new SimpleSelector(null,p,obj)
   val iter = m.listStatements(selector)
   if (iter.hasNext) {
     val node = iter.next.getSubject
     if (!iter.hasNext) node
     else throw
    	 	new Exception("findSubject: Resource " + obj + " has more than one subject for property " + p)
   }
   else
     throw new Exception("findSubject: Resource " + obj + " does not have subject for property " + p)
 }

 def findSubject_asResource(m: Model, obj:Resource, p : Property) : Resource = {
   val v = findSubject(m,obj,p)
   if (v.isResource) v.asResource
   else {
     throw new Exception("findSubject_asResource: Object " + obj + " has value " + v + " for property " + p + " which is not a resource")
   }
 }

 def hasProperty(m: Model, r:Resource, p: Property) : Boolean = {
   val iter = m.listStatements(r,p,any)
   iter.hasNext
 }

 /**
  * TODO: rename these methods to "findObject"
  */
 def findProperty(m: Model, r:Resource, p: Property) : RDFNode = {
   val iter = m.listStatements(r,p,any)
   if (iter.hasNext) {
     val node = iter.next.getObject
     if (!iter.hasNext) node
     else {
       val msg="findProperty: Resource " + r + " has more than one value for property " + p
       throw new Exception(msg)
//       logger.error(msg)
//       node
     }
   }
   else
     throw new Exception("findProperty: Resource " + r + " does not have value for property " + p)
 }

 def findProperty_asResource(m: Model, r:Resource, p : Property) : Resource = {
   val v = findProperty(m,r,p)
   if (v.isResource) v.asResource
   else {
     throw new Exception("findProperty_asResource: Resource " + r + " has value " + v + " for property " + p + " which is not a resource")
   }
 }

 def findProperty_asLiteral(m: Model, r:Resource, p : Property) : Literal = {
   val v = findProperty(m,r,p)
   if (v.isLiteral) v.asLiteral
   else {
     throw new Exception("findProperty_asLiteral: Resource " + r + " has value " + v + " for property " + p + " which is not a literal")
   }
 }

 def readFileFromPath(path: String): String = {
      val inputStream = getClass.getClassLoader().getResourceAsStream(path)
      if (inputStream == null)
        throw new FileNotFoundException("File especified does not exist")
      Source.fromInputStream(inputStream).getLines.mkString("\n")
 }

  val literalTrue				=
    ResourceFactory.createTypedLiteral("true",XSDDatatype.XSDboolean)

  def literalInt(i : Int) 		=
    ResourceFactory.createTypedLiteral(new Integer(i))

  def literalInteger(i : Integer) 		=
    ResourceFactory.createTypedLiteral(i.toString,XSDDatatype.XSDinteger)
  def literalFloat(n : Float) 	=
    ResourceFactory.createTypedLiteral(n.toString,XSDDatatype.XSDfloat)
  def literalDouble(n : Double) 	=
    ResourceFactory.createTypedLiteral(n.toString,XSDDatatype.XSDdouble)

  def literal(name: String) 	=
    ResourceFactory.createPlainLiteral(name)

  def newResourceNoBlankNode(m: Model, base: String) : Resource = {
    bNodeCount = bNodeCount + 1
    m.createResource(base + time + "_" + bNodeCount)
  }

}


text:
typedef enum {
	ATARI_UP = 0x01,
	ATARI_DOWN = 0x08,
	ATARI_LEFT = 0x02,
	ATARI_RIGHT = 0x04,
	ATARI_BUTT_X = 0x80,
	ATARI_BUTT_Y = 0x10,
	ATARI_BUTT_A = 0x40,
	ATARI_BUTT_B = 0x20,
} ATARI_ENUMS;

@interface AtariDuoGamePad : NSObject <NSStreamDelegate, NSCopying>

// !! MUST BE RUN ON MAIN THREAD !!
// This is probably what you want to use in your main game loop
//  - checks for new data (doesn't wait for runloop check)
//  - if there is new data it runs appropriate handlers before returning
//  - returns the state of the gamepad
- (uint8_t)pollCurrentState;

// The handler is run on the main thread whenever a new state is detected.
// This makes it good for detecting combos and codes
//   New states are detected:
//    - when a runloop event happens
//    - when the current state is polled
@property (nonatomic, strong) void (^handler)(uint8_t state);

// Tells you if the gamepad is there or not
@property (nonatomic, readonly) BOOL isConnected;

@end


text: a website for cramming information into your head fast


text:
CppSharp is a tool and set of libraries which facilitates the usage of native C/C++ code
with the .NET ecosystem.

It consumes C/C++ header and library files and generates the
necessary glue code to surface the native API as a managed API. Such an API can be
used to consume an existing native library in your managed code or add
managed scripting support to a native codebase.

The supported target languages at present are C# and C++/CLI.

It can also be used as a library to parse native code into a syntax tree with a
rich declaration and type information model.

## Releases/Build Status

| NuGet Packages            | Continuous Integration    |
|---------------------------|---------------------------|
| [![NuGet](https://img.shields.io/nuget/v/CppSharp.svg)](https://www.nuget.org/packages/CppSharp/) | [![GitHub-actions](https://github.com/mono/CppSharp/workflows/CI/badge.svg)](https://github.com/mono/CppSharp/actions?query=workflow%3ACI)

1. [Libraries](#libraries)
2. [Documentation](#documentation)
3. [Community](#community)
4. [Support](#support)
5. [Users](#users)

## Libraries

### AST

Mirrors the Clang's C/C++ AST and type system classes in C# APIs.

Check out [_Clang's AST introduction docs_](http://clang.llvm.org/docs/IntroductionToTheClangAST.html) for more details about its architecture.

 * C++ declarations
 * C++ statements / expressions
 * C++ types
 * Class object layout
 * Declaration visitors
 * Type visitors

### Parser

Provides APIs for parsing of C/C++ source code into a syntax tree.

* Parsing of C/C++ source code
* Parsing of libraries archives symbols
* Parsing of shared libraries symbols
* Based on the very accurate Clang C++ parser.

### Generator

Generates the glue binding code from a syntax tree of the native code.

 * Multiple backends: C++/CLI and C# (P/Invoke)
 * Multiple ABIs: Itanium, MS, ARM, iOS
 * Multiple platforms: Windows, OS X and Linux
 * Multiple runtimes: .NET and Mono
 * C++ virtual methods overriding from managed code
 * C++ multiple inheritance by translating to C# interfaces
 * C++ std::string
 * C++ default parameter values
 * C/C++ semantic comments (Doxygen) to C# comments
 * Extensible bindings semantics via user passes and type mapping

## Documentation

Please see the following resources for more information:

[Getting Started](docs/GettingStarted.md)

[User's Manual](docs/UsersManual.md)

[Developer's Manual](docs/DevManual.md)

## Community

Feel free to open up issues on Github for any problems you find.

You can also join us at our [#managed-interop](https://gitter.im/managed-interop) Gitter discussion channel.

## Support

For building wrappers and priority support please write to cppsharp@protonmail.com.
Alternatively, you may post bounties at https://www.bountysource.com/.

## Users

CppSharp is used by the following projects:

[QtSharp](https://gitlab.com/ddobrev/QtSharp)

[MonoGame](https://github.com/mono/MonoGame)

[LLDBSharp](https://github.com/tritao/LLDBSharp)

[Xamarin](http://xamarin.com/)

[FFMPEG.net](https://github.com/crazyender/FFMPEG.net)

[FFmpeg bindings](https://github.com/InitialForce/FFmpeg_bindings)

[Tizen bindings](https://github.com/kitsilanosoftware/CppSharpTizen)

[libgd bindings](https://github.com/imazen/deprecated-gd-bindings-generator-old)

[ChakraSharp](https://github.com/baristalabs/ChakraSharp)

[FFmpeg.AutoGen](https://github.com/Ruslan-B/FFmpeg.AutoGen)

[GLFW3.NET](https://github.com/realvictorprm/GLFW3.NET)

Please feel free to send us a pull request adding your own projects to the list above.


text:
import * as React from 'react';
import TextField from '@material-ui/core/TextField';

{
  // https://github.com/mui-org/material-ui/issues/12999
  const defaulted = (
    <TextField InputProps={{ classes: { inputTypeSearch: 'search-input', input: 'input' } }} />
  );
  const standard = (
    <TextField variant="standard" InputProps={{ classes: { inputTypeSearch: 'search-input' } }} />
  );
  const standardOutlinedClassname = (
    <TextField
      variant="standard"
      InputProps={
        {
          // notchedOutline is only used with variant "outlined"
          // FIXME this no longer generates an error in TS 3.2, see https://github.com/Microsoft/TypeScript/issues/28926
          // classes: { inputTypeSearch: 'search-input', notchedOutline: 'notched-outline' }, // $ExpectError
        }
      }
    />
  );

  const filled = (
    <TextField
      variant="filled"
      InputProps={{ classes: { inputAdornedStart: 'adorned-start' } }}
      onChange={event => {
        // type inference for event still works?
        const value = event.target.value; // $ExpectType string
      }}
    />
  );

  const outlined = (
    <TextField variant="outlined" InputProps={{ classes: { notchedOutline: 'notched-outline' } }} />
  );
}


text:
package org.littlewings.javaee7.beanvalidation

import scala.annotation.meta.field

import javax.validation.constraints.{Min, NotNull, Size}

case class CaseBook(
  @(NotNull @field)
  @(Size @field)(min = 14, max = 14)
  isbn: String,

  @(NotNull @field)
  title: String,

  @(Min @field)(1)
  price: Int
)


text:
"""Enables handy interaction with arandr for display management.  Left-clicking
will execute arandr for interactive display management.  Right-clicking will
bring up a context- and state-sensitive menu that will allow you to switch to a
saved screen layout as well as toggle on/off individual connected displays.

Parameters:
    * No configuration parameters

Requires the following python modules:
    * tkinter

Requires the following executable:
    * arandr
    * xrandr

contributed by `zerorust <https://github.com/zerorust>`_ - many thanks!
"""

import fnmatch
from functools import partial
import logging
import os
import re

import core.module
import core.widget
import core.input
import core.decorators
from util import popup
from util.cli import execute

log = logging.getLogger(__name__)

__screenlayout_dir__ = os.path.expanduser("~/.screenlayout")

class Module(core.module.Module):
    @core.decorators.never
    def __init__(self, config, theme):
        super().__init__(config, theme, core.widget.Widget(''))

        self.manager = self.parameter("manager", "arandr")
        self.toggle_cmd = "xrandr"
        core.input.register(
            self,
            button=core.input.LEFT_MOUSE,
            cmd=self.popup,
        )

        core.input.register(self, button=core.input.RIGHT_MOUSE,
                            cmd=self.popup)

    @staticmethod
    def activate_layout(layout_path):
        log.debug("activating layout")
        log.debug(layout_path)
        execute(layout_path, ignore_errors=True)

    def popup(self, widget):
        """Create Popup that allows the user to control their displays in one
        of three ways: launch arandr, select a pre-set screenlayout, toggle a
        display.
        """
        menu = popup.menu()
        menu.add_menuitem(
            "arandr",
            callback=partial(execute, self.manager, ignore_errors=True)
        )
        menu.add_separator()

        displays = Module._get_displays()
        log.debug(displays)
        layouts = Module._get_layouts()
        available_layouts = Module._prune_layouts(layouts, displays)
        log.debug("Available layouts:")
        log.debug(available_layouts)

        if len(available_layouts) > 0:
            for layout in available_layouts:
                sh = os.path.join(__screenlayout_dir__, layout)
                sh_name = os.path.splitext(layout)[0]
                menu.add_menuitem(sh_name,
                                  callback=partial(self.activate_layout, sh))

        menu.add_separator()
        count_on = 0
        for display, state in displays.items():
            if state[1]:
                count_on += 1
        for display, state in displays.items():
            if not state[0]:
                continue
            on_off = "On" if state[1] else "Off"
            menu_line = "{}: {}".format(display, on_off)
            menu.add_menuitem(menu_line,
                              callback=partial(self.toggle_display, display,
                                               state[1], count_on))

        menu.show(widget, 0, 0)

    def toggle_display(self, display, current_state, count_on):
        """Toggle a display on or off based on its current state."""
        if current_state:
            log.debug("toggling off {}".format(display))
            if count_on == 1:
                log.info("attempted to turn off last display")
                return
            execute("{} --output {} --off".format(self.toggle_cmd, display), ignore_errors=True)
        else:
            log.debug("toggling on {}".format(display))
            execute(
                "{} --output {} --auto".format(self.toggle_cmd, display),
                ignore_errors=True
            )

    @staticmethod
    def _get_displays():
        """Queries xrandr and builds a dict of the displays and their state.

        The dict entries are key by the display and are bools (True if
        connected).
        """
        displays = {}
        for line in execute("xrandr -q", ignore_errors=True).split("\n"):
            if "connected" not in line:
                continue
            is_on = bool(re.search(r"\d+x\d+\+(\d+)\+\d+", line))
            parts = line.split(" ", 2)
            display = parts[0]
            displays[display] = (
                (True, is_on) if parts[1] == "connected" else (False, is_on)
            )

        return displays

    @staticmethod
    def _get_layouts():
        """Loads and parses the arandr screen layout scripts."""
        layouts = {}
        try:
            for filename in os.listdir(__screenlayout_dir__):
                if fnmatch.fnmatch(filename, '*.sh'):
                    fullpath = os.path.join(__screenlayout_dir__, filename)
                    with open(fullpath, "r") as file:
                        for line in file:
                            s_line = line.strip()
                            if "xrandr" not in s_line:
                                continue
                            displays_in_file = Module._parse_layout(line)
                            layouts[filename] = displays_in_file
        except Exception as e:
            log.error(str(e))
        return layouts

    @staticmethod
    def _parse_layout(line):
        """Parses a single xrandr line to find what displays are active in the
        command.  Returns them as a list.
        """
        active_displays = []
        to_check = line[7:].split("--output ")
        for check in to_check:
            if not check or "off" in check:
                continue
            active_displays.append(check.split(" ")[0])
        return active_displays

    @staticmethod
    def _prune_layouts(layouts, displays):
        """Return a list of layouts whose displays are actually connected."""
        available = []
        for layout, needs in layouts.items():
            still_valid = True
            for need in needs:
                if need not in displays or not displays[need][0]:
                    still_valid = False
                    break
            if still_valid:
                available.append(layout)
        return available

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4


text:
oc_wm_request

oc_wm_request_logger

oc_wm_request_writer


text:
Kuebiko
=======
A (partial) [Notational Velocity](http://notational.net) clone written in Java.

About
-----
In Japanese mythology, [Kuebiko](http://en.wikipedia.org/wiki/Kuebiko) is the god of knowledge. Likewise, __this__ Kuebiko is a repository for notes, information, and ideas.

Kuebiko came about to fulfill my desire to run NV on multiple platforms. At the time, I was forced to use a Windows PC at work, and there wasn't an alternative to NV that did what I wanted. I wrote Kuebiko to fill this gap.

Once I was able to use a Mac at work, however, the need for an application like Kuebiko lessened greatly. Also, [several alternatives](http://lmgtfy.com/?q=cross+platform+notational+velocity+clone) to NV now exist, rendering further development of Kuebiko superfluous. While functional, the application should be considered an alpha; there are probably a few (potentially nasty) bugs lurking in the code. I've made the source code available in hopes that someone may find it useful.

License
-------
Kuebiko is open source and licensed under the [BSD 3-Clause License](http://opensource.org/licenses/BSD-3-Clause). Please use it as you see fit.