text:
<?xml version="1.0" ?>
<!DOCTYPE project [
        <!ENTITY properties SYSTEM "file:../../../xmls/properties.xml">
        <!ENTITY paths  SYSTEM "file:../../../xmls/path_refs.xml">
        <!ENTITY taskdefs SYSTEM "file:../../../xmls/taskdefs.xml">
        <!ENTITY taskdefs_post_compile SYSTEM "file:../../../xmls/taskdefs_post_compile.xml">
        <!ENTITY targets SYSTEM "file:../../../xmls/targets.xml">
]>

<!-- ===================================================================
<description>
   Test/Sample Component file for Axis

Notes:
   This is a build file for use with the Jakarta Ant build tool.

Prerequisites:

   jakarta-ant from http://jakarta.apache.org

Build Instructions:
   To compile
        ant compile
   To execute
        ant run

Author:
  Matt Seibert mseibert@us.ibm.com

Copyright:
  Copyright (c) 2002-2003 Apache Software Foundation.
</description>
==================================================================== -->

<project default="compile">

        <property name="axis.home" location="../../../" />
	<property name="componentName" value="test/wsdl/jaxrpchandler"/>

        &properties;
        &paths;
        &taskdefs;
        &taskdefs_post_compile;
	&targets;

<target name="clean">
    <echo message="Removing ${build.dir}/classes/${componentName} and ${build.dir}/work/${componentName}" />
    <delete dir="${build.dir}/classes/${componentName}"/>
    <delete dir="${build.dir}/work/${componentName}"/>
</target>

<target name="copy" depends="setenv"/>

<target name="compile" depends="copy">
  <echo message="Compiling ${componentName}"/>
    <!-- This is (OK, "will be") a comprehensive test of XML schema types -->
    <wsdl2java url="${axis.home}/test/wsdl/jaxrpchandler/jaxrpchandler.wsdl"
               output="${build.dir}/work"
               serverSide="no"
               testcase="no">
    </wsdl2java>

    <copy todir="${build.dir}/work/test/wsdl/jaxrpchandler" overwrite="yes">
      <fileset dir="${axis.home}/test/wsdl/jaxrpchandler">
        <include name="*TestCase.java"/>
        <include name="*Impl.java"/>
	<include name="*Handler.java"/>
      </fileset>
    </copy>

  <javac srcdir="${build.dir}/work/test/wsdl/jaxrpchandler" destdir="${build.dest}" debug="${debug}" nowarn="${nowarn}" source="${source}" fork="${javac.fork}">
    <classpath>
        <path refid="classpath"/>
    </classpath>
    <include name="*.java"/>
  </javac>
</target>

<target name="run">
	<antcall target="execute-Component" />
</target>

</project>


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Project.picture'
        db.add_column('main_site_project', 'picture',
                      self.gf('django.db.models.fields.files.ImageField')(max_length=100, null=True, blank=True),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'Project.picture'
        db.delete_column('main_site_project', 'picture')

    models = {
        'main_site.project': {
            'Meta': {'object_name': 'Project'},
            'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'date_started': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'picture': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'status': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'summary': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'url': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'})
        }
    }

    complete_apps = ['main_site']

redpajama_set_name: RedPajamaGithub


text:
/* Skin CSS */

.socialcount {
    color: #fff;
    font-size: .875em;
    line-height: 2.2em;
}
.socialcount > li {
    background-color: #999;
}
.socialcount > li,
.socialcount > li > a:focus,
.socialcount .loading {
    border-radius: 5px;
}
.socialcount > li > a:focus,
.socialcount > li:hover,
.socialcount > li.hover /* fix for IE and iframes */ {
    background-color: #464646;
}
/* Special class added to count when it's >= the minimum */
.socialcount .count.minimum {
}

/* Base CSS */

.socialcount {
    list-style: none;
    padding-left: 0;
    margin: 0 0 .6em 0;
    overflow: hidden;
}
.socialcount-large {
    line-height: normal;
}
.socialcount :link,
.socialcount :visited {
    color: inherit;
}
.socialcount > li {
    display: inline-block;
    *display: inline;
    zoom: 1;
    position: relative;
    vertical-align: top;
    min-width: 80px;
    min-height: 30px;
    text-align: center;
    white-space: nowrap;
    *margin-right: 4px;
}
.socialcount.like.de_DE > .facebook {
    min-width: 90px; /* like */
}
.socialcount-small > li {
    min-width: 0;
}
.socialcount-large > li {
    float: left;
    margin: 0 .6em .6em 0;
}
.socialcount.recommend .facebook {
    min-width: 120px;
}
.socialcount-small.recommend .facebook {
    min-width: 0;
}
.socialcount-large > li,
.socialcount-large.recommend .facebook {
    min-width: 105px;
}
.socialcount > li > a {
    display: block;
    padding: 0 5px;
    text-decoration: none;
    color: inherit;
}
.socialcount-small > li > a {
    padding-left: 8px;
    padding-right: 8px;
}
.socialcount-large > li > a {
    padding: 12px 5px 8px;
}

.socialcount .count {
    color: inherit;
    position: relative;
    display: inline-block;
    *display: inline;
    zoom: 1;
    text-align: center;
    margin-left: 6px;
}
.socialcount-large .count {
    display: block;
    width: 100%;
    margin-left: 0;
    padding-top: 10px;
}
.socialcount-small .count {
    margin-left: 0;
}

.socialcount .facebook iframe {
    height: 21px;
    width: 90px; /* recommend */
}
.socialcount.de_DE .facebook iframe {
    width: 83px; /* recommend */
}
.socialcount.like .facebook iframe {
    width: 48px; /* like */
}
.socialcount.like.de_DE .facebook iframe {
    width: 83px; /* like */
}

.socialcount .button {
    display: none;
    width: 100%;
    position: absolute;
    left: 0;
    top: 5px;
    text-align: center;
    pointer-events: none;
}
.socialcount .button iframe {
    pointer-events: auto;
}
.socialcount-large .button {
    top: auto;
    bottom: 2px;
}

.socialcount.grade-a.activate-on-hover > li.hover .count,
.socialcount.grade-a.activate-on-click > li.hover.active .count {
    text-indent: -999px;
}

.socialcount.grade-a.activate-on-hover > li.hover .button,
.socialcount.grade-a.activate-on-click > li.hover.active .button {
    display: block;
}
.socialcount.grade-a.activate-on-hover > li.hover > a,
.socialcount.grade-a.activate-on-click > li.hover.active > a {
    cursor: default;
}
.socialcount-small.grade-a.activate-on-hover > li.hover > a,
.socialcount-small.grade-a.activate-on-click > li.hover.active > a,
.socialcount.grade-a.activate-on-hover > li.hover .button iframe,
.socialcount.grade-a.activate-on-click > li.hover.active .button iframe {
    cursor: pointer;
}

/* Inline loading */
.socialcount .loading {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 3;
    background-color: #aaa;
    background-color: rgba(170, 170, 170, 0.7);
    color: #000;
    text-transform: uppercase;
    font-size: .75em;
    text-align: center;
}
.socialcount-large .loading {
    padding-top: 30%;
}
.socialcount .loading .dot {
    display: inline-block;
    /* no ie7 compat needed here, just shows the text links */
    width: 6px;
    height: 6px;
    margin: 0 3px;
    background: #fff;
    opacity: 0;
    border-radius: 50%;

    -webkit-animation: socialCountLoadingFade .6s infinite;
    -moz-animation: socialCountLoadingFade .6s infinite;
    animation: socialCountLoadingFade .6s infinite;
}

.socialcount .loading .dot:nth-child(1) {
    -webkit-animation-delay: 0s;
    -moz-animation-delay: 0s;
    animation-delay: 0s;
}

.socialcount .loading .dot:nth-child(2) {
    -webkit-animation-delay: .05s;
    -moz-animation-delay: .05s;
    animation-delay: .05s;
}

.socialcount .loading .dot:nth-child(3) {
    -webkit-animation-delay: .1s;
    -moz-animation-delay: .1s;
    animation-delay: .1s;
}

@-webkit-keyframes socialCountLoadingFade {
    0% { opacity: 0; }
    50% { opacity: 0.8; }
    100% { opacity: 0; }
}

@-moz-keyframes socialCountLoadingFade {
    0% { opacity: 0;  }
    50% { opacity: 0.8; }
    100% { opacity: 0; }
}

@keyframes socialCountLoadingFade {
    0% { opacity: 0; }
    50% { opacity: 0.8; }
    100% { opacity: 0; }
}

.social-icon {
    display: inline-block;
    *display: inline;
    zoom: 1;
    vertical-align: middle;
    *margin-right: 5px;
}

.socialcount.grade-a.activate-on-hover > li.hover .social-icon,
.socialcount.grade-a.activate-on-click > li.hover.active .social-icon {
    display: none;
}

.socialcount-small.grade-a.activate-on-hover > li.hover .social-icon,
.socialcount-small.grade-a.activate-on-click > li.hover.active .social-icon,
.socialcount-large.grade-a.activate-on-hover > li.hover .social-icon,
.socialcount-large.grade-a.activate-on-click > li.hover.active .social-icon {
    display: inline-block;
    *display: inline;
    zoom: 1;
}

.icon-sprite, .icon-facebook, .icon-googleplus, .icon-pinterest, .icon-share, .icon-twitter {
    background: url('/bundles/classcentralsite/slashpixel/images/icon-sd6cd4d0ec7.png') no-repeat;
}

.icon-facebook {
    background-position: 0 0;
    height: 15px;
    width: 17px;
}

.icon-googleplus {
    background-position: -21px 0;
    height: 17px;
    width: 20px;
}

.icon-pinterest {
    background-position: -45px 0;
    height: 15px;
    width: 11px;
}

.icon-share {
    background-position: -60px 0;
    height: 16px;
    width: 20px;
}

.icon-twitter {
    background-position: -84px 0;
    height: 15px;
    width: 17px;
}

/* HD icons */
@media (min--moz-device-pixel-ratio: 1.5), (-o-min-device-pixel-ratio: 3/2), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 1.5dppx) {
    .social-icon {
        -webkit-background-size: auto 17px;
        -moz-background-size: auto 17px;
        -o-background-size: auto 17px;
        background-size: auto 17px;
        background-image: url('/bundles/classcentralsite/slashpixel/images/icon-hd-s816aa7a6b3.png');
    }
}


text:
package com.intellij.pom;

public interface Navigatable {
  /**
   * Open editor and select/navigate to the object there if possible. Just do nothing if navigation is not possible like in case of a package
   * @param requestFocus
   */
  void navigate(boolean requestFocus);

  /**
   * @return false if navigation is not possible for any reason.
   */
  boolean canNavigate();

  /**
   * @return false if navigation to source is not possible for any reason. Source means some kind of editor
   */
  boolean canNavigateToSource();
}


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.base.compat;

import android.annotation.TargetApi;
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Process;
import android.os.UserManager;
import android.security.NetworkSecurityPolicy;
import android.view.ActionMode;
import android.view.ViewConfiguration;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import org.chromium.base.annotations.VerifiesOnM;

/**
 * Utility class to use new APIs that were added in M (API level 23). These need to exist in a
 * separate class so that Android framework can successfully verify classes without
 * encountering the new APIs.
 */
@VerifiesOnM
@TargetApi(Build.VERSION_CODES.M)
public final class ApiHelperForM {
    private ApiHelperForM() {}

    /**
     * See {@link WebViewClient#onPageCommitVisible(WebView, String)}, which was added in M.
     */
    public static void onPageCommitVisible(
            WebViewClient webViewClient, WebView webView, String url) {
        webViewClient.onPageCommitVisible(webView, url);
    }

    /**
     * See {@link Process#is64Bit()}.
     */
    public static boolean isProcess64Bit() {
        return Process.is64Bit();
    }

    /** See {@link ConnectivityManager#getBoundNetworkForProcess() } */
    public static Network getBoundNetworkForProcess(ConnectivityManager connectivityManager) {
        return connectivityManager.getBoundNetworkForProcess();
    }

