text:
#include "tensorflow/lite/delegates/gpu/gl/gl_errors.h"

#include <string>
#include <vector>

#include "absl/strings/str_join.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/gl/portable_egl.h"
#include "tensorflow/lite/delegates/gpu/gl/portable_gl31.h"

namespace tflite {
namespace gpu {
namespace gl {
namespace {

const char* ErrorToString(GLenum error) {
  switch (error) {
    case GL_INVALID_ENUM:
      return "[GL_INVALID_ENUM]: An unacceptable value is specified for an "
             "enumerated argument.";
    case GL_INVALID_VALUE:
      return "[GL_INVALID_VALUE]: A numeric argument is out of range.";
    case GL_INVALID_OPERATION:
      return "[GL_INVALID_OPERATION]: The specified operation is not allowed "
             "in the current state.";
    case GL_INVALID_FRAMEBUFFER_OPERATION:
      return "[GL_INVALID_FRAMEBUFFER_OPERATION]: The framebuffer object is "
             "not complete.";
    case GL_OUT_OF_MEMORY:
      return "[GL_OUT_OF_MEMORY]: There is not enough memory left to execute "
             "the command.";
  }
  return "[UNKNOWN_GL_ERROR]";
}

struct ErrorFormatter {
  void operator()(std::string* out, GLenum error) const {
    absl::StrAppend(out, ErrorToString(error));
  }
};

}  // namespace

// TODO(akulik): create new error space for GL error.

absl::Status GetOpenGlErrors() {
#ifdef __EMSCRIPTEN__
  // This check is not recommended on WebGL, since it will force a wait on the
  // GPU process.
  return absl::OkStatus();
#else
  auto error = glGetError();
  if (error == GL_NO_ERROR) {
    return absl::OkStatus();
  }
  auto error2 = glGetError();
  if (error2 == GL_NO_ERROR) {
    return absl::InternalError(ErrorToString(error));
  }
  std::vector<GLenum> errors = {error, error2};
  for (error = glGetError(); error != GL_NO_ERROR; error = glGetError()) {
    errors.push_back(error);
  }
  return absl::InternalError(absl::StrJoin(errors, ",", ErrorFormatter()));
#endif  // __EMSCRIPTEN__
}

absl::Status GetEglError() {
  EGLint error = eglGetError();
  switch (error) {
    case EGL_SUCCESS:
      return absl::OkStatus();
    case EGL_NOT_INITIALIZED:
      return absl::InternalError(
          "EGL is not initialized, or could not be initialized, for the "
          "specified EGL display connection.");
    case EGL_BAD_ACCESS:
      return absl::InternalError(
          "EGL cannot access a requested resource (for example a context is "
          "bound in another thread).");
    case EGL_BAD_ALLOC:
      return absl::InternalError(
          "EGL failed to allocate resources for the requested operation.");
    case EGL_BAD_ATTRIBUTE:
      return absl::InternalError(
          "An unrecognized attribute or attribute value was passed in the "
          "attribute list.");
    case EGL_BAD_CONTEXT:
      return absl::InternalError(
          "An EGLContext argument does not name a valid EGL rendering "
          "context.");
    case EGL_BAD_CONFIG:
      return absl::InternalError(
          "An EGLConfig argument does not name a valid EGL frame buffer "
          "configuration.");
    case EGL_BAD_CURRENT_SURFACE:
      return absl::InternalError(
          "The current surface of the calling thread is a window, pixel buffer "
          "or pixmap that is no longer valid.");
    case EGL_BAD_DISPLAY:
      return absl::InternalError(
          "An EGLDisplay argument does not name a valid EGL display "
          "connection.");
    case EGL_BAD_SURFACE:
      return absl::InternalError(
          "An EGLSurface argument does not name a valid surface (window, pixel "
          "buffer or pixmap) configured for GL rendering.");
    case EGL_BAD_MATCH:
      return absl::InternalError(
          "Arguments are inconsistent (for example, a valid context requires "
          "buffers not supplied by a valid surface).");
    case EGL_BAD_PARAMETER:
      return absl::InternalError("One or more argument values are invalid.");
    case EGL_BAD_NATIVE_PIXMAP:
      return absl::InternalError(
          "A NativePixmapType argument does not refer to a valid native "
          "pixmap.");
    case EGL_BAD_NATIVE_WINDOW:
      return absl::InternalError(
          "A NativeWindowType argument does not refer to a valid native "
          "window.");
    case EGL_CONTEXT_LOST:
      return absl::InternalError(
          "A power management event has occurred. The application must destroy "
          "all contexts and reinitialize OpenGL ES state and objects to "
          "continue rendering.");
  }
  return absl::UnknownError("EGL error: " + std::to_string(error));
}

}  // namespace gl
}  // namespace gpu
}  // namespace tflite


text:
<?php $this->beginContent('//layouts/main'); ?>
<div id="content">
	<?php print $content; ?>
</div><!-- content -->
<?php $this->endContent(); ?>

redpajama_set_name: RedPajamaGithub


text: {{block}}


text:
package ch.fhnw.demopolis.model;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import ch.fhnw.demopolis.config.ILogConfig;
import ch.fhnw.demopolis.model.entities.IDesignEntity;

public final class Model {
	private final IScenario scenario;

	private final Materials materials = new Materials();
	private final StaticEnvironment environment = new StaticEnvironment();
	private final Population population = new Population();
	private final ScenarioWriter writer = new ScenarioWriter();

	private final List<IDesignEntity> designEntities = new ArrayList<>();

	public Model(IScenario scenario) throws IOException {
		this.scenario = scenario;
		environment.load(this);
		population.load(this);
		resetDesignEntities();
	}

	public IScenario getScenario() {
		return scenario;
	}

	public Materials getMaterials() {
		return materials;
	}

	public StaticEnvironment getEnvironment() {
		return environment;
	}

	public Population getPopulation() {
		return population;
	}

	public List<IDesignEntity> getDesignEntities() {
		return designEntities;
	}

	public void setDesignEntities(List<IDesignEntity> entities) {
		designEntities.clear();
		designEntities.addAll(entities);
	}

	public void resetDesignEntities() {
		setDesignEntities(scenario.getEntities());
	}

	public void write() {
		try {
			writer.write(this, ILogConfig.BASE_PATH);
		} catch (Exception e) {
			System.err.println("cant write scenario: " + e);
		}
	}
}


text:
package com.common.android.utils.interfaces;

import android.support.annotation.NonNull;
import android.view.MotionEvent;

/**
 * Created by Jan Rabe on 28/09/15.
 */
public interface DispatchTouchEvent {

    boolean dispatchTouchEvent(@NonNull final MotionEvent event);
}


text:
package org.apache.commons.vfs2.provider.tar;

import java.util.Collection;

import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.provider.CompositeFileProvider;

/**
 * A file system provider for Tar files. Provides read-only file systems.
 */
public class Tbz2FileProvider extends CompositeFileProvider {
    /** The provider's capabilities */
    protected static final Collection<Capability> capabilities = TarFileProvider.capabilities;

    private static final String[] SCHEMES = new String[] { "bz2", "tar" };

    public Tbz2FileProvider() {
        super();
    }

    @Override
    protected String[] getSchemes() {
        return SCHEMES;
    }

    @Override
    public Collection<Capability> getCapabilities() {
        return capabilities;
    }
}


text: from .profile_edit import *


text:
"""Copyright 2021 Advanced Micro Devices, Inc. All rights Reserved.
Run tests on build"""

import re
import os
import sys
import subprocess
import shlex
import argparse
import pathlib
import platform
from genericpath import exists
from fnmatch import fnmatchcase
from xml.dom import minidom
import multiprocessing
import time

args = {}
OS_info = {}

timeout = False
test_proc = None
stop = 0

test_script = [ 'cd %IDIR%', '%XML%' ]