    /** See {@link Network#getNetworkHandle() } */
    public static long getNetworkHandle(Network network) {
        return network.getNetworkHandle();
    }

    /** See @{link ConnectivityManager#getActiveNetwork() } */
    public static Network getActiveNetwork(ConnectivityManager connectivityManager) {
        return connectivityManager.getActiveNetwork();
    }

    /** See @{link ConnectivityManager#getNetworkInfo(Network) } */
    public static NetworkInfo getNetworkInfo(
            ConnectivityManager connectivityManager, Network network) {
        return connectivityManager.getNetworkInfo(network);
    }

    /** See {@link Activity#requestPermissions(String[], int)}. */
    public static void requestActivityPermissions(
            Activity activity, String[] permissions, int requestCode) {
        activity.requestPermissions(permissions, requestCode);
    }

    /** See {@link Activity#shouldShowRequestPermissionRationale(String)}. */
    public static boolean shouldShowRequestPermissionRationale(
            Activity activity, String permission) {
        return activity.shouldShowRequestPermissionRationale(permission);
    }

    /** See {@link PackageManager#isPermissionRevokedByPolicy(String, String)}. */
    public static boolean isPermissionRevokedByPolicy(Activity activity, String permission) {
        return activity.getPackageManager().isPermissionRevokedByPolicy(
                permission, activity.getPackageName());
    }

    /** See {@link NetworkSecurityPolicy#isCleartextTrafficPermitted()}. */
    public static boolean isCleartextTrafficPermitted() {
        return NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted();
    }

    /** See {@link UserManager#isSystemUser()}. */
    public static boolean isSystemUser(UserManager userManager) {
        return userManager.isSystemUser();
    }

    /*
     * See {@link ActionMode#invalidateContentRect()}.
     * @param actionMode
     */
    public static void invalidateContentRectOnActionMode(ActionMode actionMode) {
        actionMode.invalidateContentRect();
    }

    public static void onWindowFocusChangedOnActionMode(ActionMode actionMode, boolean gainFocus) {
        actionMode.onWindowFocusChanged(gainFocus);
    }

    public static int getActionModeType(ActionMode actionMode) {
        return actionMode.getType();
    }

    public static long getDefaultActionModeHideDuration() {
        return ViewConfiguration.getDefaultActionModeHideDuration();
    }

    public static void hideActionMode(ActionMode actionMode, long duration) {
        actionMode.hide(duration);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TorrentParser
{
    /// <summary>
    /// Provides methods for displaying tree model of a string representation of <see cref="Dictionary{,}"/> or <see cref="List{}"/> objects.
    /// </summary>
    public class PrintTree
    {
        /// <summary>
        /// Writes to the console's output string representation of source object, expanding it as a tree if it is a <see cref="Dictionary{,}"/> or a <see cref="List{}"/> type.
        /// </summary>
        /// <param name="source">The object to display.</param>
        /// <param name="indentSize">A size of space indent.</param>
        /// <param name="step">An initial indent amount.</param>
        static public void PrintTreeSimple(object source, int indentSize, int step)
        {
            if (source.GetType().GetInterface(typeof(System.Collections.IDictionary).FullName) != null)
            {
                foreach (System.Collections.DictionaryEntry item in ((System.Collections.IDictionary)source))
                {
                    Console.WriteLine(new string(' ', indentSize * step) + item.Key.ToString() + ":K");
                    if (item.Key.ToString() != "pieces")
                        PrintTreeSimple(item.Value, indentSize * step, step + 1);
                }
            }
            else if (source.GetType().GetInterface(typeof(System.Collections.IList).FullName) != null)
            {
                foreach (object item in ((System.Collections.IList)source))
                {
                    PrintTreeSimple(item, indentSize * step, step + 1);
                }
            }
            else
            {
                Console.WriteLine(new string(' ', indentSize * step) + source.ToString());
            }
        }
        /// <summary>
        /// Writes to the console's output string representation of source object, expanding it as a tree if it is a <see cref="Dictionary{,}"/> or a <see cref="List{}"/> type.
        /// </summary>
        /// <param name="source">The object to display.</param>
        /// <param name="indent">An initial indent amount.</param>
        /// <param name="encoding">An encoding to be used for byte array translation.</param>
        static void PrintTreeDetailed(object source, int indent, Encoding encoding)
        {
            if (source is byte[])
            {
                Console.WriteLine(new string(' ', indent) + new string(encoding.GetChars((byte[])source)));
                /*case "System.Char[]":
                Console.WriteLine(new string(' ', indent) + new string((char[]) o));
                break;*/
            }
            else if (source is long || source is string)
            {
                Console.WriteLine(new string(' ', indent) + source);
            }
            else if (source is List<object>)
            {
                Console.WriteLine(new string(' ', indent) + "[List]");
                foreach (object nestedO in (List<Object>)source)
                {
                    PrintTreeDetailed(nestedO, indent + 1, encoding);
                }
                Console.WriteLine();
            }
            //'source' is supposed to be a Dictionary<byte[], object> . This will confuse users.
            else if (source is Dictionary<object, object>)
            {
                Console.WriteLine(new string(' ', indent) + "[Dictionary]");
                foreach (KeyValuePair<byte[], object> nestedO in (Dictionary<byte[], object>)source)
                {
                    string decodedKey = encoding.GetString(nestedO.Key);
                    Console.WriteLine(new string(' ', indent) + decodedKey + ":K");
                    if (decodedKey == "pieces")
                    {
                        //Console.WriteLine(new string(' ', indent + 1) + BitConverter.ToString((byte[]) nestedO.Value));
                    }
                    else
                        PrintTreeDetailed(nestedO.Value, indent + 1, encoding);
                }
                Console.WriteLine();
            }
            else
            {
                throw new Exception("Unknown type!");
            }
        }
    }
}


text:
import { call, put } from 'redux-saga/effects';
import { fromJS } from 'immutable';

import { apiClient } from '../../mocks/apiMock';
import { callFetchStoreStock } from '../../app/sagas/getStoreStockSaga';
import * as productActions from '../../app/actions/productActions';

jest.mock('../../app/CommandLineOptions', () => ({
  isDebugMode: jest.fn()
}));

const validResponse = {
  data: 'someData'
};
const genericError = new Error('genericError');

describe('getStoreStockSaga', () => {
  describe("scenario1: response is fine, doesn't throw", () => {
    const input = { productCode: '123456' };
    const gen = callFetchStoreStock(input);

    it('should call the api first', () => {
      expect(gen.next().value).toEqual(call(apiClient.fetchAllStoreStock, input.productCode));
    });

    it('should dispatch a SUCCESS_FETCH_STORESTOCK action with the result', () => {
      const transformedResult = fromJS(validResponse);
      expect(gen.next(validResponse).value).toEqual(
        put(productActions.successFetchStoreStock(input.productCode, transformedResult))
      );
    });

    it('and then nothing', () => {
      expect(gen.next().value).toBeUndefined();
    });
  });

  describe('Scenario2: response is not valid, throws an exception', () => {
    const input = { productCode: '' };
    const gen = callFetchStoreStock(input);

    it('should call the api first', () => {
      expect(gen.next().value).toEqual(call(apiClient.fetchAllStoreStock, input.productCode));
    });

    it('should dispatch a FAILURE_FETCH_STORESTOCK action with the error message', () => {
      expect(gen.throw(genericError).value).toEqual(
        put(productActions.failureFetchStoreStock(genericError))
      );
    });
  });
});


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

import java.io.*;
import java.nio.charset.StandardCharsets;
import org.redkale.net.http.WebSocketPacket.FrameType;

/**
 *
 * <p>
 * 详情见: https://redkale.org
 *
 * @author zhangjx
 */
public final class WebSocketPacket {

    public static final Object MESSAGE_NIL = new Object();

    static final WebSocketPacket NONE = new WebSocketPacket();

    public static final WebSocketPacket DEFAULT_PING_PACKET = new WebSocketPacket(FrameType.PING, new byte[0]);

    public static enum MessageType {
        STRING, BYTES, OBJECT;
    }

    public static enum FrameType {

        SERIES(0x00), TEXT(0x01), BINARY(0x02), CLOSE(0x08), PING(0x09), PONG(0x0A);

        private final int value;

        private FrameType(int v) {
            this.value = v;
        }

        public int getValue() {
            return value;
        }

        public static FrameType valueOf(int v) {
            switch (v) {
                case 0x00: return SERIES;
                case 0x01: return TEXT;
                case 0x02: return BINARY;
                case 0x08: return CLOSE;
                case 0x09: return PING;
                case 0x0A: return PONG;
                default: return null;
            }
        }
    }

    protected FrameType type;

    protected byte[] payload;

    protected boolean last = true;

    public WebSocketPacket() {
    }

    public WebSocketPacket(FrameType type, byte[] data) {
        this(type, data, true);
    }

    public WebSocketPacket(FrameType type, byte[] data, boolean last) {
        this.type = type;
        this.payload = data;
        this.last = last;
    }

    public WebSocketPacket(Serializable message, boolean last) {
        boolean bin = message != null && message.getClass() == byte[].class;
        if (bin) {
            this.type = FrameType.BINARY;
            this.payload = (byte[]) message;
        } else {
            this.type = FrameType.TEXT;
            this.payload = String.valueOf(message).getBytes(StandardCharsets.UTF_8);
        }
        this.last = last;
    }

    public byte[] getPayload() {
        return payload;
    }

    public boolean isLast() {
        return last;
    }

    public FrameType getType() {
        return type;
    }

    public void setType(FrameType type) {
        this.type = type;
    }

    public void setPayload(byte[] payload) {
        this.payload = payload;
    }

    public void setLast(boolean last) {
        this.last = last;
    }

    public String toSimpleString() {
        if (payload == null) return null;
        return type == FrameType.TEXT ? new String(payload, StandardCharsets.UTF_8) : ("bytes(" + payload.length + ")");
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + "[type=" + type + ", last=" + last + ", payload=" + toSimpleString() + "]";
    }

}


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

<title>M-Index</title>
<meta name="date" content="2017-05-04">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L M N O P Q R S T U V W X Y _

M

main(String[]) - Static method in class io.github.teamfractal.desktop.DesktopLauncher

mainMenuScreen - Variable in class io.github.teamfractal.RoboticonQuest

MainMenuScreen - Class in io.github.teamfractal.screens

MainMenuScreen(RoboticonQuest) - Constructor for class io.github.teamfractal.screens.MainMenuScreen

mapLayer - Variable in class io.github.teamfractal.screens.GameScreen

mapLayer - Variable in class io.github.teamfractal.util.PlotManager

mapTile - Variable in class io.github.teamfractal.entity.LandPlot

Market - Class in io.github.teamfractal.entity

Market() - Constructor for class io.github.teamfractal.entity.Market

Initialise the market

market - Variable in class io.github.teamfractal.entity.MarketTest

market - Variable in class io.github.teamfractal.RoboticonQuest

MarketAdjustableActor - Class in io.github.teamfractal.actors

MarketAdjustableActor(RoboticonQuest, Skin, ResourceType, boolean) - Constructor for class io.github.teamfractal.actors.MarketAdjustableActor

Constructs an interface to handle the purchase or sale of a particular resource-type
 Populated with buttons for incrementing/decrementing a desired quantity of a particular resource to buy/sell,
 along with an additional button for initiating the relevant transaction and any necessary labels to indicate
 the widget's function and current state

marketCanCheckResourceMoreThanAmountYouWantToBuy() - Method in class io.github.teamfractal.entity.MarketTest

test: hasEnoughResources
 player class can use this method to find out that the amount of resource
 player want to buy is available in the market, if the amount of resource
 in the market is less than the amount of resources player want to buy then
 throw exception

marketShouldAbleToGetAndSetResources() - Method in class io.github.teamfractal.entity.MarketTest

test setEnergy(), setOre(), setFood(), setRoboticon()
 The market should be able to set and get resources.

marketShouldHaveCorrectPricesForResources() - Method in class io.github.teamfractal.entity.MarketTest

test: getBuyPrice()
 The market should start with correct price for player to buy.

marketShouldInitWithCorrectValues() - Method in class io.github.teamfractal.entity.MarketTest

test start mo
 The market should start with correct amount of resources.

marketShouldReduceResourcesWhenSells() - Method in class io.github.teamfractal.entity.MarketTest

marketShouldReturnCorrectSellPrice() - Method in class io.github.teamfractal.entity.MarketTest

test: getSellPrice()

marketShouldUseOreToCreateRoboticons() - Method in class io.github.teamfractal.entity.MarketTest

marketTable - Variable in class io.github.teamfractal.actors.ResourceMarketActors

Provides the spatial framework for the buying/selling widgets presented in the market

MarketTest - Class in io.github.teamfractal.entity

MarketTest() - Constructor for class io.github.teamfractal.entity.MarketTest

max - Variable in class io.github.teamfractal.actors.MarketAdjustableActor

Variable setting the maximum value that the widget can take

max - Variable in class io.github.teamfractal.entity.CaptureData.AttributeRateComment

message - Variable in class io.github.teamfractal.entity.CaptureData.FightAction.Fail

min - Variable in class io.github.teamfractal.actors.MarketAdjustableActor

Variable setting the minimum value that the widget can take

min - Variable in class io.github.teamfractal.entity.CaptureData.AttributeRateComment

modifiers - Variable in class io.github.teamfractal.entity.PlayerEffect

Array holding the inventory modifiers that the effect imposes
 These are either to be added/subtracted to/from the player's current resource counts or multiplied by them,
 depending on the value of the [multiply] variable declared below

money - Variable in class io.github.teamfractal.entity.CaptureData.FightAction.Fail.Cost

money - Variable in class io.github.teamfractal.entity.Player

money - Variable in class io.github.teamfractal.entity.ResourceDelta

montserratLight - Variable in class io.github.teamfractal.util.Fonts

montserratRegular - Variable in class io.github.teamfractal.util.Fonts

This class exists to import TrueType fonts into the game and to convert them into BitmapFont objects using
 the TTFont class that was ported over from DRTN's last project

moreAIPlayers - Variable in class io.github.teamfractal.actors.PlayerSelectActors

morePlayers - Variable in class io.github.teamfractal.actors.PlayerSelectActors

moveLeftInventoryButton - Variable in class io.github.teamfractal.actors.RoboticonMarketActors

Button that decrements selectedRoboticonIndex

moveRightInventoryButton - Variable in class io.github.teamfractal.actors.RoboticonMarketActors

Button that increments selectedRoboticonIndex

multiplier - Variable in class io.github.teamfractal.entity.CaptureData.AttributeRate.Against

multiply - Variable in class io.github.teamfractal.entity.PlayerEffect

Determines whether the effect is to add to (or subtract from) the player's resources or to multiply them by set
 factors

A B C D E F G H I L M N O P Q R S T U V W X Y _

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package com.jsyn.unitgen;

/**
 * LowShelf Filter. This creates a flat response below the cutoff frequency. This filter is
 * sometimes used at the end of a bank of EQ filters. This filter is based on the BiQuad filter.
 * Coefficients are updated whenever the frequency or Q changes.
 *
 * @author Phil Burk (C) 2009 Mobileer Inc
 */
public class FilterLowShelf extends FilterBiquadShelf {

    /**
     * This method is called by Filter_BiquadShelf to update coefficients.
     */
    @Override
    public void updateCoefficients() {
        double scalar = 1.0 / (AP1 + AM1cs + beta_sn);
        a0 = factorA * (AP1 - AM1cs + beta_sn) * scalar;
        a1 = 2.0 * factorA * (AM1 - AP1cs) * scalar;
        a2 = factorA * (AP1 - AM1cs - beta_sn) * scalar;
        b1 = -2.0 * (AM1 + AP1cs) * scalar;
        b2 = (AP1 + AM1cs - beta_sn) * scalar;
    }
}


text:
#include "tensorflow/compiler/mlir/tensorflow/translate/upgrade_graph.h"

namespace tensorflow {

Status GenerateResourceSharedNameIfEmpty(Graph& graph,
                                         FunctionLibraryDefinition& flib_def) {
  auto is_resource_op_with_empty_shared_name = [](const NodeDef& node_def,
                                                  const OpDef& op_def) {
    // Only upgrade when it is a resource handle op.
    if (op_def.output_arg().size() != 1 ||
        op_def.output_arg(0).type() != tensorflow::DT_RESOURCE)
      return false;

    // If the OpDef has "use_node_name_sharing" field, then it is valid to use
    // node names as shared names.
    if (!std::any_of(op_def.attr().begin(), op_def.attr().end(),
                     [](const auto& attr_def) {
                       return attr_def.name() == "use_node_name_sharing" &&
                              attr_def.type() == "bool";
                     }))
      return false;

    if (!std::any_of(op_def.attr().begin(), op_def.attr().end(),
                     [](const auto& attr_def) {
                       return attr_def.name() == "shared_name" &&
                              attr_def.type() == "string";
                     }))
      return false;

    auto iter = node_def.attr().find("shared_name");
    if (iter == node_def.attr().end()) return true;
    return iter->second.s().empty();
  };

  // Upgrade nodes in the graph.
  for (auto* node : graph.nodes()) {
    if (is_resource_op_with_empty_shared_name(node->def(), node->op_def())) {
      node->AddAttr("shared_name", node->name());
    }
  }

  // Upgrade nodes in the functions.
  auto func_names = flib_def.ListFunctionNames();
  for (const auto& func_name : func_names) {
    const FunctionDef* orig = flib_def.Find(func_name);
    DCHECK(orig);
    auto copy = *orig;
    for (auto& node_def : *copy.mutable_node_def()) {
      const OpDef* op_def = nullptr;
      TF_RETURN_IF_ERROR(flib_def.LookUpOpDef(node_def.op(), &op_def));
      if (is_resource_op_with_empty_shared_name(node_def, *op_def)) {
        // Use the concat of function name and node name for such ops in a
        // function as the shared_name. "@" is used as the separator because it
        // is not allowed in the function name or the node name.
        (*node_def.mutable_attr())["shared_name"].set_s(
            absl::StrCat(node_def.name(), "@", func_name));
      }
    }
    TF_RETURN_IF_ERROR(flib_def.ReplaceFunction(func_name, copy));
  }

  return tensorflow::Status::OK();
}

}  // namespace tensorflow


text:
@implementation UIView (PrintSubviews)

- (void)printSubviewsWithIndentation:(int)indentation {

    // Get all the subviews of the current view
    NSArray *subviews = [self subviews];

    // Loop through the whole subviews array. We are using the plain-old C-like for loop,
    // just for its simplicity and also to be provided with the iteration number
    for (int i = 0; i < [subviews count]; i++) {

        // Get the subview at current index
        UIView *currentSubview = [subviews objectAtIndex:i];

        // We will create our description using this mutable string
        NSMutableString *currentViewDescription = [[NSMutableString alloc] init];

        // Indent the actual description to provide visual clue of  how deeply is the current view nested
        for (int j = 0; j <= indentation; j++) {
            [currentViewDescription appendString:@"   "];
        }

        // Construct the actual description string. Note that we are using just index of the current view
        // and name of its class, but it's up to you to print anything you are interested in
        // (for example the frame property using the NSStringFromCGRect(currentSubview.frame) )
        [currentViewDescription appendFormat:@"[%d]: class: '%@'", i, NSStringFromClass([currentSubview class])];

        // Log the description string to the console
        NSLog(@"%@", currentViewDescription);

        // the 'recursiveness' nature of this method. Call it on the current subview, with greater indentation
        [currentSubview printSubviewsWithIndentation:indentation+1];
    }
}

@end


text:
ListSort Enterprise Edition
===========================
Inspired by [this](http://codegolf.stackexchange.com/a/16296)


text:
layout: news
title: "Lab is Open Again"
date: 2019-09-05T00:00:00.000Z
categories:
  - "news"
  - "opening times"
---

Just to let you know, we are open again! The laser cutter is better than ever and we worked hard to improve the assembly room so that you can find your tools quickly.


text:
<?php

namespace Spiechu\LazyPimple;

use Spiechu\LazyPimple\Service\EventEmittingService;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class VarDumpTest extends AbstractLazyPimpleTest
{
    public function testDontKillMeForThisTest()
    {
        ob_start();

        // @var $eventDispatcher EventDispatcherInterface
        $eventDispatcher = $this->container['event_dispatcher'];

        $this->assertInstanceOf(EventDispatcherInterface::class, $eventDispatcher);
        $this->assertTrue($eventDispatcher->hasListeners(Event::FIRST_EVENT));

        // @var $eventEmittingService EventEmittingService
        $eventEmittingService = $this->container['event_emitting_service'];

        $this->assertInstanceOf(EventEmittingService::class, $eventEmittingService);

        $eventEmittingService->emit();

        $result = ob_get_clean();

        $this->assertRegExp('/^emitting first eventfirst subscriber constructor calledon first calledstatic hit calledawesome constructor calledinstance hit calledProxyManagerGeneratedProxy/i', $result);
    }
}


text:
package GSF.Hadoop.Datamining.Tools.DataProcessing;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.InvalidParameterException;

import GSF.Hadoop.Datamining.Tools.DataProcessing.ValueObjects.FrequencyClassification;

public class InstanceMaker
{
	public InstanceMaker()
	{
	}

	private void ParseFile(File inFile, int pointsPer, int deltaWindow, File outFile) throws IOException
	{
		if( 0 >= deltaWindow )
			throw new InvalidParameterException("deltaWindow must be positive.");

		int windowsComplete = 0;

		// this strategy is slow, but is easiest to program, and performance in sample generation is not important
		while(true)
		{
			try
			{
				// reset to the start of the window
				BufferedReader reader = new BufferedReader( new FileReader(inFile) );
				reader.mark(100 * pointsPer);

				// skip until we get to the next window
				// why can't i set position manually?
				int linesRead = 0;
				while( linesRead < deltaWindow * windowsComplete )
				{
					reader.readLine();
					linesRead++;
				}

				String[] timestamps = new String[pointsPer];
				String[] values = new String[pointsPer];

				int linesReadInThisWindow = 0;
				while( linesReadInThisWindow < pointsPer )
				{
					String pointString = reader.readLine();
					String[] chunks = pointString.split(",");

					timestamps[linesReadInThisWindow] = chunks[0];
					values[linesReadInThisWindow] = chunks[1];

					linesReadInThisWindow++;
				}

				reader.close();

				BufferedWriter writer = new BufferedWriter( new FileWriter(outFile, true) );

				// now write file
				//for( int i = 0; i < pointsPer; i++ )
					//writer.write(timestamps[i] + ",");
				//writer.write("\r\n");
				for( int i = 0; i < pointsPer; i++ )
				{
					writer.write(values[i]);
					if( i < pointsPer - 1 )
						writer.write(",");
				}

				writer.write(FrequencyClassification.UNCLASSIFIED.toString());

				writer.write(System.getProperty("line.separator"));
				//writer.write("\r\n");

				writer.close();

				windowsComplete++;
			}
			catch(NullPointerException e)
			{
				//e.printStackTrace();
				System.out.println("done reading " + inFile.getName());
				break;
			}
		}
	}

	public void ParseWindows(File inFile, int pointsPer, int deltaWindow, File outFile) throws IOException
	{
		// parse all blocks with a given point id in the open file/folder, write to fileName
		if( inFile.isFile() )
		{
			ParseFile(inFile, pointsPer, deltaWindow, outFile);
		}
		else
		{
			for (File file : inFile.listFiles())
				ParseWindows(file, pointsPer, deltaWindow, outFile);
		}
	}
}


text:
//
//  NSData+TTExt.h
//  TQKit
//
//  Created by 天智慧启 on 2017/6/7.
//  Copyright © 2017年 guojie. All rights reserved.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSData (TTExt)

#pragma mark - Hash
///=============================================================================
/// @name Hash
///=============================================================================

/**
 Returns a lowercase NSString for md2 hash.
 */
- (NSString *)tt_md2String;

/**
 Returns an NSData for md2 hash.
 */
- (NSData *)tt_md2Data;

/**
 Returns a lowercase NSString for md4 hash.
 */
- (NSString *)tt_md4String;

/**
 Returns an NSData for md4 hash.
 */
- (NSData *)tt_md4Data;

/**
 Returns a lowercase NSString for md5 hash.
 */
- (NSString *)tt_md5String;

/**
 Returns an NSData for md5 hash.
 */
- (NSData *)tt_md5Data;

/**
 Returns a lowercase NSString for sha1 hash.
 */
- (NSString *)tt_sha1String;

/**
 Returns an NSData for sha1 hash.
 */
- (NSData *)tt_sha1Data;

/**
 Returns a lowercase NSString for sha224 hash.
 */
- (NSString *)tt_sha224String;

/**
 Returns an NSData for sha224 hash.
 */
- (NSData *)tt_sha224Data;

/**
 Returns a lowercase NSString for sha256 hash.
 */
- (NSString *)tt_sha256String;

/**
 Returns an NSData for sha256 hash.
 */
- (NSData *)tt_sha256Data;

/**
 Returns a lowercase NSString for sha384 hash.
 */
- (NSString *)tt_sha384String;

/**
 Returns an NSData for sha384 hash.
 */
- (NSData *)tt_sha384Data;

/**
 Returns a lowercase NSString for sha512 hash.
 */
- (NSString *)tt_sha512String;

/**
 Returns an NSData for sha512 hash.
 */
- (NSData *)tt_sha512Data;

/**
 Returns a lowercase NSString for hmac using algorithm md5 with key.
 @param key  The hmac key.
 */
- (NSString *)tt_hmacMD5StringWithKey:(NSString *)key;

/**
 Returns an NSData for hmac using algorithm md5 with key.
 @param key  The hmac key.
 */
- (NSData *)tt_hmacMD5DataWithKey:(NSData *)key;

/**
 Returns a lowercase NSString for hmac using algorithm sha1 with key.
 @param key  The hmac key.
 */
- (NSString *)tt_hmacSHA1StringWithKey:(NSString *)key;

/**
 Returns an NSData for hmac using algorithm sha1 with key.
 @param key  The hmac key.
 */
- (NSData *)tt_hmacSHA1DataWithKey:(NSData *)key;

/**
 Returns a lowercase NSString for hmac using algorithm sha224 with key.
 @param key  The hmac key.
 */
- (NSString *)tt_hmacSHA224StringWithKey:(NSString *)key;

/**
 Returns an NSData for hmac using algorithm sha224 with key.
 @param key  The hmac key.
 */
- (NSData *)tt_hmacSHA224DataWithKey:(NSData *)key;

/**
 Returns a lowercase NSString for hmac using algorithm sha256 with key.
 @param key  The hmac key.
 */
- (NSString *)tt_hmacSHA256StringWithKey:(NSString *)key;

/**
 Returns an NSData for hmac using algorithm sha256 with key.
 @param key  The hmac key.
 */
- (NSData *)tt_hmacSHA256DataWithKey:(NSData *)key;

/**
 Returns a lowercase NSString for hmac using algorithm sha384 with key.
 @param key  The hmac key.
 */
- (NSString *)tt_hmacSHA384StringWithKey:(NSString *)key;

/**
 Returns an NSData for hmac using algorithm sha384 with key.
 @param key  The hmac key.
 */
- (NSData *)tt_hmacSHA384DataWithKey:(NSData *)key;

/**
 Returns a lowercase NSString for hmac using algorithm sha512 with key.
 @param key  The hmac key.
 */
- (NSString *)tt_hmacSHA512StringWithKey:(NSString *)key;

/**
 Returns an NSData for hmac using algorithm sha512 with key.
 @param key  The hmac key.
 */
- (NSData *)tt_hmacSHA512DataWithKey:(NSData *)key;

/**
 Returns a lowercase NSString for crc32 hash.
 */
- (NSString *)tt_crc32String;

/**
 Returns crc32 hash.
 */
- (uint32_t)tt_crc32;

#pragma mark - Encrypt and Decrypt
///=============================================================================
/// @name Encrypt and Decrypt
///=============================================================================

/**
 Returns an encrypted NSData using AES.

 @param key   A key length of 16, 24 or 32 (128, 192 or 256bits).

 @param iv    An initialization vector length of 16(128bits).
 Pass nil when you don't want to use iv.

 @return      An NSData encrypted, or nil if an error occurs.
 */
- (nullable NSData *)tt_aes256EncryptWithKey:(NSData *)key iv:(nullable NSData *)iv;

/**
 Returns an decrypted NSData using AES.

 @param key   A key length of 16, 24 or 32 (128, 192 or 256bits).

 @param iv    An initialization vector length of 16(128bits).
 Pass nil when you don't want to use iv.

 @return      An NSData decrypted, or nil if an error occurs.
 */
- (nullable NSData *)tt_aes256DecryptWithkey:(NSData *)key iv:(nullable NSData *)iv;

#pragma mark - Encode and decode
///=============================================================================
/// @name Encode and decode
///=============================================================================

/**
 Returns string decoded in UTF8.
 */
- (nullable NSString *)tt_utf8String;

/**
 Returns a uppercase NSString in HEX.
 */
- (nullable NSString *)tt_hexString;

/**
 Returns an NSData from hex string.

 @param hexString   The hex string which is case insensitive.

 @return a new NSData, or nil if an error occurs.
 */
+ (nullable NSData *)tt_dataWithHexString:(NSString *)hexString;

/**
 Returns an NSString for base64 encoded.
 */
- (nullable NSString *)tt_base64EncodedString;

/**
 Returns an NSData from base64 encoded string.

 @warning This method has been implemented in iOS7.

 @param base64EncodedString  The encoded string.
 */
+ (nullable NSData *)tt_dataWithBase64EncodedString:(NSString *)base64EncodedString;

/**
 Returns an NSDictionary or NSArray for decoded self.
 Returns nil if an error occurs.
 */
- (nullable id)tt_jsonValueDecoded;

#pragma mark - Inflate and deflate
///=============================================================================
/// @name Inflate and deflate
///=============================================================================

/**
 Decompress data from gzip data.
 @return Inflated data.
 */
- (nullable NSData *)tt_gzipInflate;

/**
 Comperss data to gzip in default compresssion level.
 @return Deflated data.
 */
- (nullable NSData *)tt_gzipDeflate;

/**
 Decompress data from zlib-compressed data.
 @return Inflated data.
 */
- (nullable NSData *)tt_zlibInflate;

/**
 Comperss data to zlib-compressed in default compresssion level.
 @return Deflated data.
 */
- (nullable NSData *)tt_zlibDeflate;

#pragma mark - Others
///=============================================================================
/// @name Others
///=============================================================================

/**
 Create data from the file in main bundle (similar to [UIImage imageNamed:]).

 @param name The file name (in main bundle).

 @return A new data create from the file.
 */
+ (nullable NSData *)tt_dataNamed:(NSString *)name;

@end

NS_ASSUME_NONNULL_END


text:
<?php
namespace Google\Service\Tasks;

class TaskList extends \Google\Model
{
  public $etag;
  public $id;
  public $kind;
  public $selfLink;
  public $title;
  public $updated;

  public function setEtag($etag)
  {
    $this->etag = $etag;
  }

  public function getEtag()
  {
    return $this->etag;
  }

  public function setId($id)
  {
    $this->id = $id;
  }

  public function getId()
  {
    return $this->id;
  }

  public function setKind($kind)
  {
    $this->kind = $kind;
  }

  public function getKind()
  {
    return $this->kind;
  }

  public function setSelfLink($selfLink)
  {
    $this->selfLink = $selfLink;
  }

  public function getSelfLink()
  {
    return $this->selfLink;
  }

  public function setTitle($title)
  {
    $this->title = $title;
  }

  public function getTitle()
  {
    return $this->title;
  }

  public function setUpdated($updated)
  {
    $this->updated = $updated;
  }

  public function getUpdated()
  {
    return $this->updated;
  }

}


text:
class Cassandra::Flow::Action::MatchTime < Cassandra::Flow::Action
  action!
  attr_reader :mapper, :callback, :catalog,
              :source_field, :matched_field,
              :interval

  # TIME_STEP instead of (slice: :before/after) because of uuid
  TIME_STEP = 0.001

  def setup!(mapper, options={}, &callback)
    @mapper        = mapper
    @callback      = callback
    @source_field  = options[:source] || source.config.subkey.first
    @matched_field = mapper.config.subkey.first
    @match_after   = options[:after]

    if options[:interval]
      @interval = (options[:interval] + TIME_STEP) * (match_after? ? 1 : -1)
    end

    append_name mapper.table
    append_name source_field.to_s
    append_name matched_field.to_s
    build_catalog

    mapper.config.dsl.after_insert do |match|
      key          = select(:key, match)
      matched_time = match[matched_field]

      lock key do
        records = query_catalog key, matched_time
        unless interval
          records.select! do |it|
            sign = match_after? ? :> : :<
            not it[:matched_time] or it[:matched_time].send(sign, matched_time)
          end
        end

        records.each do |record|
          prepare = { result: record[:action_result], time: record[:source_time] }
          prepare[:match] = match unless interval
          match_time :insert, key, record[:action_data], prepare
        end
      end
    end

    mapper.config.dsl.after_remove do |match|
      key          = select(:key, match)
      matched_time = match[matched_field]

      lock key do
        records = query_catalog key, matched_time
        unless interval
          records.select! {|it| it[:matched_time].to_i == matched_time.to_i }
        end

        records.each do |record|
          prepare = { result: record[:action_result], time: record[:source_time] }
          match_time :insert, key, record[:action_data], prepare
        end
      end
    end
  end

  def propagate(type, data)
    key = select(:key, data)

    if key.values.any?(&:nil?)
      propagate_next type, callback.call(data, nil)
    else
      lock key do
        match_time type, key, data
      end
    end
  end

  private

  def match_time(type, key, data, prepared_data={})
    source_time = prepared_data[:time] || data[source_field]
    error! "missing :#{source_field} in #{data.inspect}" unless source_time

    case type
    when :insert
      if prepared_data[:match]
        matched = prepared_data[:match]
      else
        query = if match_after?
            { start: { matched_field => source_time }}
          else
            # slice :after in reverse means to match including current record
            { reversed: true, start: { matched_field => source_time, slice: :after }}
          end
        if interval
          query[:finish] = { matched_field => source_time + interval }
          matched = mapper.get key, query
        else
          matched = mapper.one key, query
        end

        if interval and not match_after?
          matched.reverse!
        end
      end

      result = callback.call data, matched

      if matched and not interval
        matched_time = matched[matched_field]
      end

      catalog_record = key
      catalog_record.merge! \
        action_data:    data,
        action_result:  result,
        matched_time:   matched_time,
        source_time:    source_time
      catalog.insert catalog_record
    when :remove
      all = catalog.get key
      found = all.find {|it| it[:action_data] == data }

      if found
        result = found[:action_result]
        catalog.remove found
      end
    when :check
      all = catalog.get key
      found = all.find {|it| it[:action_data] == data }

      log_inspect key
      log_inspect found
      log_inspect all

      if found
        result = found[:action_result]
      end
    end

    previous_result = prepared_data.fetch(:result, false)
    if result != previous_result
      propagate_next :remove, previous_result if previous_result
      propagate_next type, result
    end
  end

  def build_catalog
    config = mapper.config
    @catalog = Cassandra::Mapper.new keyspace_name, name do
      key *config.key
      subkey :source_time
      type :action_data,   :marshal
      type :action_result, :marshal
      type :source_time,   :uuid
      type :matched_time,  :time
    end
  end

  def select(key_type, data)
    mapper.config.send(key_type).each_with_object({}) do |field, result|
      result[field] = data[field]
    end
  end

  def lock(key, &block)
    super name + key.values.join('.'), sleep: 1000, &block
  end

  def error!(text, error=ArgumentError)
    raise error, <<-ERROR
      #{text}
      from #{location}
      parents #{parents.map(&:location).join(', ')}
    ERROR
  end

  def match_after?
    @match_after
  end

  def rounded_time(time)
    Time.at((time.to_f * 1000).to_i / 1000.0)
  end

  def query_catalog(key, time)
    if match_after?
      query = { finish: { source_time: time + TIME_STEP }}
      if interval
        query[:start] = { source_time: time - interval }
      end
    else
      query = { start: { source_time: time - TIME_STEP }}
      if interval
        query[:finish] = { source_time: time - interval }
      end
    end

    catalog.get key, query
  end
end


text:
#ifndef _DECAF_NET_URLENCODER_H_
#define _DECAF_NET_URLENCODER_H_

#include <decaf/util/Config.h>
#include <string>

namespace decaf{
namespace net{

    class DECAF_API URLEncoder {
    private:

        static const std::string digits;

    private:

        URLEncoder();

    public:

        virtual ~URLEncoder() {}

        /**
         * This class contains a utility method for converting a string to the
         * format required by the application/x-www-form-urlencoded
         * MIME content type.
         *

         * All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
         * and characters '.', '-', '*', '_' are converted into their hexidecimal
         * value prepended by '%'.
         *

         * For example: '#' -> %23
         *

         * In addition, spaces are substituted by '+'
         *
         * @param value - the string to be converted
         * @returns the converted string
         */
        static std::string encode( const std::string& value );

    };

}}

#endif /*_DECAF_NET_URLENCODER_H_*/


text:
"""Test for ds_tc_resnet model in session mode."""
import numpy as np
from kws_streaming.layers import test_utils
from kws_streaming.layers.compat import tf
from kws_streaming.layers.compat import tf1
from kws_streaming.layers.modes import Modes
from kws_streaming.models import utils
import kws_streaming.models.ds_tc_resnet as ds_tc_resnet
from kws_streaming.train import inference

class DsTcResnetTest(tf.test.TestCase):
  """Test ds_tc_resnet model in non streaming and streaming modes."""

  def setUp(self):
    super(DsTcResnetTest, self).setUp()

    config = tf1.ConfigProto()
    config.gpu_options.allow_growth = True
    self.sess = tf1.Session(config=config)
    tf1.keras.backend.set_session(self.sess)
    tf.keras.backend.set_learning_phase(0)

    test_utils.set_seed(123)
    self.params = utils.ds_tc_resnet_model_params(True)

    self.model = ds_tc_resnet.model(self.params)
    self.model.summary()

    self.input_data = np.random.rand(self.params.batch_size,
                                     self.params.desired_samples)

    # run non streaming inference
    self.non_stream_out = self.model.predict(self.input_data)

  def test_ds_tc_resnet_stream(self):
    """Test for tf streaming with internal state."""
    # prepare tf streaming model
    model_stream = utils.to_streaming_inference(
        self.model, self.params, Modes.STREAM_INTERNAL_STATE_INFERENCE)
    model_stream.summary()

    # run streaming inference
    stream_out = inference.run_stream_inference_classification(
        self.params, model_stream, self.input_data)
    self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5)

  def test_ds_tc_resnet_stream_tflite(self):
    """Test for tflite streaming with external state."""
    tflite_streaming_model = utils.model_to_tflite(
        self.sess, self.model, self.params,
        Modes.STREAM_EXTERNAL_STATE_INFERENCE)

    interpreter = tf.lite.Interpreter(model_content=tflite_streaming_model)
    interpreter.allocate_tensors()

    # before processing new test sequence we reset model state
    inputs = []
    for detail in interpreter.get_input_details():
      inputs.append(np.zeros(detail['shape'], dtype=np.float32))

    stream_out = inference.run_stream_inference_classification_tflite(
        self.params, interpreter, self.input_data, inputs)

    self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5)

if __name__ == '__main__':
  tf1.disable_eager_execution()
  tf.test.main()


text:
using testing::_;

namespace device {

using mojom::UsbControlTransferRecipient;
using mojom::UsbControlTransferType;
using mojom::UsbSynchronizationType;
using mojom::UsbTransferDirection;
using mojom::UsbTransferStatus;
using mojom::UsbTransferType;
using mojom::UsbUsageType;

namespace {

ACTION_P2(InvokeCallback, data, length) {
  size_t transferred_length = std::min(length, arg6->size());
  memcpy(arg6->front(), data, transferred_length);
  std::move(arg8).Run(UsbTransferStatus::COMPLETED, arg6, transferred_length);
}

void ExpectStringDescriptors(
    std::unique_ptr<std::map<uint8_t, std::u16string>> string_map) {
  EXPECT_EQ(3u, string_map->size());
  EXPECT_EQ(u"String 1", (*string_map)[1]);
  EXPECT_EQ(u"String 2", (*string_map)[2]);
  EXPECT_EQ(u"String 3", (*string_map)[3]);
}

// clang-format off
const uint8_t kDeviceDescriptor[] = {0x12, 0x01, 0x10, 0x03, 0xFF, 0xFF,
                                     0xFF, 0x09, 0x34, 0x12, 0x78, 0x56,
                                     0x00, 0x01, 0x01, 0x02, 0x03, 0x02};

const uint8_t kConfig1Descriptor[] = {
    // Config 1
    0x09, 0x02, 0x38, 0x00, 0x02, 0x01, 0x01, 0x01, 0x10,
    // Interface Association (0 + 1)
    0x08, 0x0B, 0x00, 0x02, 0xFF, 0xFF, 0xFF, 0x00,
    // Interface 0
    0x09, 0x04, 0x00, 0x00, 0x03, 0x12, 0x34, 0x56, 0x02,
    // Endpoint 1 IN
    0x07, 0x05, 0x81, 0x02, 0x00, 0x02, 0x00,
    // Endpoint 2 IN
    0x07, 0x05, 0x82, 0x03, 0x00, 0x02, 0x04,
    // Endpoint 3 OUT
    0x07, 0x05, 0x03, 0x13, 0x00, 0x02, 0x04,
    // Interface 1
    0x09, 0x04, 0x01, 0x00, 0x00, 0x78, 0x9A, 0xAB, 0x03,
};

const uint8_t kConfig2Descriptor[] = {
    // Config 2
    0x09, 0x02, 0x29, 0x00, 0x01, 0x02, 0x04, 0x03, 0x20,
    // Interface 0 (alternate 0)
    0x09, 0x04, 0x00, 0x00, 0x00, 0xCD, 0xEF, 0x01, 0x04,
    // Interface 0 (alternate 1)
    0x09, 0x04, 0x00, 0x01, 0x02, 0xCD, 0xEF, 0x01, 0x05,
    // Endpoint 1 IN
    0x07, 0x05, 0x81, 0x01, 0x00, 0x04, 0x08,
    // Endpoint 2 OUT
    0x07, 0x05, 0x02, 0x11, 0x00, 0x04, 0x08,
};
// clang-format on

void ExpectConfig1Info(const mojom::UsbConfigurationInfo& config) {
  // Config 1
  EXPECT_EQ(1, config.configuration_value);
  EXPECT_FALSE(config.self_powered);
  EXPECT_FALSE(config.remote_wakeup);
  EXPECT_EQ(16, config.maximum_power);
  ASSERT_EQ(2u, config.interfaces.size());
  EXPECT_EQ(8u, config.extra_data.size());
  // Interface 0
  EXPECT_EQ(0, config.interfaces[0]->interface_number);
  EXPECT_EQ(0, config.interfaces[0]->first_interface);
  const auto& alternate = config.interfaces[0]->alternates[0];
  EXPECT_EQ(0, alternate->alternate_setting);
  EXPECT_EQ(0x12, alternate->class_code);
  EXPECT_EQ(0x34, alternate->subclass_code);
  EXPECT_EQ(0x56, alternate->protocol_code);
  ASSERT_EQ(3u, alternate->endpoints.size());
  EXPECT_EQ(0u, alternate->extra_data.size());

  // Endpoint 1 IN
  EXPECT_EQ(0x01, alternate->endpoints[0]->endpoint_number);
  EXPECT_EQ(UsbTransferDirection::INBOUND, alternate->endpoints[0]->direction);
  EXPECT_EQ(512u, alternate->endpoints[0]->packet_size);
  EXPECT_EQ(UsbSynchronizationType::NONE,
            alternate->endpoints[0]->synchronization_type);
  EXPECT_EQ(UsbTransferType::BULK, alternate->endpoints[0]->type);
  EXPECT_EQ(UsbUsageType::RESERVED, alternate->endpoints[0]->usage_type);
  EXPECT_EQ(0, alternate->endpoints[0]->polling_interval);
  EXPECT_EQ(0u, alternate->endpoints[0]->extra_data.size());
  // Endpoint 2 IN
  EXPECT_EQ(0x02, alternate->endpoints[1]->endpoint_number);
  EXPECT_EQ(UsbTransferDirection::INBOUND, alternate->endpoints[1]->direction);
  EXPECT_EQ(512u, alternate->endpoints[1]->packet_size);
  EXPECT_EQ(UsbSynchronizationType::NONE,
            alternate->endpoints[1]->synchronization_type);
  EXPECT_EQ(UsbTransferType::INTERRUPT, alternate->endpoints[1]->type);
  EXPECT_EQ(UsbUsageType::PERIODIC, alternate->endpoints[1]->usage_type);
  EXPECT_EQ(4, alternate->endpoints[1]->polling_interval);
  EXPECT_EQ(0u, alternate->endpoints[1]->extra_data.size());
  // Endpoint 3 OUT
  EXPECT_EQ(0x03, alternate->endpoints[2]->endpoint_number);
  EXPECT_EQ(UsbTransferDirection::OUTBOUND, alternate->endpoints[2]->direction);
  EXPECT_EQ(512u,
            config.interfaces[0]->alternates[0]->endpoints[2]->packet_size);
  EXPECT_EQ(UsbSynchronizationType::NONE,
            alternate->endpoints[2]->synchronization_type);
  EXPECT_EQ(UsbTransferType::INTERRUPT, alternate->endpoints[2]->type);
  EXPECT_EQ(UsbUsageType::NOTIFICATION, alternate->endpoints[2]->usage_type);
  EXPECT_EQ(4, alternate->endpoints[2]->polling_interval);
  EXPECT_EQ(0u, alternate->endpoints[2]->extra_data.size());
  // Interface 1
  EXPECT_EQ(1, config.interfaces[1]->interface_number);
  EXPECT_EQ(0, config.interfaces[1]->first_interface);
  EXPECT_EQ(0, config.interfaces[1]->alternates[0]->alternate_setting);
  EXPECT_EQ(0x78, config.interfaces[1]->alternates[0]->class_code);
  EXPECT_EQ(0x9A, config.interfaces[1]->alternates[0]->subclass_code);
  EXPECT_EQ(0xAB, config.interfaces[1]->alternates[0]->protocol_code);
  ASSERT_EQ(0u, config.interfaces[1]->alternates[0]->endpoints.size());
  EXPECT_EQ(0u, config.interfaces[1]->alternates[0]->extra_data.size());
}

void ExpectConfig2Info(const mojom::UsbConfigurationInfo& config) {
  // Config 2
  EXPECT_EQ(2, config.configuration_value);
  EXPECT_TRUE(config.self_powered);
  EXPECT_FALSE(config.remote_wakeup);
  EXPECT_EQ(32, config.maximum_power);
  ASSERT_EQ(1u, config.interfaces.size());
  ASSERT_EQ(2u, config.interfaces[0]->alternates.size());
  EXPECT_EQ(0u, config.extra_data.size());
  // Interface 0
  EXPECT_EQ(0, config.interfaces[0]->interface_number);
  EXPECT_EQ(0, config.interfaces[0]->alternates[0]->alternate_setting);
  EXPECT_EQ(0xCD, config.interfaces[0]->alternates[0]->class_code);
  EXPECT_EQ(0xEF, config.interfaces[0]->alternates[0]->subclass_code);
  EXPECT_EQ(0x01, config.interfaces[0]->alternates[0]->protocol_code);
  ASSERT_EQ(0u, config.interfaces[0]->alternates[0]->endpoints.size());
  EXPECT_EQ(0u, config.interfaces[0]->alternates[0]->extra_data.size());
  EXPECT_EQ(0, config.interfaces[0]->first_interface);
  // Interface 0 (alternate 1)
  const auto& alternate = config.interfaces[0]->alternates[1];
  EXPECT_EQ(1, alternate->alternate_setting);
  EXPECT_EQ(0xCD, alternate->class_code);
  EXPECT_EQ(0xEF, alternate->subclass_code);
  EXPECT_EQ(0x01, alternate->protocol_code);
  ASSERT_EQ(2u, alternate->endpoints.size());
  EXPECT_EQ(0u, alternate->extra_data.size());
  // Endpoint 1 IN
  EXPECT_EQ(0x01, alternate->endpoints[0]->endpoint_number);
  EXPECT_EQ(UsbTransferDirection::INBOUND, alternate->endpoints[0]->direction);
  EXPECT_EQ(1024u, alternate->endpoints[0]->packet_size);
  EXPECT_EQ(UsbSynchronizationType::NONE,
            alternate->endpoints[0]->synchronization_type);
  EXPECT_EQ(UsbTransferType::ISOCHRONOUS, alternate->endpoints[0]->type);
  EXPECT_EQ(UsbUsageType::DATA, alternate->endpoints[0]->usage_type);
  EXPECT_EQ(8, alternate->endpoints[0]->polling_interval);
  EXPECT_EQ(0u, alternate->endpoints[0]->extra_data.size());
  // Endpoint 2 OUT
  EXPECT_EQ(0x02, alternate->endpoints[1]->endpoint_number);
  EXPECT_EQ(UsbTransferDirection::OUTBOUND, alternate->endpoints[1]->direction);
  EXPECT_EQ(1024u, alternate->endpoints[1]->packet_size);
  EXPECT_EQ(UsbSynchronizationType::NONE,
            alternate->endpoints[1]->synchronization_type);
  EXPECT_EQ(UsbTransferType::ISOCHRONOUS, alternate->endpoints[1]->type);
  EXPECT_EQ(UsbUsageType::FEEDBACK, alternate->endpoints[1]->usage_type);
  EXPECT_EQ(8, alternate->endpoints[1]->polling_interval);
  EXPECT_EQ(0u, alternate->endpoints[1]->extra_data.size());
}

void ExpectDeviceDescriptor(const UsbDeviceDescriptor& descriptor) {
  // Device
  EXPECT_EQ(0x03, descriptor.device_info->usb_version_major);
  EXPECT_EQ(0x01, descriptor.device_info->usb_version_minor);
  EXPECT_EQ(0x00, descriptor.device_info->usb_version_subminor);
  EXPECT_EQ(0xFF, descriptor.device_info->class_code);
  EXPECT_EQ(0xFF, descriptor.device_info->subclass_code);
  EXPECT_EQ(0xFF, descriptor.device_info->protocol_code);
  EXPECT_EQ(0x1234, descriptor.device_info->vendor_id);
  EXPECT_EQ(0x5678, descriptor.device_info->product_id);
  EXPECT_EQ(0x01, descriptor.device_info->device_version_major);
  EXPECT_EQ(0x00, descriptor.device_info->device_version_minor);
  EXPECT_EQ(0x00, descriptor.device_info->device_version_subminor);
  ASSERT_EQ(2u, descriptor.device_info->configurations.size());
  ExpectConfig1Info(*descriptor.device_info->configurations[0]);
  ExpectConfig2Info(*descriptor.device_info->configurations[1]);
}

void OnReadDescriptors(std::unique_ptr<UsbDeviceDescriptor> descriptor) {
  ASSERT_TRUE(descriptor);
  ExpectDeviceDescriptor(*descriptor);
}

class UsbDescriptorsTest : public ::testing::Test {};

TEST_F(UsbDescriptorsTest, ParseDescriptor) {
  std::vector<uint8_t> buffer;
  buffer.insert(buffer.end(), kDeviceDescriptor,
                kDeviceDescriptor + sizeof(kDeviceDescriptor));
  buffer.insert(buffer.end(), kConfig1Descriptor,
                kConfig1Descriptor + sizeof(kConfig1Descriptor));
  buffer.insert(buffer.end(), kConfig2Descriptor,
                kConfig2Descriptor + sizeof(kConfig2Descriptor));

  UsbDeviceDescriptor descriptor;
  ASSERT_TRUE(descriptor.Parse(buffer));
  ExpectDeviceDescriptor(descriptor);
}

TEST_F(UsbDescriptorsTest, ReadDescriptors) {
  scoped_refptr<MockUsbDeviceHandle> device_handle(
      new MockUsbDeviceHandle(nullptr));
  EXPECT_CALL(*device_handle,
              ControlTransferInternal(UsbTransferDirection::INBOUND,
                                      UsbControlTransferType::STANDARD,
                                      UsbControlTransferRecipient::DEVICE, 0x06,
                                      0x0100, 0x0000, _, _, _))
      .WillOnce(InvokeCallback(kDeviceDescriptor, sizeof(kDeviceDescriptor)));
  EXPECT_CALL(*device_handle,
              ControlTransferInternal(UsbTransferDirection::INBOUND,
                                      UsbControlTransferType::STANDARD,
                                      UsbControlTransferRecipient::DEVICE, 0x06,
                                      0x0200, 0x0000, _, _, _))
      .Times(2)
      .WillRepeatedly(
          InvokeCallback(kConfig1Descriptor, sizeof(kConfig1Descriptor)));
  EXPECT_CALL(*device_handle,
              ControlTransferInternal(UsbTransferDirection::INBOUND,
                                      UsbControlTransferType::STANDARD,
                                      UsbControlTransferRecipient::DEVICE, 0x06,
                                      0x0201, 0x0000, _, _, _))
      .Times(2)
      .WillRepeatedly(
          InvokeCallback(kConfig2Descriptor, sizeof(kConfig2Descriptor)));

  ReadUsbDescriptors(device_handle, base::BindOnce(&OnReadDescriptors));
}

TEST_F(UsbDescriptorsTest, NoInterfaceAssociations) {
  mojom::UsbConfigurationInfoPtr config =
      BuildUsbConfigurationInfoPtr(1, false, false, 0);
  config->interfaces.push_back(BuildUsbInterfaceInfoPtr(0, 0, 255, 255, 255));
  config->interfaces.push_back(BuildUsbInterfaceInfoPtr(0, 1, 255, 255, 255));
  config->interfaces.push_back(BuildUsbInterfaceInfoPtr(1, 0, 255, 255, 255));
  AssignFirstInterfaceNumbers(config.get());

  EXPECT_EQ(0, config->interfaces[0]->first_interface);
  EXPECT_EQ(0, config->interfaces[1]->first_interface);
  EXPECT_EQ(1, config->interfaces[2]->first_interface);
}

TEST_F(UsbDescriptorsTest, InterfaceAssociations) {
  // Links interfaces 0 and 1 into a single function.
  static const uint8_t kIAD1[] = {0x08, 0x0b, 0x00, 0x02,
                                  0xff, 0xff, 0xff, 0x00};
  // Only references a single interface, 2.
  static const uint8_t kIAD2[] = {0x08, 0x0b, 0x02, 0x01,
                                  0xff, 0xff, 0xff, 0x00};
  // Malformed. References interface 3 but bInterfaceCount is 0.
  static const uint8_t kIAD3[] = {0x08, 0x0b, 0x03, 0x00,
                                  0xff, 0xff, 0xff, 0x00};
  // Links interfaces 4 and 5 into a single function.
  static const uint8_t kIAD4[] = {0x08, 0x0b, 0x04, 0x02,
                                  0xff, 0xff, 0xff, 0x00};

  mojom::UsbConfigurationInfoPtr config =
      BuildUsbConfigurationInfoPtr(1, false, false, 0);
  config->extra_data.assign(kIAD1, kIAD1 + sizeof(kIAD1));
  config->extra_data.insert(config->extra_data.end(), kIAD2,
                            kIAD2 + sizeof(kIAD2));
  config->interfaces.push_back(BuildUsbInterfaceInfoPtr(0, 0, 255, 255, 255));
  config->interfaces.push_back(BuildUsbInterfaceInfoPtr(1, 0, 255, 255, 255));
  mojom::UsbInterfaceInfoPtr iface1a =
      BuildUsbInterfaceInfoPtr(1, 1, 255, 255, 255);
  iface1a->alternates[0]->extra_data.assign(kIAD3, kIAD3 + sizeof(kIAD3));
  config->interfaces.push_back(std::move(iface1a));
  config->interfaces.push_back(BuildUsbInterfaceInfoPtr(2, 0, 255, 255, 255));
  config->interfaces.push_back(BuildUsbInterfaceInfoPtr(3, 0, 255, 255, 255));
  mojom::UsbInterfaceInfoPtr iface4 =
      BuildUsbInterfaceInfoPtr(4, 0, 255, 255, 255);
  iface4->alternates[0]->extra_data.assign(kIAD4, kIAD4 + sizeof(kIAD4));
  config->interfaces.push_back(std::move(iface4));
  config->interfaces.push_back(BuildUsbInterfaceInfoPtr(5, 0, 255, 255, 255));
  AssignFirstInterfaceNumbers(config.get());

  // Interfaces 0 and 1 (plus 1's alternate) are a single function.
  EXPECT_EQ(0, config->interfaces[0]->interface_number);
  EXPECT_EQ(0, config->interfaces[0]->first_interface);
  EXPECT_EQ(1, config->interfaces[1]->interface_number);
  EXPECT_EQ(0, config->interfaces[1]->first_interface);
  EXPECT_EQ(1, config->interfaces[2]->interface_number);
  EXPECT_EQ(0, config->interfaces[2]->first_interface);

  // Interfaces 2 and 3 are their own functions.
  EXPECT_EQ(2, config->interfaces[3]->interface_number);
  EXPECT_EQ(2, config->interfaces[3]->first_interface);
  EXPECT_EQ(3, config->interfaces[4]->interface_number);
  EXPECT_EQ(3, config->interfaces[4]->first_interface);

  // Interfaces 4 and 5 are a single function.
  EXPECT_EQ(4, config->interfaces[5]->interface_number);
  EXPECT_EQ(4, config->interfaces[5]->first_interface);
  EXPECT_EQ(5, config->interfaces[6]->interface_number);
  EXPECT_EQ(4, config->interfaces[6]->first_interface);
}

TEST_F(UsbDescriptorsTest, CorruptInterfaceAssociations) {
  {
    // Descriptor is too short.
    static const uint8_t kIAD[] = {0x01};
    mojom::UsbConfigurationInfoPtr config =
        BuildUsbConfigurationInfoPtr(1, false, false, 0);
    config->extra_data.assign(kIAD, kIAD + sizeof(kIAD));
    AssignFirstInterfaceNumbers(config.get());
  }
  {
    // Descriptor is too long.
    static const uint8_t kIAD[] = {0x09, 0x0b, 0x00, 0x00,
                                   0x00, 0x00, 0x00, 0x00};
    mojom::UsbConfigurationInfoPtr config =
        BuildUsbConfigurationInfoPtr(1, false, false, 0);
    config->extra_data.assign(kIAD, kIAD + sizeof(kIAD));
    AssignFirstInterfaceNumbers(config.get());
  }
  {
    // References an undefined interface.
    static const uint8_t kIAD[] = {0x08, 0x0b, 0x07, 0x00,
                                   0xff, 0xff, 0xff, 0x00};
    mojom::UsbConfigurationInfoPtr config =
        BuildUsbConfigurationInfoPtr(1, false, false, 0);
    config->interfaces.push_back(BuildUsbInterfaceInfoPtr(0, 0, 255, 255, 255));
    config->extra_data.assign(kIAD, kIAD + sizeof(kIAD));
    AssignFirstInterfaceNumbers(config.get());

    EXPECT_EQ(0, config->interfaces[0]->interface_number);
    EXPECT_EQ(0, config->interfaces[0]->first_interface);
  }
}

TEST_F(UsbDescriptorsTest, StringDescriptor) {
  static const uint8_t kBuffer[] = {0x1a, 0x03, 'H', 0, 'e', 0, 'l', 0, 'l', 0,
                                    'o',  0,    ' ', 0, 'w', 0, 'o', 0, 'r', 0,
                                    'l',  0,    'd', 0, '!', 0};
  std::u16string string;
  ASSERT_TRUE(ParseUsbStringDescriptor(
      std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)), &string));
  EXPECT_EQ(u"Hello world!", string);
}

TEST_F(UsbDescriptorsTest, ShortStringDescriptorHeader) {
  // The buffer is just too darn short.
  static const uint8_t kBuffer[] = {0x01};
  std::u16string string;
  ASSERT_FALSE(ParseUsbStringDescriptor(
      std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)), &string));
}