def parse_args():
    """Parse command-line arguments"""
    parser = argparse.ArgumentParser(description="""
    Checks build arguments
    """)
    parser.add_argument('-t', '--test', required=True,
                        help='Test set to run from rtest.xml (required, e.g. osdb)')
    parser.add_argument('-g', '--debug', required=False, default=False,  action='store_true',
                        help='Test Debug build (optional, default: false)')
    parser.add_argument('-o', '--output', type=str, required=False, default="xml",
                        help='Test output file (optional, default: test_detail.xml)')
    parser.add_argument(      '--install_dir', type=str, required=False, default="build",
                        help='Installation directory where build or release folders are (optional, default: build)')
    parser.add_argument(      '--fail_test', default=False, required=False, action='store_true',
                        help='Return as if test failed (optional, default: false)')
    # parser.add_argument('-v', '--verbose', required=False, default = False, action='store_true',
    #                     help='Verbose install (optional, default: False)')
    return parser.parse_args()

def vram_detect():
    global OS_info
    OS_info["VRAM"] = 0
    if os.name == "nt":
        cmd = "hipinfo.exe"
        process = subprocess.run([cmd], stdout=subprocess.PIPE)
        for line_in in process.stdout.decode().splitlines():
            if 'totalGlobalMem' in line_in:
                OS_info["VRAM"] = float(line_in.split()[1])
                break
    else:
        cmd = "rocminfo"
        process = subprocess.run([cmd], stdout=subprocess.PIPE)
        for line_in in process.stdout.decode().splitlines():
            match = re.search(r'.*Size:.*([0-9]+)\(.*\).*KB', line_in, re.IGNORECASE)
            if match:
                OS_info["VRAM"] = float(match.group(1))/(1024*1024)
                break

def os_detect():
    global OS_info
    if os.name == "nt":
        OS_info["ID"] = platform.system()
    else:
        inf_file = "/etc/os-release"
        if os.path.exists(inf_file):
            with open(inf_file) as f:
                for line in f:
                    if "=" in line:
                        k,v = line.strip().split("=")
                        OS_info[k] = v.replace('"','')
    OS_info["NUM_PROC"] = os.cpu_count()
    vram_detect()
    print(OS_info)

def create_dir(dir_path):
    if os.path.isabs(dir_path):
        full_path = dir_path
    else:
        full_path = os.path.join( os.getcwd(), dir_path )
    return pathlib.Path(full_path).mkdir(parents=True, exist_ok=True)

def delete_dir(dir_path) :
    if (not os.path.exists(dir_path)):
        return
    if os.name == "nt":
        return run_cmd( "RMDIR" , f"/S /Q {dir_path}")
    else:
        linux_path = pathlib.Path(dir_path).absolute()
        return run_cmd( "rm" , f"-rf {linux_path}")

class TimerProcess(multiprocessing.Process):

    def __init__(self, start, stop, kill_pid):
        multiprocessing.Process.__init__(self)
        self.quit = multiprocessing.Event()
        self.timed_out = multiprocessing.Event()
        self.start_time = start
        self.max_time = stop
        self.kill_pid = kill_pid

    def run(self):
        while not self.quit.is_set():
            #print( f'time_stop {self.start_time} limit {self.max_time}')
            if (self.max_time == 0):
                return
            t = time.monotonic()
            if ( t - self.start_time > self.max_time ):
                print( f'killing {self.kill_pid} t {t}')
                if os.name == "nt":
                    cmd = ['TASKKILL', '/F', '/T', '/PID', str(self.kill_pid)]
                    proc = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr)
                else:
                    os.kill(self.kill_pid, signal.SIGKILL)
                self.timed_out.set()
                self.stop()
            pass

    def stop(self):
        self.quit.set()

    def stopped(self):
        return self.timed_out.is_set()

def time_stop(start, pid):
    global timeout, stop
    while (True):
        print( f'time_stop {start} limit {stop}')
        t = time.monotonic()
        if (stop == 0):
            return
        if ( (stop > 0) and (t - start > stop) ):
            print( f'killing {pid} t {t}')
            if os.name == "nt":
                cmd = ['TASKKILL', '/F', '/T', '/PID', str(pid)]
                proc = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr)
            else:
                test_proc.kill()
            timeout = True
            stop = 0
        time.sleep(0)