TEST_F(UsbDescriptorsTest, ShortStringDescriptor) {
  // The buffer is just too darn short.
  static const uint8_t kBuffer[] = {0x01, 0x03};
  std::u16string string;
  ASSERT_FALSE(ParseUsbStringDescriptor(
      std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)), &string));
}

TEST_F(UsbDescriptorsTest, OddLengthStringDescriptor) {
  // There's an extra byte at the end of the string.
  static const uint8_t kBuffer[] = {0x0d, 0x03, 'H', 0,   'e', 0,  'l',
                                    0,    'l',  0,   'o', 0,   '!'};
  std::u16string string;
  ASSERT_TRUE(ParseUsbStringDescriptor(
      std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)), &string));
  EXPECT_EQ(u"Hello", string);
}

TEST_F(UsbDescriptorsTest, EmptyStringDescriptor) {
  // The string is empty.
  static const uint8_t kBuffer[] = {0x02, 0x03};
  std::u16string string;
  ASSERT_TRUE(ParseUsbStringDescriptor(
      std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)), &string));
  EXPECT_EQ(std::u16string(), string);
}

TEST_F(UsbDescriptorsTest, OneByteStringDescriptor) {
  // The string is only one byte.
  static const uint8_t kBuffer[] = {0x03, 0x03, '?'};
  std::u16string string;
  ASSERT_TRUE(ParseUsbStringDescriptor(
      std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)), &string));
  EXPECT_EQ(std::u16string(), string);
}

TEST_F(UsbDescriptorsTest, ReadStringDescriptors) {
  std::unique_ptr<std::map<uint8_t, std::u16string>> string_map(
      new std::map<uint8_t, std::u16string>());
  (*string_map)[1] = std::u16string();
  (*string_map)[2] = std::u16string();
  (*string_map)[3] = std::u16string();

  scoped_refptr<MockUsbDeviceHandle> device_handle(
      new MockUsbDeviceHandle(nullptr));
  static const uint8_t kStringDescriptor0[] = {0x04, 0x03, 0x21, 0x43};
  EXPECT_CALL(*device_handle,
              ControlTransferInternal(UsbTransferDirection::INBOUND,
                                      UsbControlTransferType::STANDARD,
                                      UsbControlTransferRecipient::DEVICE, 0x06,
                                      0x0300, 0x0000, _, _, _))
      .WillOnce(InvokeCallback(kStringDescriptor0, sizeof(kStringDescriptor0)));
  static const uint8_t kStringDescriptor1[] = {0x12, 0x03, 'S', 0, 't', 0,
                                               'r',  0,    'i', 0, 'n', 0,
                                               'g',  0,    ' ', 0, '1', 0};
  EXPECT_CALL(*device_handle,
              ControlTransferInternal(UsbTransferDirection::INBOUND,
                                      UsbControlTransferType::STANDARD,
                                      UsbControlTransferRecipient::DEVICE, 0x06,
                                      0x0301, 0x4321, _, _, _))
      .WillOnce(InvokeCallback(kStringDescriptor1, sizeof(kStringDescriptor1)));
  static const uint8_t kStringDescriptor2[] = {0x12, 0x03, 'S', 0, 't', 0,
                                               'r',  0,    'i', 0, 'n', 0,
                                               'g',  0,    ' ', 0, '2', 0};
  EXPECT_CALL(*device_handle,
              ControlTransferInternal(UsbTransferDirection::INBOUND,
                                      UsbControlTransferType::STANDARD,
                                      UsbControlTransferRecipient::DEVICE, 0x06,
                                      0x0302, 0x4321, _, _, _))
      .WillOnce(InvokeCallback(kStringDescriptor2, sizeof(kStringDescriptor2)));
  static const uint8_t kStringDescriptor3[] = {0x12, 0x03, 'S', 0, 't', 0,
                                               'r',  0,    'i', 0, 'n', 0,
                                               'g',  0,    ' ', 0, '3', 0};
  EXPECT_CALL(*device_handle,
              ControlTransferInternal(UsbTransferDirection::INBOUND,
                                      UsbControlTransferType::STANDARD,
                                      UsbControlTransferRecipient::DEVICE, 0x06,
                                      0x0303, 0x4321, _, _, _))
      .WillOnce(InvokeCallback(kStringDescriptor3, sizeof(kStringDescriptor3)));

  ReadUsbStringDescriptors(device_handle, std::move(string_map),
                           base::BindOnce(&ExpectStringDescriptors));
}

}  // namespace

}  // namespace device