def run_cmd(cmd, test = False, time_limit = 0):
    global args
    global test_proc, timer_thread
    global stop
    if (cmd.startswith('cd ')):
        return os.chdir(cmd[3:])
    if (cmd.startswith('mkdir ')):
        return create_dir(cmd[6:])
    cmdline = f"{cmd}"
    print(cmdline)
    try:
        if not test:
            proc = subprocess.run(cmdline, check=True, stderr=subprocess.STDOUT, shell=True)
            status = proc.returncode
        else:
            error = False
            timeout = False
            test_proc = subprocess.Popen(shlex.split(cmdline), text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
            if time_limit > 0:
                start = time.monotonic()
                #p = multiprocessing.Process(target=time_stop, args=(start, test_proc.pid))
                p = TimerProcess(start, time_limit, test_proc.pid)
                p.start()
            while True:
                output = test_proc.stdout.readline()
                if output == '' and test_proc.poll() is not None:
                    break
                elif output:
                    outstring = output.strip()
                    print (outstring)
                    error = error or re.search(r'error|fail', outstring, re.IGNORECASE)
            status = test_proc.poll()
            if time_limit > 0:
                p.stop()
                p.join()
                timeout = p.stopped()
                print(f"timeout {timeout}")
            if error:
                status = 1
            elif timeout:
                status = 2
            else:
                status = test_proc.returncode
    except:
        import traceback
        exc = traceback.format_exc()
        print( "Python Exception: {0}".format(exc) )
        status = 3
    return status

def batch(script, xml):
    global OS_info
    global args
    #
    cwd = pathlib.os.curdir
    rtest_cwd_path = os.path.abspath( os.path.join( cwd, 'rtest.xml') )
    if os.path.isfile(rtest_cwd_path) and os.path.dirname(rtest_cwd_path).endswith( "staging" ):
        # if in a staging directory then test locally
        test_dir = cwd
    else:
        if args.debug: build_type = "debug"
        else: build_type = "release"
        test_dir = f"{args.install_dir}//{build_type}//clients//staging"
    fail = False
    for i in range(len(script)):
        cmdline = script[i]
        xcmd = cmdline.replace('%IDIR%', test_dir)
        cmd = xcmd.replace('%ODIR%', args.output)
        if cmd.startswith('tdir '):
            if pathlib.Path(cmd[5:]).exists():
                return 0 # all further cmds skipped
            else:
                continue
        error = False
        if cmd.startswith('%XML%'):
            # run the matching tests listed in the xml test file
            var_subs = {}
            for var in xml.getElementsByTagName('var'):
                name = var.getAttribute('name')
                val = var.getAttribute('value')
                var_subs[name] = val
            for test in xml.getElementsByTagName('test'):
                sets = test.getAttribute('sets')
                runset = sets.split(',')
                if args.test in runset:
                    for run in test.getElementsByTagName('run'):
                        name = run.getAttribute('name')
                        vram_limit = run.getAttribute('vram_min')
                        if vram_limit:
                            if OS_info["VRAM"] < float(vram_limit):
                                print( f'***\n*** Skipped: {name} due to VRAM req.\n***')
                                continue
                        if name:
                            print( f'***\n*** Running: {name}\n***')
                        time_limit = run.getAttribute('time_max')
                        if time_limit:
                            timeout = float(time_limit)
                        else:
                            timeout = 0

                        raw_cmd = run.firstChild.data
                        var_cmd = raw_cmd.format_map(var_subs)
                        error = run_cmd(var_cmd, True, timeout)
                        if (error == 2):
                            print( f'***\n*** Timed out when running: {name}\n***')
        else:
            error = run_cmd(cmd)
        fail = fail or error

    if (fail):
        if (cmd == "%XML%"):
            print(f"FAILED xml test suite!")
        else:
            print(f"ERROR running: {cmd}")
        if (os.curdir != cwd):
            os.chdir( cwd )
        return 1
    if (os.curdir != cwd):
        os.chdir( cwd )
    return 0

def run_tests():
    global test_script
    global xmlDoc

    # install
    cwd = os.curdir

    xmlPath = os.path.join( cwd, 'rtest.xml')
    xmlDoc = minidom.parse( xmlPath )

    scripts = []
    scripts.append( test_script )
    for i in scripts:
        if (batch(i, xmlDoc)):
            #print("Failure in script. ABORTING")
            if (os.curdir != cwd):
                os.chdir( cwd )
            return 1
    if (os.curdir != cwd):
        os.chdir( cwd )
    return 0

def main():
    global args
    global timer_thread

    os_detect()
    args = parse_args()

    status = run_tests()

    if args.fail_test: status = 1

    if (status):
        sys.exit(status)

if __name__ == '__main__':
    main()


text:
ALTER TABLE notification.notification_content ADD PRIMARY KEY (id) NOT DEFERRABLE INITIALLY IMMEDIATE;
-- ----------------------------
--  Indexes structure for table notification_content
-- ----------------------------

-- ----------------------------------------------------------------------------------------
--  Structure for table Notification
-- ----------------------------------------------------------------------------------------
-- ----------------------------
--  Primary key structure for table notification
-- ----------------------------
ALTER TABLE notification.notification ADD PRIMARY KEY (id) NOT DEFERRABLE INITIALLY IMMEDIATE;
-- ----------------------------
--  Foreign keys structure for table notification
-- ----------------------------
-- account relation is in different schema
ALTER TABLE notification.notification ADD CONSTRAINT "notification_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES api.account (id) ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE;
ALTER TABLE notification.notification ADD CONSTRAINT "notification_notification_content_id_fkey" FOREIGN KEY ("notification_content_id") REFERENCES notification.notification_content (id) ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE;
-- ----------------------------
--  Indexes structure for table notification
-- ----------------------------

-- ----------------------------------------------------------------------------------------
--  Structure for table NotificationActivity
-- ----------------------------------------------------------------------------------------
-- ----------------------------
--  Primary key structure for table notification_activity
-- ----------------------------
ALTER TABLE notification.notification_activity ADD PRIMARY KEY (id) NOT DEFERRABLE INITIALLY IMMEDIATE;
-- ----------------------------
--  Foreign keys structure for table activity
-- ----------------------------
-- account relation is in different schema
ALTER TABLE notification.notification_activity ADD CONSTRAINT "notification_activity_actor_id_fkey" FOREIGN KEY ("actor_id") REFERENCES api.account (id) ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE;
ALTER TABLE notification.notification_activity ADD CONSTRAINT "notification_activity_notification_content_id_fkey" FOREIGN KEY ("notification_content_id") REFERENCES notification.notification_content (id) ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE;
-- ----------------------------
--  Indexes structure for table activity
-- ----------------------------
CREATE INDEX  "notification_account_id_context_id_notification_content_id_idx" ON "notification"."notification" USING btree(account_id DESC, context_channel_id DESC, notification_content_id DESC);

CREATE INDEX  "notification_activity_actor_id_content_id_obsolete_idx" ON "notification"."notification_activity" USING btree(actor_id DESC, notification_content_id DESC, obsolete);

CREATE INDEX  "notification_content_type_constant_target_id_idx" ON "notification"."notification_content" USING btree(type_constant DESC, target_id DESC);

-- ----------------------------
--  Primary key structure for table notification_setting
-- ----------------------------
ALTER TABLE notification.notification_setting ADD PRIMARY KEY (id) NOT DEFERRABLE INITIALLY IMMEDIATE;
-- ----------------------------
--  Foreign keys structure for table activity
-- ----------------------------
-- account relation is in different schema
ALTER TABLE notification.notification_setting ADD CONSTRAINT "notification_setting_channel_id_fkey" FOREIGN KEY ("channel_id") REFERENCES "api"."channel" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE;
ALTER TABLE notification.notification_setting ADD CONSTRAINT "notification_setting_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "api"."account" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE;


text:
package io.fabric8.openclustermanagement.test.apps;

import io.fabric8.kubernetes.client.server.mock.EnableKubernetesMockClient;
import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer;
import io.fabric8.openclustermanagement.api.model.multicloudoperatorssubscription.apps.helmrelease.v1.HelmRelease;
import io.fabric8.openclustermanagement.api.model.multicloudoperatorssubscription.apps.helmrelease.v1.HelmReleaseBuilder;
import io.fabric8.openclustermanagement.api.model.multicloudoperatorssubscription.apps.helmrelease.v1.HelmReleaseList;
import io.fabric8.openclustermanagement.api.model.multicloudoperatorssubscription.apps.helmrelease.v1.HelmReleaseListBuilder;
import io.fabric8.openclustermanagement.client.OpenClusterManagementClient;
import org.junit.jupiter.api.Test;

import java.net.HttpURLConnection;

import static org.assertj.core.api.Assertions.assertThat;

@EnableKubernetesMockClient
class HelmReleaseTest {
  private OpenClusterManagementClient client;
  private KubernetesMockServer server;

  @Test
  void get() {
    // Given
    server.expect().get().withPath("/apis/apps.open-cluster-management.io/v1/namespaces/ns1/helmreleases/test-get")
        .andReturn(HttpURLConnection.HTTP_OK, createNewHelmRelease("test-get"))
        .once();

    // When
    HelmRelease helmRelease = client.apps().helmReleases().inNamespace("ns1").withName("test-get").get();

    // Then
    assertThat(helmRelease)
        .isNotNull()
        .hasFieldOrPropertyWithValue("metadata.name", "test-get");
  }

  @Test
  void list() {
    // Given
    server.expect().get().withPath("/apis/apps.open-cluster-management.io/v1/namespaces/ns1/helmreleases")
        .andReturn(HttpURLConnection.HTTP_OK, new HelmReleaseListBuilder()
            .addToItems(createNewHelmRelease("test-list"))
            .build())
        .once();

    // When
    HelmReleaseList HelmReleaseList = client.apps().helmReleases().inNamespace("ns1").list();

    // Then
    assertThat(HelmReleaseList).isNotNull();
    assertThat(HelmReleaseList.getItems()).hasSize(1);
    assertThat(HelmReleaseList.getItems().get(0))
        .hasFieldOrPropertyWithValue("metadata.name", "test-list");
  }

  @Test
  void delete() {
    // Given
    server.expect().delete().withPath("/apis/apps.open-cluster-management.io/v1/namespaces/ns1/helmreleases/sample-hr")
        .andReturn(HttpURLConnection.HTTP_OK, createNewHelmRelease("sample-hr"))
        .once();

    // When
    boolean isDeleted = client.apps().helmReleases().inNamespace("ns1").withName("sample-hr").delete().size() == 1;

    // Then
    assertThat(isDeleted).isTrue();
  }

  private HelmRelease createNewHelmRelease(String name) {
    return new HelmReleaseBuilder()
        .withNewMetadata().withName(name).endMetadata()
        .withNewRepo()
        .withChartName("nginx-ingress")
        .withNewSource()
        .withNewHelmRepo()
        .withUrls("https://kubernetes-charts.storage.googleapis.com/nginx-ingress-1.26.0.tgz")
        .endHelmRepo()
        .withType("HelmRepo")
        .endSource()
        .withVersion("1.26.0")
        .endRepo()
        .build();
  }
}


text:
import pygame
##import thread
##import atexit
import time

##def start():
##    pass #TODO:
##    # start a thread that calls tick() regularly
##    atexit.register(stop)

##def tick():
##    pass #TODO:

##def stop():
##    pass #TODO:
##    # stop the ticker thread

commands = {
    pygame.K_LEFT:  'L',
    pygame.K_RIGHT: 'R',
    pygame.K_UP:    'U',
    pygame.K_DOWN:  'D',
    pygame.K_A:     'A',
    pygame.K_B:     'B'
}
keys = []

def get_command_flags():
    """Get a collection of flags, one for each possible button/action"""
    global idx

    # Process all queued keypresses and keyreleases, in order
    # and update the 'keys' list
    for event in pygame.events.get():
        if event.type == pygame.KEYDOWN:
            try:
                letter = commands[event.key]
                if not letter in keys:
                    keys.append(letter)
            except:
                pass # ignore unknown key presses

        elif event.type == pygame.KEYUP:
            try:
                letter = commands[event.key]
                if letter in keys:
                    keys.remove(letter)
            except:
                pass # ignore unknown key releases

    return keys

# auto-start the keyboard monitor thread when module is imported
#start()

#----- TEST HARNESS -----------------------------------------------------------

if __name__ == "__main__": # test harness
    while True:
        time.sleep(0.5)
        flags = get_command_flags()
        if 'U' in flags: print("up")
        if 'D' in flags: print("down")
        if 'L' in flags: print("left")
        if 'R' in flags: print("right")
        if 'A' in flags: print("fire")
        if 'B' in flags: print("eject")

# END


text:
package org.littlewings.infinispan.marshalling;

import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;

public class Book {
    @ProtoField(number = 1, required = true)
    String isbn;

    @ProtoField(number = 2, required = true)
    String title;

    @ProtoField(number = 3, required = true, defaultValue = "0")
    int price;

    @ProtoFactory
    public static Book create(String isbn, String title, int price) {
        Book book = new Book();

        book.setIsbn(isbn);
        book.setTitle(title);
        book.setPrice(price);

        return book;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getTitle() {
        return title;
    }

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

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
}


text:
#include <cassert>
#include <iosfwd>
#include <strstream>

int main ()
{
    std::strstreambuf sb;
    std::streampos pos = sb.pubseekoff (10, std::ios::beg, std::ios::in);
    assert (-1 == pos);
    return 0;
}


text:
<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/custom_check" android:state_checked="false"/>
    <item android:drawable="@drawable/custom_checked" android:state_checked="true"/>
    <item android:drawable="@drawable/custom_check"/>
</selector>


text:
scriptdir=`dirname $0`
datapath="$scriptdir/../data"
outpath="$datapath/py"
hcbpath="$datapath/hcb"
hcb2pypath="$scriptdir/favorite/hcb2py.py"
hcbinfopath="$scriptdir/favorite/hcbinfo"
pyexe=""
if command -v "python3" &>/dev/null; then
    pyexe="python3"
elif command -v "py" &>/dev/null; then
    pyexe="py"
else
    pyexe="python"
fi

echo "Creating output directory"
mkdir -p "$outpath"

echo ">> Hoshizora no Memoria"
$pyexe "$hcb2pypath" "$outpath/hoshimemo.py" "$hcbpath/Memoria.hcb" "$hcbinfopath/hoshimemo_1.1.py"

echo ">> Hoshizora no Memoria Eternal Heart"
$pyexe "$hcb2pypath" "$outpath/eternalheart.py" "$hcbpath/Hoshimemo_EH.hcb" "$hcbinfopath/eternalheart_1.2.py"

echo ">> Irotoridori no Sekai"
$pyexe "$hcb2pypath" "$outpath/iroseka.py" "$hcbpath/World.hcb" "$hcbinfopath/iroseka_1.1.py"

echo ">> Irotoridori no Hikari"
$pyexe "$hcb2pypath" "$outpath/irohika.py" "$hcbpath/Hikari.hcb" "$hcbinfopath/irohika_1.1.py"

echo ">> Akai Hitomi ni Utsuru Sekai"
$pyexe "$hcb2pypath" "$outpath/akaihitomi.py" "$hcbpath/Shinku.hcb" "$hcbinfopath/akaihitomi_1.0.py"

echo ">> AstralAir no Shiroki Towa"
$pyexe "$hcb2pypath" "$outpath/astralair.py" "$hcbpath/Snow.hcb" "$hcbinfopath/astralair_1.1.py"

echo ">> AstralAir no Shiroki Towa Finale"
$pyexe "$hcb2pypath" "$outpath/astralfinale.py" "$hcbpath/AstralAirFinale.hcb" "$hcbinfopath/astralfinale_1.1.py"


text:
using Fody.Constructors.Internal;
using System;

namespace Fody.Constructors {
   [AttributeUsage(AttributeTargets.Class)]
   public class RequiredFieldsConstructorAttribute : AbstractConstructorAttributeBase {
      public RequiredFieldsConstructorAttribute() : base(FieldCondition) { }

      private static bool FieldCondition(FieldInfo field) {
         return !field.HasNonDefaultFieldInitializer && field.IsInitOnly;
      }
   }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using ModernRonin.PraeterArtem.Functional;

namespace ModernRonin.PraeterArtem.Scheduling
{
    /// <summary>
    /// Implements <see cref="IProcessor{T}"/>.
    /// </summary>
    /// <typeparam name="TWrappedProcessor"></typeparam>
    public sealed class Processor<TWrappedProcessor> : AThrottlingConfigurable,
                                                IProcessor<TWrappedProcessor>
    {
        readonly Dictionary<DateTime, TimeSpan> mHistory =
            new Dictionary<DateTime, TimeSpan>();
        readonly object mLocker = new object();
        readonly ITimeGiver mTimeGiver;
        readonly TWrappedProcessor mWrappedProcessor;
        bool mIsExecutingRequest;
        public Processor(TWrappedProcessor wrappedProcessor,
                         ITimeGiver timeGiver)
        {
            mWrappedProcessor = wrappedProcessor;
            mTimeGiver = timeGiver;
        }
        public TimeSpan AverageLag
        {
            get
            {
                PruneHistory();
                if (mHistory.IsEmpty())
                    return TimeSpan.FromMilliseconds(0);
                return
                    TimeSpan.FromMilliseconds(
                                              mHistory.Values.Average(
                                                                      t =>
                                                                          t
                                                                              .TotalMilliseconds));
            }
        }
        public bool CanCurrentlyExecuteRequest
        {
            get
            {
                if (mIsExecutingRequest)
                    return false;
                return CurrentRequestCountTowardsLimit <
                       MaximumRequestCountPerDuration;
            }
        }
        public int CurrentRequestCountTowardsLimit
        {
            get
            {
                PruneHistory();
                return mHistory.Count;
            }
        }
        public void Execute(Action<TWrappedProcessor> request)
        {
            mIsExecutingRequest = true;
            // avoiding re-entrancy
            lock (mLocker)
            {
                var started = mTimeGiver.Now;
                mHistory[started]= TimeSpan.FromMilliseconds(0);
                var watch = new Stopwatch();
                watch.Start();
                request(mWrappedProcessor);
                watch.Stop();
                mHistory[started] = watch.Elapsed;
            }
            mIsExecutingRequest = false;
        }
        void PruneHistory()
        {
            var now = mTimeGiver.Now;
            var startOfThrottlingPeriod = now.Subtract(Duration);
            mHistory.RemoveWhere(kvp => kvp.Key < startOfThrottlingPeriod);
        }
    }
}


text:
<?php namespace Anomaly\FilesModule\Folder\Command;

use Anomaly\FilesModule\File\Contract\FileRepositoryInterface;
use Anomaly\FilesModule\Folder\Contract\FolderRepositoryInterface;
use Anomaly\Streams\Platform\Support\Decorator;

/**
 * Class GetFolder
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 */
class GetFolder
{

    /**
     * The folder identifier.
     *
     * @var mixed
     */
    protected $identifier;

    /**
     * Create a new GetFolder instance.
     *
     * @param $identifier
     */
    public function __construct($identifier)
    {
        $this->identifier = $identifier;
    }

    /**
     * Handle the command.
     *
     * @param  FileRepositoryInterface   $files
     * @param  FolderRepositoryInterface $folders
     * @param  Decorator                 $decorator
     * @return \Anomaly\FilesModule\Folder\Contract\FolderInterface|\Anomaly\Streams\Platform\Model\EloquentModel|null
     */
    public function handle(FolderRepositoryInterface $folders)
    {
        if (is_numeric($this->identifier)) {
            return $folders->find($this->identifier);
        }

        if (!is_numeric($this->identifier)) {
            return $folders->findBySlug($this->identifier);
        }

        return null;
    }
}


text:
import Ember from 'ember';

export default Ember.ObjectController.extend({
	needs:['items'],
	onInit:function(){

	}.on('init'),
	items:function(){
		return this.get('controllers.items.model');
	}.property('controllers.items.model'),
});


text:
package com.wiztoybox.examplelauncher;

import android.os.Bundle;
import android.util.Log;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;

public class ExampleActivity extends AndroidApplication {

	public void onCreate (Bundle bundle) {
		super.onCreate(bundle);

		Bundle extras = getIntent().getExtras();
		String exampleName = (String)extras.get("Example");
		Log.i("Starting Example: ", exampleName);
		Example example = Example.newExample(exampleName);
		AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
		config.useGL20 = example.needsGL20();
		config.numSamples = 2;
		initialize(example, config);
	}

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace FileHelpers
{
    /// Indicates the <see cref="ConverterKind"/> used for read/write operations.
    /// <remarks>See the Complete attributes list for more information and examples of each one.</remarks>

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
    public sealed class FieldConverterAttribute : Attribute
    {
        #region "  Constructors  "

        /// Indicates the <see cref="ConverterKind"/> used for read/write operations.
        /// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param>
        public FieldConverterAttribute(ConverterKind converter)
            : this(converter, new string[] {}) {}

        /// Indicates the <see cref="ConverterKind"/> used for read/write operations.
        /// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param>
        /// <param name="arg1">The first param passed directly to the Converter Constructor.</param>
        public FieldConverterAttribute(ConverterKind converter, string arg1)
            : this(converter, new string[] {arg1}) {}

        /// Indicates the <see cref="ConverterKind"/> used for read/write operations.
        /// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param>
        /// <param name="arg1">The first param passed directly to the Converter Constructor.</param>
        /// <param name="arg2">The second param passed directly to the Converter Constructor.</param>
        public FieldConverterAttribute(ConverterKind converter, string arg1, string arg2)
            : this(converter, new string[] {arg1, arg2}) {}

        /// Indicates the <see cref="ConverterKind"/> used for read/write operations.
        /// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param>
        /// <param name="arg1">The first param passed directly to the Converter Constructor.</param>
        /// <param name="arg2">The second param passed directly to the Converter Constructor.</param>
        /// <param name="arg3">The third param passed directly to the Converter Constructor.</param>
        public FieldConverterAttribute(ConverterKind converter, string arg1, string arg2, string arg3)
            : this(converter, new string[] {arg1, arg2, arg3}) {}

        ///
        /// Indicates the <see cref="ConverterKind"/> used for read/write operations.
        ///
        /// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param>
        /// <param name="args">An array of parameters passed directly to the Converter</param>
        private FieldConverterAttribute(ConverterKind converter, params string[] args)
        {
            Kind = converter;

            Type convType;

            switch (converter) {
                case ConverterKind.Date:
                    convType = typeof (ConvertHelpers.DateTimeConverter);
                    break;

                case ConverterKind.DateMultiFormat:
                    convType = typeof (ConvertHelpers.DateTimeMultiFormatConverter);
                    break;

                case ConverterKind.Byte:
                    convType = typeof (ConvertHelpers.ByteConverter);
                    break;

                case ConverterKind.SByte:
                    convType = typeof (ConvertHelpers.SByteConverter);
                    break;

                case ConverterKind.Int16:
                    convType = typeof (ConvertHelpers.Int16Converter);
                    break;
                case ConverterKind.Int32:
                    convType = typeof (ConvertHelpers.Int32Converter);
                    break;
                case ConverterKind.Int64:
                    convType = typeof (ConvertHelpers.Int64Converter);
                    break;

                case ConverterKind.UInt16:
                    convType = typeof (ConvertHelpers.UInt16Converter);
                    break;
                case ConverterKind.UInt32:
                    convType = typeof (ConvertHelpers.UInt32Converter);
                    break;
                case ConverterKind.UInt64:
                    convType = typeof (ConvertHelpers.UInt64Converter);
                    break;

                case ConverterKind.Decimal:
                    convType = typeof (ConvertHelpers.DecimalConverter);
                    break;
                case ConverterKind.Double:
                    convType = typeof (ConvertHelpers.DoubleConverter);
                    break;
                    // Added by Shreyas Narasimhan 17 March 2010
                case ConverterKind.PercentDouble:
                    convType = typeof (ConvertHelpers.PercentDoubleConverter);
                    break;
                case ConverterKind.Single:
                    convType = typeof (ConvertHelpers.SingleConverter);
                    break;
                case ConverterKind.Boolean:
                    convType = typeof (ConvertHelpers.BooleanConverter);
                    break;
                    // Added by Alexander Obolonkov 2007.11.08
                case ConverterKind.Char:
                    convType = typeof (ConvertHelpers.CharConverter);
                    break;
                    // Added by Alexander Obolonkov 2007.11.08
                case ConverterKind.Guid:
                    convType = typeof (ConvertHelpers.GuidConverter);
                    break;
                default:
                    throw new BadUsageException("Converter '" + converter.ToString() +
                                                "' not found, you must specify a valid converter.");
            }
            //mType = type;

            CreateConverter(convType, args);
        }

        /// Indicates a custom <see cref="ConverterBase"/> implementation.
        /// <param name="customConverter">The Type of your custom converter.</param>
        /// <param name="arg1">The first param passed directly to the Converter Constructor.</param>
        public FieldConverterAttribute(Type customConverter, string arg1)
            : this(customConverter, new string[] {arg1}) {}

        /// Indicates a custom <see cref="ConverterBase"/> implementation.
        /// <param name="customConverter">The Type of your custom converter.</param>
        /// <param name="arg1">The first param passed directly to the Converter Constructor.</param>
        /// <param name="arg2">The second param passed directly to the Converter Constructor.</param>
        public FieldConverterAttribute(Type customConverter, string arg1, string arg2)
            : this(customConverter, new string[] {arg1, arg2}) {}

        /// Indicates a custom <see cref="ConverterBase"/> implementation.
        /// <param name="customConverter">The Type of your custom converter.</param>
        /// <param name="arg1">The first param passed directly to the Converter Constructor.</param>
        /// <param name="arg2">The second param passed directly to the Converter Constructor.</param>
        /// <param name="arg3">The third param passed directly to the Converter Constructor.</param>
        public FieldConverterAttribute(Type customConverter, string arg1, string arg2, string arg3)
            : this(customConverter, new string[] {arg1, arg2, arg3}) {}

        /// Indicates a custom <see cref="ConverterBase"/> implementation.
        /// <param name="customConverter">The Type of your custom converter.</param>
        /// <param name="args">A list of params passed directly to your converter constructor.</param>
        public FieldConverterAttribute(Type customConverter, params object[] args)
        {
            CreateConverter(customConverter, args);
        }

        /// Indicates a custom <see cref="ConverterBase"/> implementation.
        /// <param name="customConverter">The Type of your custom converter.</param>
        public FieldConverterAttribute(Type customConverter)
        {
            CreateConverter(customConverter, new object[] {});
        }

        #endregion

        #region "  Converter  "

        /// The final concrete converter used for FieldToString and StringToField operations
        public ConverterBase Converter { get; private set; }

        /// The <see cref="ConverterKind"/> if a default converter is used
        public ConverterKind Kind { get; private set; }

        #endregion

        #region "  CreateConverter  "

        private void CreateConverter(Type convType, object[] args)
        {
            if (typeof (ConverterBase).IsAssignableFrom(convType)) {
                ConstructorInfo constructor;
                constructor = convType.GetConstructor(
                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic,
                    null,
                    ArgsToTypes(args),
                    null);

                if (constructor == null) {
                    if (args.Length == 0) {
                        throw new BadUsageException("Empty constructor for converter: " + convType.Name +
                                                    " was not found. You must add a constructor without args (can be public or private)");
                    }
                    else {
                        throw new BadUsageException("Constructor for converter: " + convType.Name +
                                                    " with these arguments: (" + ArgsDesc(args) +
                                                    ") was not found. You must add a constructor with this signature (can be public or private)");
                    }
                }

                try {
                    Converter = (ConverterBase) constructor.Invoke(args);
                }
                catch (TargetInvocationException ex) {
                    throw ex.InnerException;
                }
            }
            else if (convType.IsEnum)
                Converter = new EnumConverter(convType);

            else
                throw new BadUsageException("The custom converter must inherit from ConverterBase");
        }

        #endregion

        #region "  ArgsToTypes  "

        private static Type[] ArgsToTypes(object[] args)
        {
            if (args == null) {
                throw new BadUsageException(
                    "The args to the constructor can be null, if you do not want to pass anything into them.");
            }

            var res = new Type[args.Length];

            for (int i = 0; i < args.Length; i++) {
                if (args[i] == null)
                    res[i] = typeof (object);
                else
                    res[i] = args[i].GetType();
            }

            return res;
        }

        private static string ArgsDesc(object[] args)
        {
            string res = DisplayType(args[0]);

            for (int i = 1; i < args.Length; i++)
                res += ", " + DisplayType(args[i]);

            return res;
        }

        private static string DisplayType(object o)
        {
            if (o == null)
                return "Object";
            else
                return o.GetType().Name;
        }

        #endregion

        internal void ValidateTypes(FieldInfo fi)
        {
            bool valid = false;

            Type fieldType = fi.FieldType;

            if (fieldType.IsValueType &&
                fieldType.IsGenericType &&
                fieldType.GetGenericTypeDefinition() == typeof (Nullable<>))
                fieldType = fieldType.GetGenericArguments()[0];

            switch (Kind) {
                case ConverterKind.None:
                    valid = true;
                    break;

                case ConverterKind.Date:
                case ConverterKind.DateMultiFormat:
                    valid = typeof (DateTime) == fieldType;
                    break;

                case ConverterKind.Byte:
                case ConverterKind.SByte:
                case ConverterKind.Int16:
                case ConverterKind.Int32:
                case ConverterKind.Int64:
                case ConverterKind.UInt16:
                case ConverterKind.UInt32:
                case ConverterKind.UInt64:
                case ConverterKind.Decimal:
                case ConverterKind.Double:
                case ConverterKind.Single:
                case ConverterKind.Boolean:
                case ConverterKind.Char:
                case ConverterKind.Guid:
                    valid = Kind.ToString() == fieldType.UnderlyingSystemType.Name;
                    break;
                case ConverterKind.PercentDouble:
                    valid = typeof (double) == fieldType;
                    break;
            }

            if (valid == false) {
                throw new BadUsageException(
                    "The converter of the field: '" + fi.Name + "' is wrong. The field is of Type: " + fieldType.Name +
                    " and the converter is for type: " + Kind.ToString());
            }
        }
    }
}


text:
using System;
using Android.Bluetooth;
using Plugin.BLE.Abstractions.Exceptions;
namespace Plugin.BLE.Android.CallbackEventArgs
{
    public class DescriptorCallbackEventArgs
    {
        public BluetoothGattDescriptor Descriptor { get; }
        public Exception Exception { get; }

        public DescriptorCallbackEventArgs(BluetoothGattDescriptor descriptor, Exception exception = null)
        {
            Descriptor = descriptor;
            Exception = exception;
        }
    }
}


text:
package cn.telling.shirocontroller;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.springframework.stereotype.Component;

import cn.telling.utils.LogUtils;
import cn.telling.utils.TCPIPUtil;

@Component("frameperms")
public class FramePermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {

	@Override
	public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws IOException
	{
		HttpServletRequest req = (HttpServletRequest) request;
		Subject subject = getSubject(request, response);
		String uri = req.getRequestURI();
		String requestURL = req.getRequestURL().toString();//带协议的全访问地址
		String contextPath = req.getContextPath();//请求项目名称 /Fancy/

		int i = uri.indexOf(contextPath);
		if (i > -1)
		{
			uri = uri.substring(i + contextPath.length());
		}
		if (StringUtils.isNotEmpty(uri))
		{
			uri = "/";
		}
		boolean permitted = false;
		if ("/".equals(uri))
		{
			permitted = true;
		} else
		{
			permitted = subject.isPermitted(uri);
		}
		String isqx = "否";
		if (permitted)
		{
			isqx = "是";
		}
		// 写日志
		String ip = TCPIPUtil.getIpAddr(req);
		LogUtils.info("访问地址:"+requestURL.replace("localhost", ip)+",是否通过:"+isqx);
		return permitted;
	}
}


text:
require "spec_helper"

describe Gesund::Checks::File do
  subject { Gesund::Checks::File.new('somefile') }
  it "sets success as true when file is a file" do
    expect(File).to receive(:file?) { true }
    expect(subject.success).to equal(true)
    expect(subject.message).to match "File somefile is a file"
  end
  it "sets success to false when file is not a file" do
    expect(File).to receive(:file?) { false }
    expect(subject.success).to equal(false)
    expect(subject.message).to match "File somefile is not a file"
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Brunonia 9: 196 (1986)

#### Original name
Myelorrhiza jenjiana Verdon & Elix

### Remarks
null


text:
require("../bootstrap");
$injector.require("projectConstants", "./appbuilder/project-constants");
$injector.require("projectFilesProvider", "./appbuilder/providers/project-files-provider");
$injector.require("pathFilteringService", "./appbuilder/services/path-filtering");
$injector.require("liveSyncServiceBase", "./services/livesync-service-base");
$injector.require("androidLiveSyncServiceLocator", "./appbuilder/services/livesync/android-livesync-service");
$injector.require("iosLiveSyncServiceLocator", "./appbuilder/services/livesync/ios-livesync-service");
$injector.require("deviceAppDataProvider", "./appbuilder/providers/device-app-data-provider");
$injector.requirePublic("companionAppsService", "./appbuilder/services/livesync/companion-apps-service");
$injector.require("nativeScriptProjectCapabilities", "./appbuilder/project/nativescript-project-capabilities");
$injector.require("cordovaProjectCapabilities", "./appbuilder/project/cordova-project-capabilities");
$injector.require("mobilePlatformsCapabilities", "./appbuilder/mobile-platforms-capabilities");
$injector.requirePublic("npmService", "./appbuilder/services/npm-service");
$injector.require("iOSLogFilter", "./mobile/ios/ios-log-filter");


text:
package org.jetbrains.plugins.textmate.plist;

import com.intellij.openapi.util.text.Strings;
import com.intellij.util.XmlDomReader;
import com.intellij.util.XmlElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import static org.jetbrains.plugins.textmate.plist.PListValue.value;

public class XmlPlistReader implements PlistReader {
  @Override
  public Plist read(@NotNull InputStream inputStream) throws IOException {
    return internalRead(XmlDomReader.readXmlAsModel(inputStream));
  }

  @Override
  public Plist read(@NotNull File file) throws IOException {
    try (FileInputStream fs = new FileInputStream(file)) {
      return read(fs);
    }
  }

  private static Plist internalRead(@NotNull XmlElement root) throws IOException {
    if (root.children.isEmpty()) {
      return Plist.EMPTY_PLIST;
    }

    if (!"plist".equals(root.name)) {
      throw new IOException("Unknown xml format. Root element is '" + root.name + "'");
    }

    XmlElement dictElement = root.getChild("dict");
    return dictElement != null ? (Plist)readDict(dictElement).getValue() : Plist.EMPTY_PLIST;
  }

  private static PListValue readDict(@NotNull XmlElement dictElement) throws IOException {
    Plist dict = new Plist();
    List<XmlElement> children = dictElement.children;
    int i = 0;
    for (; i < children.size(); i++) {
      XmlElement keyElement = children.get(i);
      if ("key".equals(keyElement.name)) {
        String attributeKey = keyElement.content;
        i++;
        PListValue value = attributeKey != null ? readValue(attributeKey, children.get(i)) : null;
        if (value != null) {
          dict.setEntry(attributeKey, value);
        }
      }
    }

    return value(dict, PlistValueType.DICT);
  }

  @Nullable
  private static PListValue readValue(@NotNull String key, @NotNull XmlElement valueElement) throws IOException {
    String type = valueElement.name;
    if ("dict".equals(type)) {
      return readDict(valueElement);
    }
    else if ("array".equals(type)) {
      return readArray(key, valueElement);
    }
    else {
      return readBasicValue(type, valueElement);
    }
  }

  private static PListValue readArray(String key, XmlElement element) throws IOException {
    List<Object> result = new ArrayList<>();
    for (XmlElement child : element.children) {
      Object val = readValue(key, child);
      if (val != null) {
        result.add(val);
      }
    }
    return value(result, PlistValueType.ARRAY);
  }

  @Nullable
  private static PListValue readBasicValue(@NotNull String type, @NotNull XmlElement valueElement) throws IOException {
    String content = valueElement.content;

    if ("string".equals(type) && content != null) {
      return value(Strings.unescapeXmlEntities(content), PlistValueType.STRING);
    }
    else if ("true".equals(type)) {
      return value(Boolean.TRUE, PlistValueType.BOOLEAN);
    }
    else if ("false".equals(type)) {
      return value(Boolean.FALSE, PlistValueType.BOOLEAN);
    }
    else if ("integer".equals(type) && content != null) {
      return value(Long.parseLong(content), PlistValueType.INTEGER);
    }
    else if ("real".equals(type) && content != null) {
      return value(Double.parseDouble(content), PlistValueType.REAL);
    }
    else if ("date".equals(type) && content != null) {
      try {
        return value(Plist.dateFormatter().parse(content), PlistValueType.DATE);
      }
      catch (ParseException e) {
        throw new IOException(e);
      }
    }
    return null;
  }
}


text:
"""Implementation of the UUencode and UUdecode functions.

encode(in_file, out_file [,name, mode])
decode(in_file [, out_file, mode])
"""

import binascii
import os
import sys

__all__ = ["Error", "encode", "decode"]

class Error(Exception):
    pass

def encode(in_file, out_file, name=None, mode=None):
    """Uuencode file"""
    #
    # If in_file is a pathname open it and change defaults
    #
    opened_files = []
    try:
        if in_file == '-':
            in_file = sys.stdin
        elif isinstance(in_file, basestring):
            if name is None:
                name = os.path.basename(in_file)
            if mode is None:
                try:
                    mode = os.stat(in_file).st_mode
                except AttributeError:
                    pass
            in_file = open(in_file, 'rb')
            opened_files.append(in_file)
        #
        # Open out_file if it is a pathname
        #
        if out_file == '-':
            out_file = sys.stdout
        elif isinstance(out_file, basestring):
            out_file = open(out_file, 'wb')
            opened_files.append(out_file)
        #
        # Set defaults for name and mode
        #
        if name is None:
            name = '-'
        if mode is None:
            mode = 0666
        #
        # Write the data
        #
        out_file.write('begin %o %s\n' % ((mode&0777),name))
        data = in_file.read(45)
        while len(data) > 0:
            out_file.write(binascii.b2a_uu(data))
            data = in_file.read(45)
        out_file.write(' \nend\n')
    finally:
        for f in opened_files:
            f.close()

def decode(in_file, out_file=None, mode=None, quiet=0):
    """Decode uuencoded file"""
    #
    # Open the input file, if needed.
    #
    opened_files = []
    if in_file == '-':
        in_file = sys.stdin
    elif isinstance(in_file, basestring):
        in_file = open(in_file)
        opened_files.append(in_file)
    try:
        #
        # Read until a begin is encountered or we've exhausted the file
        #
        while True:
            hdr = in_file.readline()
            if not hdr:
                raise Error('No valid begin line found in input file')
            if not hdr.startswith('begin'):
                continue
            hdrfields = hdr.split(' ', 2)
            if len(hdrfields) == 3 and hdrfields[0] == 'begin':
                try:
                    int(hdrfields[1], 8)
                    break
                except ValueError:
                    pass
        if out_file is None:
            out_file = hdrfields[2].rstrip()
            if os.path.exists(out_file):
                raise Error('Cannot overwrite existing file: %s' % out_file)
        if mode is None:
            mode = int(hdrfields[1], 8)
        #
        # Open the output file
        #
        if out_file == '-':
            out_file = sys.stdout
        elif isinstance(out_file, basestring):
            fp = open(out_file, 'wb')
            try:
                os.path.chmod(out_file, mode)
            except AttributeError:
                pass
            out_file = fp
            opened_files.append(out_file)
        #
        # Main decoding loop
        #
        s = in_file.readline()
        while s and s.strip() != 'end':
            try:
                data = binascii.a2b_uu(s)
            except binascii.Error, v:
                # Workaround for broken uuencoders by /Fredrik Lundh
                nbytes = (((ord(s[0])-32) & 63) * 4 + 5) // 3
                data = binascii.a2b_uu(s[:nbytes])
                if not quiet:
                    sys.stderr.write("Warning: %s\n" % v)
            out_file.write(data)
            s = in_file.readline()
        if not s:
            raise Error('Truncated input file')
    finally:
        for f in opened_files:
            f.close()

def test():
    """uuencode/uudecode main program"""

    import optparse
    parser = optparse.OptionParser(usage='usage: %prog [-d] [-t] [input [output]]')
    parser.add_option('-d', '--decode', dest='decode', help='Decode (instead of encode)?', default=False, action='store_true')
    parser.add_option('-t', '--text', dest='text', help='data is text, encoded format unix-compatible text?', default=False, action='store_true')

    (options, args) = parser.parse_args()
    if len(args) > 2:
        parser.error('incorrect number of arguments')
        sys.exit(1)

    input = sys.stdin
    output = sys.stdout
    if len(args) > 0:
        input = args[0]
    if len(args) > 1:
        output = args[1]

    if options.decode:
        if options.text:
            if isinstance(output, basestring):
                output = open(output, 'w')
            else:
                print sys.argv[0], ': cannot do -t to stdout'
                sys.exit(1)
        decode(input, output)
    else:
        if options.text:
            if isinstance(input, basestring):
                input = open(input, 'r')
            else:
                print sys.argv[0], ': cannot do -t from stdin'
                sys.exit(1)
        encode(input, output)

if __name__ == '__main__':
    test()


text:
<?php
namespace Crunch\RegularExpression\Modifier;

class _ModifierTest extends \PHPUnit_Framework_TestCase {
    public function testDummy () {
        $this->markTestIncomplete('Implement tests');
    }
}


text:
---
uid: SolidEdgeFramework.RibbonBars.Parent
summary:
remarks:
---


text:
import unittest
from csrv.model import cards
from csrv.model.cards import corp
from csrv.model.cards import runner
from csrv.model import deck
from csrv.model import errors
from csrv.model import game
from csrv.model import premade_decks
from csrv.model import test_base
from csrv.model import timing_phases
from csrv.model.cards.runner import card01029

class Card01029Test(test_base.TestBase):

  def setUp(self):
    test_base.TestBase.setUp(self)
    self.card = card01029.Card01029(self.game, self.game.runner)
    self.game.runner.clicks.set(4)
    self.game.runner.credits.set(5)
    self.game.runner.grip.add(self.card)
    self.game.insert_next_phase(
        timing_phases.RunnerTurnActions(self.game, self.game.runner))

  def test_installable(self):
    self.assertIn(self.card.install_action,
        self.game.current_phase().choices())

  def test_take_money(self):
    card = cards.Registry.get('Card01108')(self.game, self.game.corp)
    server = self.game.corp.new_remote_server()
    server.install(card)
    self.game.resolve_current_phase(self.card.install_action, None)
    self.game.new_run(server)
    self.game.run.begin()

    # Skip past phase 4_1
    self.game.current_phase().end_phase()

    # indicate that we want to continue the run
    self.game.resolve_current_phase(
        self.game.run._continue_run_action, None)

    # Skip past phase 4_3
    self.game.current_phase().end_phase()

    # end phase 4_4
    self.game.current_phase().end_phase()

    # Instead of phase 4.5, we should have a choice of access phases
    self.assertIsInstance(self.game.current_phase(),
        timing_phases.SelectAccessPhase)

    # Choose the access phase corresponding to our card
    for choice in self.game.current_phase().choices():
      if choice.card == self.card:
        self.game.resolve_current_phase(choice, None)
        break
    else:
      self.fail()

    # There should be only one choice now: how much money to take
    choices = self.game.current_phase().choices()
    self.assertEqual(1, len(choices))
    response = choices[0].request().new_response()
    response.number = 8
    self.game.resolve_current_phase(choices[0], response)

    # Bank Job should have 0 credits and be in the trash
    self.assertEqual(0, self.card.credits)
    self.assertEqual(self.game.runner.heap, self.card.location)

if __name__ == '__main__':
  unittest.main()


text:
[19 things I learnt reading the NodeJS docs](https://hackernoon.com/19-things-i-learnt-reading-the-nodejs-docs-8a2dcc7f307f)

[Node Hero](https://blog.risingstack.com/node-hero-tutorial-getting-started-with-node-js)

[Node.JS at Scale](https://blog.risingstack.com/nodejs-at-scale-npm-best-practices/)


text:
SITE_NAME="This is your site name"
DRUPAL_PROFILE="minimal"

DB_HOST="localhost"
DB_NAME="my_database_name"
DB_USERNAME="my_database_user"
DB_PASSWORD="my_database_password"
DB_ADMIN_USERNAME="my_database_admin_user"
DB_ADMIN_PASSWORD="my_database_admin_password"

DRUPAL_ADMIN_USERNAME="drupal_admin_user"
DRUPAL_ADMIN_PASSWORD="drupal_admin_password"
DRUPAL_ADMIN_EMAIL="drupal.admin-user@email.com"
DRUPAL_SITE_EMAIL="drupal.site@email.com"

DRUPAL_FILES_FOLDER="sites/default/files"
DRUPAL_TMP_FOLDER="sites/default/tmp"
DRUPAL_PRIVATE_FILES_FOLDER="sites/default/private"

DEFAULT_UNIX_OWNER="www-data"
DEFAULT_UNIX_GROUP="www-data"
DEFAULT_UNIX_MOD="775"
WRITEABLE_UNIX_OWNER="www-data"
WRITEABLE_UNIX_GROUP="www-data"
WRITEABLE_UNIX_MOD="775"
PROTECTED_CFG_UNIX_MOD="555"

#--------------------------------------
#       DB installation

echo "CREATE DATABASE IF NOT EXISTS $DB_NAME;
GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USERNAME'@'localhost' IDENTIFIED BY '$DB_PASSWORD';" | mysql -u $DB_ADMIN_USERNAME -p$DB_ADMIN_PASSWORD

#--------------------------------------
#       Drupal installation

chown $DEFAULT_UNIX_OWNER:$DEFAULT_UNIX_GROUP . -R
chmod $DEFAULT_UNIX_MOD . -R

#       Drupal download + initialisation
echo -n "api = 2
core = 8.x
projects[] = drupal" > tmp.make
drush make tmp.make -y
rm tmp.make
drush si $DRUPAL_PROFILE --db-url=mysql://$DB_USERNAME:$DB_PASSWORD@$DB_HOST/$DB_NAME --site-name="$SITE_NAME" --account-name="$DRUPAL_ADMIN_USERNAME" --account-pass="$DRUPAL_ADMIN_PASSWORD" --account-mail="$DRUPAL_ADMIN_EMAIL" --site-mail="$DRUPAL_SITE_EMAIL" -y

#       Drupal modules folder structure setup
mkdir libraries
mkdir modules/custom
mkdir modules/contrib
#mkdir modules/features
chown $DEFAULT_UNIX_OWNER:$DEFAULT_UNIX_GROUP . -R
chmod $DEFAULT_UNIX_MOD . -R

#       Drupal File System folders setup
mkdir $DRUPAL_TMP_FOLDER
mkdir $DRUPAL_PRIVATE_FILES_FOLDER
chown $WRITEABLE_UNIX_OWNER:$WRITEABLE_UNIX_GROUP $DRUPAL_FILES_FOLDER -R
chmod $WRITEABLE_UNIX_MOD $DRUPAL_FILES_FOLDER -R
chown $WRITEABLE_UNIX_OWNER:$WRITEABLE_UNIX_GROUP $DRUPAL_TMP_FOLDER -R
chmod $WRITEABLE_UNIX_MOD $DRUPAL_TMP_FOLDER -R
chown $WRITEABLE_UNIX_OWNER:$WRITEABLE_UNIX_GROUP $DRUPAL_PRIVATE_FILES_FOLDER -R
chmod $WRITEABLE_UNIX_MOD $DRUPAL_PRIVATE_FILES_FOLDER -R

drush vset --yes file_public_path $DRUPAL_FILES_FOLDER
drush vset --yes file_private_path $DRUPAL_PRIVATE_FILES_FOLDER
drush vset --yes file_temporary_path $DRUPAL_TMP_FOLDER

#       Make config write-protected
chmod $PROTECTED_CFG_UNIX_MOD sites/default
chmod $PROTECTED_CFG_UNIX_MOD sites/default/settings.php


text:
/*
 * lineinput.cc
 * read strings line by line.
 */
#include <iostream>
#include <string>
using namespace std;

int main() {
  char line[ 128 ];
  cout << "input a line of strings: " << endl;
  //cin.getline( line, sizeof( line ) );
  //getline( line, sizeof( line ) );
  cin.get( line, sizeof( line ) );
  cout<< "your inupt is: " << endl;
  cout << line << endl;
  return 0;
}


text:
import React from 'react';

import Header from './main/Header';

export default class App extends React.Component {
    static get childContextTypes() {
        return {
            root: React.PropTypes.string
        };
    }

    getChildContext() {
        return {
            root: this.props.route.path
        };
    }

    render() {
        return (
            <div>
                <Header/>
                {this.props.children}
            </div>
        );
    }
}


text:
#include "mathlib/_vector4_sse.h"

const _vector4_sse _vector4_sse::zero = _vector4_sse();

#endif // defined(__USE_SSE__) || defined(DOXYGEN)