text:
[![Build Status](https://img.shields.io/travis/wooorm/vfile.svg)](https://travis-ci.org/wooorm/vfile) [![Coverage Status](https://img.shields.io/codecov/c/github/wooorm/vfile.svg)](https://codecov.io/github/wooorm/vfile)

**VFile** is a virtual file format used by [**retext**](https://github.com/wooorm/retext)
(natural language) and [**remark**](https://github.com/wooorm/remark)
(markdown). Two processors which parse, transform, and compile text. Both need
a virtual representation of files and a place to store metadata and messages.
And, they work in the browser. **VFile** provides these requirements.

Also, **VFile** exposes a warning mechanism compatible with [**ESLint**](https://github.com/eslint/eslint)s
formatters, making it easy to expose [stylish](https://github.com/eslint/eslint/blob/master/lib/formatters/stylish.js)
warnings, or export [tap](https://github.com/eslint/eslint/blob/master/lib/formatters/tap.js)
compliant messages.

> **VFile** is different from (the excellent :+1:) [**vinyl**](https://github.com/wearefractal/vinyl)
> in that it does not include file-system or node-only functionality. No
> buffers, streams, or stats. In addition, the focus on
> [metadata](#vfilenamespacekey) and [messages](#vfilemessagereason-position-ruleid)
> are useful when processing a file through a
> [middleware](https://github.com/segmentio/ware) pipeline.

## Installation

[npm](https://docs.npmjs.com/cli/install):

```bash
npm install vfile
```

**VFile** is also available for [duo](http://duojs.org/#getting-started),
and as an AMD, CommonJS, and globals module, [uncompressed and
compressed](https://github.com/wooorm/vfile/releases).

## Table of Contents

*   [Usage](#usage)

*   [Related Tools](#related-tools)

*   [API](#api)

    *   [VFile()](#vfile-1)
    *   [VFile#contents](#vfilecontents)
    *   [VFile#directory](#vfiledirectory)
    *   [VFile#filename](#vfilefilename)
    *   [VFile#extension](#vfileextension)
    *   [VFile#basename()](#vfilebasename)
    *   [VFile#quiet](#vfilequiet)
    *   [VFile#messages](#vfilemessages)
    *   [VFile#history](#vfilehistory)
    *   [VFile#toString()](#vfiletostring)
    *   [VFile#filePath()](#vfilefilepath)
    *   [VFile#move(options)](#vfilemoveoptions)
    *   [VFile#namespace(key)](#vfilenamespacekey)
    *   [VFile#message(reason\[, position\[, ruleId\]\])](#vfilemessagereason-position-ruleid)
    *   [VFile#warn(reason\[, position\[, ruleId\]\])](#vfilewarnreason-position-ruleid)
    *   [VFile#fail(reason\[, position\[, ruleId\]\])](#vfilefailreason-position-ruleid)
    *   [VFile#hasFailed()](#vfilehasfailed)
    *   [VFileMessage](#vfilemessage)

*   [License](#license)

## Usage

```js
var VFile = require('vfile');

var file = new VFile({
  'directory': '~',
  'filename': 'example',
  'extension': 'txt',
  'contents': 'Foo *bar* baz'
});

file.toString(); // 'Foo *bar* baz'
file.filePath(); // '~/example.txt'

file.move({'extension': 'md'});
file.filePath(); // '~/example.md'

file.warn('Something went wrong', {'line': 1, 'column': 3});
// { [~/example.md:1:3: Something went wrong]
//   name: '~/example.md:1:3',
//   file: '~/example.md',
//   reason: 'Something went wrong',
//   line: 1,
//   column: 3,
//   fatal: false }
```

## Related Tools

[**VFile**](#api)s are used by both [**retext**](https://github.com/wooorm/retext)
and [**remark**](https://github.com/wooorm/remark).

In addition, here's a list of useful tools:

*   [`dustinspecker/convert-vinyl-to-vfile`](https://github.com/dustinspecker/convert-vinyl-to-vfile)
    — Convert a [Vinyl](https://github.com/wearefractal/vinyl) file to a VFile;

*   [`shinnn/is-vfile-message`](https://github.com/shinnn/is-vfile-message)
    — Check if a value is a `VFileMessage` object;

*   [`wooorm/to-vfile`](https://github.com/wooorm/to-vfile)
    — Create a virtual file from a file-path;

*   [`wooorm/vfile-find-down`](https://github.com/wooorm/vfile-find-down)
    — Find one or more files by searching the file system downwards;

*   [`wooorm/vfile-find-up`](https://github.com/wooorm/vfile-find-up)
    — Find one or more files by searching the file system upwards;

*   [`wooorm/vfile-location`](https://github.com/wooorm/vfile-location)
    — Convert between positions (line and column-based) and offsets
    (range-based) locations;

*   [`shinnn/vfile-messages-to-vscode-diagnostics`](https://github.com/shinnn/vfile-messages-to-vscode-diagnostics)
    — Convert `VFileMessage`s into an array of VS Code diagnostics;

*   [`wooorm/vfile-reporter`](https://github.com/wooorm/vfile-reporter)
    — Stylish reporter for virtual files.

*   [`wooorm/vfile-sort`](https://github.com/wooorm/vfile-sort)
    — Sort virtual file messages by line/column;

## API

### `VFile()`

**VFile** objects make it easy to move files, to trigger warnings and
errors, and to store supplementary metadata relating to files, all without
accessing the file-system.

**Example**:

```js
var file = new VFile({
  'directory': '~',
  'filename': 'example',
  'extension': 'txt',
  'contents': 'Foo *bar* baz'
});

file === VFile(file); // true
file === new VFile(file); // true

VFile('foo') instanceof VFile; // true
```

**Signatures**:

*   `file = VFile(contents|options|vFile?)`.

**Parameters**:

*   `contents` (`string`) — Contents of the file;

*   `vFile` (`VFile`) — Existing representation, returned without modification;

*   `options` (`Object`):

    *   `directory` (`string?`, default: `''`)
        — Parent directory;

    *   `filename` (`string?`, default: `''`)
        — Name, without extension;

    *   `extension` (`string?`, default: `''`)
        — Extension(s), without initial dot;

    *   `contents` (`string?`, default: `''`)
        — Raw value.

**Returns**:

`vFile` — Instance.

**Notes**:

`VFile` exposes an interface compatible with ESLint's formatters.  For example,
to expose warnings using ESLint's `compact` formatter, execute the following:

```javascript
var compact = require('eslint/lib/formatters/compact');
var VFile = require('vfile');

var vFile = new VFile({
    'directory': '~',
    'filename': 'hello',
    'extension': 'txt'
});

vFile.warn('Whoops, something happened!');

console.log(compact([vFile]));
```

Which would yield the following:

```text
~/hello.txt: line 0, col 0, Warning - Whoops, something happened!

1 problem
```

### `VFile#contents`

`string` — Content of file.

### `VFile#directory`

`string` — Path to parent directory.

### `VFile#filename`

`string` — Filename. A file-path can still be generated when no filename exists.

### `VFile#extension`

`string` — Extension. A file-path can still be generated when no extension
exists.

### `VFile#basename()`

Get the filename, with extension, if applicable.

**Example**:

```js
var file = new VFile({
  'directory': '~',
  'filename': 'example',
  'extension': 'txt'
});

file.basename() // example.txt
```

**Signatures**:

*   `string = vFile.basename()`.

**Returns**:

`string`— Returns the file path without a directory, if applicable.
Otherwise,an empty string is returned.

### `VFile#quiet`

`boolean?` — Whether an error created by [`VFile#fail()`](#vfilemessagereason-position-ruleid)
is returned (when truthy) or thrown (when falsey).

Ensure all `messages` associated with a file are handled properly when setting
this to `true`.

### `VFile#messages`

`Array.<VFileMessage>` — List of associated messages.

**Notes**:

`VFile#message()`, and in turn `VFile#warn()` and `VFile#fail()`, return
`Error` objects that adhere to the [`VFileMessage`](#vfilemessage) schema.
Its results can populate `messages`.

### `VFile#history`

`Array.<String>` — List of file-paths the file [`move`](#vfilemoveoptions)d
between.

### `VFile#toString()`

Get the value of the file.

**Example**:

```js
var vFile = new VFile('Foo');
String(vFile); // 'Foo'
```

**Signatures**:

*   `string = vFile.toString()`.

**Returns**:

`string` — Contents.

### `VFile#filePath()`

Get the filename, with extension and directory, if applicable.

**Example**:

```js
var file = new VFile({
  'directory': '~',
  'filename': 'example',
  'extension': 'txt'
});

String(file.filePath); // ~/example.txt
file.filePath() // ~/example.txt
```

**Signatures**:

*   `string = vFile.filePath()`.

**Returns**:

`string` — If the `vFile` has a `filename`, it will be prefixed with the
directory (slashed), if applicable, and suffixed with the (dotted) extension
(if applicable).  Otherwise, an empty string is returned.

### `VFile#move(options)`

Move a file by passing a new directory, filename, and extension.  When these
are not given, the default values are kept.

**Example**:

```js
var file = new VFile({
  'directory': '~',
  'filename': 'example',
  'extension': 'txt',
  'contents': 'Foo *bar* baz'
});

file.move({'directory': '/var/www'});
file.filePath(); // '/var/www/example.txt'

file.move({'extension': 'md'});
file.filePath(); // '/var/www/example.md'
```

**Signatures**:

*   `vFile = vFile.move(options?)`.

**Parameters**:

*   `options` (`Object`):

    *   `directory` (`string`, default: `''`)
        — Parent directory;

    *   `filename` (`string?`, default: `''`)
        — Name, without extension;

    *   `extension` (`string`, default: `''`)
        — Extension(s), without initial dot.

**Returns**:

`vFile` — Context object (chainable).

### `VFile#namespace(key)`

Access metadata.

**Example**:

```js
var file = new VFile('Foo');

file.namespace('foo').bar = 'baz';

console.log(file.namespace('foo').bar) // 'baz';
```

**Parameters**:

*   `key` (`string`) — Namespace key.

**Returns**:

`Object` — Private namespace for metadata.

### `VFile#message(reason[, position[, ruleId]])`

Create a message with `reason` at `position`. When an error is passed in as
`reason`, copies the stack. This does not add a message to `messages`.

**Example**:

```js
var file = new VFile();

file.message('Something went wrong');
// { [1:1: Something went wrong]
//   name: '1:1',
//   file: '',
//   reason: 'Something went wrong',
//   line: null,
//   column: null }
```

**Signatures**:

*   `VFileMessage = vFile.message(err|reason, node|location|position?,
    ruleId?)`.

**Parameters**:

*   `err` (`Error`) — Original error, whose stack and message are used;

*   `reason` (`string`) — Reason for message;

*   `node` (`Node`) — Syntax tree object;

*   `location` (`Object`) — Syntax tree location (found at `node.position`);

*   `position` (`Object`) — Syntax tree position (found at
    `node.position.start` or `node.position.end`).

*   `ruleId` (`string`) — Category of warning.

**Returns**:

[`VFileMessage`](#vfilemessage) — File-related message with location
information.

### `VFile#warn(reason[, position[, ruleId]])`

Warn. Creates a non-fatal message (see [`VFile#message()`](#vfilemessagereason-position-ruleid)),
and adds it to the file's [`messages`](#vfilemessages) list.

**Example**:

```js
var file = new VFile();

file.warn('Something went wrong');
// { [1:1: Something went wrong]
//   name: '1:1',
//   file: '',
//   reason: 'Something went wrong',
//   line: null,
//   column: null,
//   fatal: false }
```

**See**:

*   [`VFile#message`](#vfilemessagereason-position-ruleid)

### `VFile#fail(reason[, position[, ruleId]])`

Fail. Creates a fatal message (see `VFile#message()`), sets `fatal: true`,
adds it to the file's `messages` list.

If `quiet` is not `true`, throws the error.

**Example**:

```js
var file = new VFile();

file.fail('Something went wrong');
// 1:1: Something went wrong
//     at VFile.exception (vfile/index.js:296:11)
//     at VFile.fail (vfile/index.js:360:20)
//     at repl:1:6

file.quiet = true;
file.fail('Something went wrong');
// { [1:1: Something went wrong]
//   name: '1:1',
//   file: '',
//   reason: 'Something went wrong',
//   line: null,
//   column: null,
//   fatal: true }
```

**See**:

*   [`VFile#message`](#vfilemessagereason-position-ruleid)

### `VFile#hasFailed()`

Check if a fatal message occurred making the file no longer processable.

**Example**:

```js
var file = new VFile();
file.quiet = true;

file.hasFailed(); // false

file.fail('Something went wrong');
file.hasFailed(); // true
```

**Signatures**:

*   `boolean = vFile.hasFailed()`.

**Returns**:

`boolean` — `true` if at least one of file's `messages` has a `fatal`
property set to `true`.

### `VFileMessage`

`Error` — File-related message with location information.

**Properties**:

*   `name` (`string`)
    — (Starting) location of the message, preceded by its file-path when
    available, and joined by `':'`. Used by the native
    [`Error#toString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/name);

*   `file` (`string`) — File-path;

*   `reason` (`string`) — Reason for message;

*   `line` (`number?`) — Line of error, when available;

*   `column` (`number?`) — Column of error, when available;

*   `stack` (`string?`) — Stack of message, when available;

*   `fatal` (`boolean?`) — Whether the associated file is still processable.

*   `location` (`object`) — Full range information, when available. Has
    `start` and `end` properties, both set to an object with `line` and
    `column`, set to `number?`.

## License

[MIT](LICENSE) © [Titus Wormer](http://wooorm.com)


text:
/*******************************************************************************
 * @author: eschuhmacher
 *
 * scripts to be included on the html file
 * <script src="../js/widgets/lib/RGraph/libraries/RGraph.common.core.js" ></script>
 * <script type="text/javascript" language="javascript" src="../js/widgets/progressbar.js"></script>
 * <script src="../js/widgets/lib/RGraph/excanvas/excanvas.js"></script>
 * <script src="../js/widgets/lib/RGraph/libraries/RGraph.hprogress.js" ></script>
 * <script src="../js/widgets/lib/jquery-2.0.3.min.js"></script>
 ******************************************************************************/

$(document).ready(function() {
	var nodes = document.getElementsByClassName("progressbar");
	var len = nodes.length;
    var progressbars = {};
	for ( var i = 0; i < len; i++) {
        var channelname = nodes[i].getAttribute("data-channel");
        var readOnly = nodes[i].getAttribute("data-channel-readonly");
        var id='rgraph-hprogress-'+i;
        nodes[i].innerHTML = '<canvas id="'+id+'">[No canvas support] </canvas>';
        fitToContainer(nodes[i].firstChild);
        if (channelname != null && channelname.trim().length > 0) {
            var displayLow = nodes[i].getAttribute("data-displayLow") != null ? parseInt(nodes[i].getAttribute("data-displayLow")) : 0;
            var displayHigh = nodes[i].getAttribute("data-displayHigh") != null ? parseInt(nodes[i].getAttribute("data-displayHigh")) : 100;
            var callback = function(evt, channel) {
                               switch (evt.type) {
                               case "connection": //connection state changed
                                   channel.readOnly = !evt.writeConnected;
                                   break;
                               case "value": //value changed
                                    var channelValue = channel.getValue();
                                    if (channelValue.display.lowDisplay == null) {
                                    } else {
                                    progressbars[channel.getId()] =new RGraph.HProgress(progressbars[channel.getId()].id,
                                                                      channelValue.value, channelValue.display.highDisplay);
                                    }
                                    var color = 'green';

                                    if(channelValue.alarm.severity =="MINOR") {
                                         progressbars[channel.getId()].Set('chart.colors', ["Gradient(#660:yellow:#660)"]);
                                       } else if (channelValue.alarm.severity =="MAJOR") {
                                          progressbars[channel.getId()].Set('chart.colors', ["Gradient(#600:red:#600)"]);
                                       } else {
                                          progressbars[channel.getId()].Set('chart.colors', ["Gradient(#060:#0f0:#060)"]);
                                       }
                                       progressbars[channel.getId()].Set('tickmarks.inner', true);
                                       progressbars[channel.getId()].Set('tickmarks.zerostart', true);
                                       progressbars[channel.getId()].Set('bevel', true);
                                       progressbars[channel.getId()].Set('margin', 10);
                                    progressbars[channel.getId()].Draw();
                                   break;
                               case "error": //error happened
                                   break;
                               case "writePermission":	// write permission changed.
                                   break;
                               case "writeCompleted": // write finished.
                                   break;
                               default:
                                   break;
                               }
                            };
            var channel = wp.subscribeChannel(channelname, callback, readOnly);
            progressbars[channel.getId()] = new RGraph.HProgress(id,0, displayHigh);
            progressbars[channel.getId()].Set('tickmarks.inner', true);
            progressbars[channel.getId()].Set('tickmarks.zerostart', true);
            progressbars[channel.getId()].Set('bevel', true);
            progressbars[channel.getId()].Set('margin', 10);
            progressbars[channel.getId()].Draw();

            progressbars[channel.getId()].canvas.onclick = function (e)
            {
                var obj   = e.target.__object__;
                var value = obj.getValue(e);
                obj.value = value;
                for(var sl in   progressbars) {
                    if(progressbars[sl].id == obj.id) {
                        var ch = wp.getChannel(sl);
                        break;
                    }
                }
                ch.setValue(value);
            }
        }
    }
});

window.onbeforeunload = function() {
	wp.close();
};

function fitToContainer(canvas){
	  canvas.style.width='100%';
	  canvas.style.height='100%';
	  canvas.width  = canvas.offsetWidth;
	  canvas.height = canvas.offsetHeight;
}


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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@color/background"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.dev4free.devbuyandroidclient.view.TitleBarView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </com.dev4free.devbuyandroidclient.view.TitleBarView>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.dev4free.devbuyandroidclient.view.ListViewCustom
            android:divider="@color/background"
            android:dividerHeight="@dimen/dimens_16dp"
            android:paddingTop="@dimen/dimens_16dp"
            android:layout_marginRight="@dimen/dimens_16dp"
            android:layout_marginLeft="@dimen/dimens_16dp"
            android:id="@+id/lv_manageaddress"
            android:background="@color/background"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </com.dev4free.devbuyandroidclient.view.ListViewCustom>

        <Button
            android:id="@+id/btn_manageaddress_add"
            android:layout_marginBottom="@dimen/dimens_16dp"
            android:layout_marginTop="48dp"
            android:text="新增地址"
            style="@style/btn_red" />

    </LinearLayout>

</ScrollView>

</LinearLayout>