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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin" >

        <!-- Circular -->
        <TextView
            android:text="@string/progress_circular"
            style="@style/SectionTextViewStyle" />
        <View style="@style/SectionDividerStyle" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="?android:progressBarStyleSmall" />

            <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="?android:progressBarStyleLarge" />

        </LinearLayout>

        <!-- Horizontal (indeterminate) -->
        <TextView
            android:text="@string/progress_horizontal_indeterminate"
            style="@style/SectionTextViewStyle" />
        <View style="@style/SectionDividerStyle" />

        <ProgressBar
            style="?android:progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:indeterminate="true" />

        <ProgressBar
            style="?android:progressBarStyleHorizontal"
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:indeterminate="true" />

        <ProgressBar
            style="?android:progressBarStyleHorizontal"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:indeterminate="true" />

        <!-- Horizontal (normal) -->
        <TextView
            android:text="@string/progress_horizontal_normal"
            style="@style/SectionTextViewStyle" />
        <View style="@style/SectionDividerStyle" />

        <ProgressBar
            style="?android:progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progress="10"
            android:secondaryProgress="40"/>

        <ProgressBar
            style="?android:progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progress="50"
            android:secondaryProgress="70" />

        <ProgressBar
            style="?android:progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progress="80"
            android:secondaryProgress="90"/>

        <!-- SeekBars -->
        <TextView
            android:text="@string/progress_seekbars"
            style="@style/SectionTextViewStyle" />
        <View style="@style/SectionDividerStyle" />

        <SeekBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progress="62"/>

        <SeekBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progress="38"/>

        <SeekBar
            android:id="@+id/myseekbar1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:enabled="false"
            android:progress="62"/>

        <SeekBar
            android:id="@+id/myseekbar2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:enabled="false"
            android:progress="38" />

        <!-- RatingBar -->
        <TextView
            android:text="@string/progress_ratingbars"
            style="@style/SectionTextViewStyle" />
        <View style="@style/SectionDividerStyle" />

        <RatingBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <RatingBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="?android:ratingBarStyleSmall"
            android:isIndicator="false" />

        <RatingBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="?android:ratingBarStyleIndicator"
            android:isIndicator="false" />

    </LinearLayout>

</ScrollView>


text:
tlassify-gender
===============

IR project to classify gender of twitter users

Currently working only for English users with English names and mostly from USA

## Current Best Result ##
![](https://github.com/puneetsl/tlassify-gender/blob/master/classification_results/best/ConfusionMatrix.png?raw=true)

## PS ##
I do not manage this code anymore here on github and moved it to bitbucket to make it private. But still you can see parts of the initial code/scripts I wrote for this project and some sample results

redpajama_set_name: RedPajamaGithub


text:
NS_ASSUME_NONNULL_BEGIN

@interface Movie (CoreDataProperties)

@property (nullable, nonatomic, retain) NSString *archive_id;
@property (nullable, nonatomic, retain) NSString *backdropURL;
@property (nullable, nonatomic, retain) NSString *collection;
@property (nullable, nonatomic, retain) NSDate *date_created;
@property (nullable, nonatomic, retain) NSDate *date_updated;
@property (nullable, nonatomic, retain) NSNumber *decade;
@property (nullable, nonatomic, retain) NSDecimalNumber *imdb_rating;
@property (nullable, nonatomic, retain) NSString *license;
@property (nullable, nonatomic, retain) NSString *movie_description;
@property (nullable, nonatomic, retain) NSString *original_title;
@property (nullable, nonatomic, retain) NSNumber *page_number;
@property (nullable, nonatomic, retain) NSString *posterURL;
@property (nullable, nonatomic, retain) NSNumber *runtime;
@property (nullable, nonatomic, retain) NSString *source;
@property (nullable, nonatomic, retain) NSString *title;
@property (nullable, nonatomic, retain) NSString *tmdb_id;
@property (nullable, nonatomic, retain) NSDecimalNumber *tmdb_rating;
@property (nullable, nonatomic, retain) NSNumber *year;
@property (nullable, nonatomic, retain) NSNumber *deletedOnServer;

@end

NS_ASSUME_NONNULL_END


text:
import * as React from 'react';

import {
  SemanticCOLORS,
  SemanticVERTICALALIGNMENTS,
  SemanticWIDTHS
} from '../..';
import { default as TableBody } from './TableBody';
import { default as TableCell } from './TableCell';
import { default as TableFooter } from './TableFooter';
import { default as TableHeader } from './TableHeader';
import { default as TableHeaderCell } from './TableHeaderCell';
import { default as TableRow } from './TableRow';

interface TableProps {
  [key: string]: any;

  /** An element type to render as (string or function). */
  as?: any;

  /** Attach table to other content */
  attached?: boolean | 'top' | 'bottom';

  /** A table can reduce its complexity to increase readability. */
  basic?: boolean | 'very';

  /** A table may be divided each row into separate cells. */
  celled?: boolean | 'internally';

  /** Primary content. */
  children?: React.ReactNode;

  /** Additional classes. */
  className?: string;

  /** A table can be collapsing, taking up only as much space as its rows. */
  collapsing?: boolean;

  /** A table can be given a color to distinguish it from other tables. */
  color?: SemanticCOLORS;

  /** A table can specify its column count to divide its content evenly. */
  columns?: SemanticWIDTHS;

  /** A table may sometimes need to be more compact to make more rows visible at a time. */
  compact?: boolean | 'very';

  /** A table may be formatted to emphasize a first column that defines a rows content. */
  definition?: boolean;

  /**
   * A table can use fixed a special faster form of table rendering that does not resize table cells based on content.
   */
  fixed?: boolean;

  /** Shorthand for a TableRow to be placed within Table.Footer. */
  footerRow?: any;

  /** Shorthand for a TableRow to be placed within Table.Header. */
  headerRow?: any;

  /** A table's colors can be inverted. */
  inverted?: boolean;

  /** A table may sometimes need to be more padded for legibility. */
  padded?: boolean | 'very';

  /**
   * A function that takes (data, index) and returns shorthand for a TableRow
   * to be placed within Table.Body.
   */
  renderBodyRow?: (data: any, index: number) => any;

  /** A table can have its rows appear selectable. */
  selectable?: boolean;

  /** A table can specify that its cell contents should remain on a single line and not wrap. */
  singleLine?: boolean;

  /** A table can also be small or large. */
  size?: 'small' | 'large';

  /** A table may allow a user to sort contents by clicking on a table header. */
  sortable?: boolean;

  /** A table can specify how it stacks table content responsively. */
  stackable?: boolean;

  /** A table can stripe alternate rows of content with a darker color to increase contrast. */
  striped?: boolean;

  /** A table can be formatted to display complex structured data. */
  structured?: boolean;

  /** Data to be passed to the renderBodyRow function. */
  tableData?: Array<any>;

  /** A table can adjust its text alignment. */
  textAlign?: 'center' | 'left' | 'right';

  /** A table can specify how it stacks table content responsively. */
  unstackable?: boolean;

  /** A table can adjust its text alignment. */
  verticalAlign?: SemanticVERTICALALIGNMENTS;
}

interface TableComponent extends React.StatelessComponent<TableProps> {
  Body: typeof TableBody;
  Cell: typeof TableCell;
  Footer: typeof TableFooter;
  Header: typeof TableHeader;
  HeaderCell: typeof TableHeaderCell;
  Row: typeof TableRow;
}

declare const Table: TableComponent;

export default Table;


text:
import MinePumpSystem.Environment;
import MinePumpSystem.MinePump;

public  class  Actions {

	Environment env;
	MinePump p;

    boolean methAndRunningLastTime = false;
    boolean switchedOnBeforeTS = false;

	Actions() {
		env = new Environment();
		p = new MinePump(env);
	}

	void waterRise() {
		env.waterRise();
	}

	void methaneChange() {
		env.changeMethaneLevel();
	}

	void stopSystem  () {
	    if(p.isSystemActive())
		p.stopSystem();
	}

	void startSystem  () {
	    if(!p.isSystemActive())
		p.startSystem();
	}

	void timeShift() {

		p.timeShift();

		if (p.isSystemActive()) {
		  Specification1();
		}
	}

	String getSystemState() {
		return p.toString();
	}

	// Specification 1 methan is Critical and pumping leads to Error
	void Specification1() {

	        Environment e = p.getEnv();

		    boolean b1 = e.isMethaneLevelCritical();
	        boolean b2 = p.isPumpRunning();

			 if ( b1 && b2) {
			     assert false;
			 }
    }
}


text:
package org.docksidestage.hangar.dbflute.bsbhv.loader;

import java.util.List;

import org.dbflute.bhv.*;
import org.dbflute.bhv.referrer.*;
import org.docksidestage.hangar.dbflute.exbhv.*;
import org.docksidestage.hangar.dbflute.exentity.*;
import org.docksidestage.hangar.dbflute.cbean.*;

/**
 * The referrer loader of WHITE_COMPOUND_PK as TABLE.

 *

 * [primary key]
 *     PK_FIRST_ID, PK_SECOND_ID
 *
 * [column]
 *     PK_FIRST_ID, PK_SECOND_ID, COMPOUND_PK_NAME, REFERRED_ID
 *
 * [sequence]
 *
 *
 * [identity]
 *
 *
 * [version-no]
 *
 *
 * [foreign table]
 *
 *
 * [referrer table]
 *     WHITE_COMPOUND_PK_REF_PHYSICAL, WHITE_COMPOUND_PK_REF_VIRTURL
 *
 * [foreign property]
 *
 *
 * [referrer property]
 *     whiteCompoundPkRefPhysicalList, whiteCompoundPkRefVirturlList
 *

 * @author DBFlute(AutoGenerator)
 */
public class LoaderOfWhiteCompoundPk {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    protected List<WhiteCompoundPk> _selectedList;
    protected BehaviorSelector _selector;
    protected WhiteCompoundPkBhv _myBhv; // lazy-loaded

    // ===================================================================================
    //                                                                   Ready for Loading
    //                                                                   =================
    public LoaderOfWhiteCompoundPk ready(List<WhiteCompoundPk> selectedList, BehaviorSelector selector)
    { _selectedList = selectedList; _selector = selector; return this; }

    protected WhiteCompoundPkBhv myBhv()
    { if (_myBhv != null) { return _myBhv; } else { _myBhv = _selector.select(WhiteCompoundPkBhv.class); return _myBhv; } }

    // ===================================================================================
    //                                                                       Load Referrer
    //                                                                       =============
    protected List<WhiteCompoundPkRefPhysical> _referrerWhiteCompoundPkRefPhysical;

    /**
     * Load referrer of whiteCompoundPkRefPhysicalList by the set-upper of referrer.

     * WHITE_COMPOUND_PK_REF_PHYSICAL by REF_FIRST_ID, REF_SECOND_ID, named 'whiteCompoundPkRefPhysicalList'.
     *

     * whiteCompoundPkBhv.load(whiteCompoundPkList, pkLoader -> {
     *     pkLoader.loadWhiteCompoundPkRefPhysical(physicalCB -> {
     *         physicalCB.setupSelect...
     *         physicalCB.query().set...
     *         physicalCB.query().addOrderBy...
     *     }); // you can load nested referrer from here
     *     //}).withNestedReferrer(physicalLoader -> {
     *     //    physicalLoader.load...
     *     //});
     * });
     * for (WhiteCompoundPk whiteCompoundPk : whiteCompoundPkList) {
     *     ... = whiteCompoundPk.getWhiteCompoundPkRefPhysicalList();
     * }
     *

     * About internal policy, the value of primary key (and others too) is treated as case-insensitive.

     * The condition-bean, which the set-upper provides, has settings before callback as follows:
     *

     * cb.query().set[ForeignKey]_InScope(pkList);
     * cb.query().addOrderBy_[ForeignKey]_Asc();
     *

     * @param refCBLambda The callback to set up referrer condition-bean for loading referrer. (NotNull)
     * @return The callback interface which you can load nested referrer by calling withNestedReferrer(). (NotNull)
     */
    public NestedReferrerLoaderGateway<LoaderOfWhiteCompoundPkRefPhysical> loadWhiteCompoundPkRefPhysical(ReferrerConditionSetupper<WhiteCompoundPkRefPhysicalCB> refCBLambda) {
        myBhv().loadWhiteCompoundPkRefPhysical(_selectedList, refCBLambda).withNestedReferrer(refLs -> _referrerWhiteCompoundPkRefPhysical = refLs);
        return hd -> hd.handle(new LoaderOfWhiteCompoundPkRefPhysical().ready(_referrerWhiteCompoundPkRefPhysical, _selector));
    }

    protected List<WhiteCompoundPkRefVirturl> _referrerWhiteCompoundPkRefVirturl;

    /**
     * Load referrer of whiteCompoundPkRefVirturlList by the set-upper of referrer.

     * WHITE_COMPOUND_PK_REF_VIRTURL by REF_FIRST_ID, REF_SECOND_ID, named 'whiteCompoundPkRefVirturlList'.
     *

     * whiteCompoundPkBhv.load(whiteCompoundPkList, pkLoader -> {
     *     pkLoader.loadWhiteCompoundPkRefVirturl(virturlCB -> {
     *         virturlCB.setupSelect...
     *         virturlCB.query().set...
     *         virturlCB.query().addOrderBy...
     *     }); // you can load nested referrer from here
     *     //}).withNestedReferrer(virturlLoader -> {
     *     //    virturlLoader.load...
     *     //});
     * });
     * for (WhiteCompoundPk whiteCompoundPk : whiteCompoundPkList) {
     *     ... = whiteCompoundPk.getWhiteCompoundPkRefVirturlList();
     * }
     *

     * About internal policy, the value of primary key (and others too) is treated as case-insensitive.

     * The condition-bean, which the set-upper provides, has settings before callback as follows:
     *

     * cb.query().set[ForeignKey]_InScope(pkList);
     * cb.query().addOrderBy_[ForeignKey]_Asc();
     *

     * @param refCBLambda The callback to set up referrer condition-bean for loading referrer. (NotNull)
     * @return The callback interface which you can load nested referrer by calling withNestedReferrer(). (NotNull)
     */
    public NestedReferrerLoaderGateway<LoaderOfWhiteCompoundPkRefVirturl> loadWhiteCompoundPkRefVirturl(ReferrerConditionSetupper<WhiteCompoundPkRefVirturlCB> refCBLambda) {
        myBhv().loadWhiteCompoundPkRefVirturl(_selectedList, refCBLambda).withNestedReferrer(refLs -> _referrerWhiteCompoundPkRefVirturl = refLs);
        return hd -> hd.handle(new LoaderOfWhiteCompoundPkRefVirturl().ready(_referrerWhiteCompoundPkRefVirturl, _selector));
    }

    // ===================================================================================
    //                                                                    Pull out Foreign
    //                                                                    ================
    // ===================================================================================
    //                                                                            Accessor
    //                                                                            ========
    public List<WhiteCompoundPk> getSelectedList() { return _selectedList; }
    public BehaviorSelector getSelector() { return _selector; }
}


text:
package com.geekmind.bolaidh.manager;

import com.geekmind.bolaidh.exception.InvalidSearchCriteriaException;
import com.geekmind.bolaidh.exception.InvalidSearchRequestException;
import com.geekmind.bolaidh.exception.InvalidSearchResponseException;
import com.geekmind.bolaidh.exception.SearchException;
import com.geekmind.bolaidh.search.BasicSearchReponse;
import com.geekmind.bolaidh.search.SearchCriteria;
import com.geekmind.bolaidh.search.SearchResponse;
import com.geekmind.bolaidh.search.miscellaneous.RateLimitCriteria;
import com.geekmind.bolaidh.search.mock.MockedSearchCriteria;
import com.geekmind.bolaidh.search.repository.RepositorySearchCriteriaBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.message.BasicNameValuePair;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * Implements all test cases necessary to ensure the correct behavior of
 * {@link ClientManager}.
 *
 * @author andre.silva
 */
@RunWith(MockitoJUnitRunner.class)
public class ClientManagerTest {

    @InjectMocks
    private final ClientManager clientManager = new ClientManager();

    /*
     * ======================================================================
     * Tests for execute().
     * ======================================================================
     */
    @Test(expected = InvalidSearchCriteriaException.class)
    public void execute_NullSearchCriteria_ThrowException() throws SearchException {

        // Run
        this.clientManager.execute(null);

    }

    @Test(expected = InvalidSearchCriteriaException.class)
    public void execute_UnknowSearchCriteria_ThrowException() throws SearchException {

        // Run
        this.clientManager.execute(new MockedSearchCriteria());

    }

    @Test(expected = InvalidSearchCriteriaException.class)
    public void execute_EmptySearchCriteria_ThrowException() throws SearchException {

        // Prepare
        SearchCriteria criteria = RepositorySearchCriteriaBuilder.newInstance().build();

        // Run
        this.clientManager.execute(criteria);

    }

    @Test(expected = InvalidSearchResponseException.class)
    public void execute_IssuesInAgentExecute_ThrowException() throws SearchException, IOException {

        // Prepare
        SearchCriteria criteria = spy(RepositorySearchCriteriaBuilder.newInstance().withKeyWord("test").build());
        when(criteria.getEndPointURL()).thenReturn(":21/search/api");

        // Run
        this.clientManager.execute(criteria);

    }

    @Test
    public void execute_ValidSearchCriteriaWithParameters_Success() throws SearchException {

        // Prepare
        SearchCriteria criteria = RepositorySearchCriteriaBuilder.newInstance().withKeyWord("test").build();

        // Run
        SearchResponse response = this.clientManager.execute(criteria);

        // Test
        assertNotNull(response);
        assertNotNull(response.getStatus());
        assertEquals((Integer) 200, response.getStatus());

    }

    @Test
    public void execute_ValidSearchCriteriaWithoutParameters_Success() throws SearchException {

        // Prepare
        SearchCriteria criteria = new RateLimitCriteria();

        // Run
        SearchResponse response = this.clientManager.execute(criteria);

        // Test
        assertNotNull(response);
        assertNotNull(response.getStatus());
        assertEquals((Integer) 200, response.getStatus());

    }

    /*
     * ======================================================================
     * Tests for parseURLParameters().
     * ======================================================================
     */
    @Test
    public void parseURLParameters_NullParameters_ReturnEmptyList() {

        // Run
        List<NameValuePair> values = this.clientManager.parseURLParameters(null);

        // Test
        assertNotNull(values);
        assertTrue(values.isEmpty());

    }

    @Test
    public void parseURLParameters_EmptyParameters_ReturnEmptyList() {

        // Run
        List<NameValuePair> values = this.clientManager.parseURLParameters(new HashMap<>());

        // Test
        assertNotNull(values);
        assertTrue(values.isEmpty());

    }

    @Test
    public void parseURLParameters_NonEmptyParameters_ReturnNonEmptyList() {

        // Prepare
        Map<String, String> parameters = new HashMap<>();
        parameters.put("q", "test");

        // Run
        List<NameValuePair> values = this.clientManager.parseURLParameters(parameters);

        // Test
        assertNotNull(values);
        assertFalse(values.isEmpty());
        assertEquals("q", values.get(0).getName());
        assertEquals("test", values.get(0).getValue());

    }

    /*
     * ======================================================================
     * Tests for prepareRequestURL(String, List<NameValuePair>).
     * ======================================================================
     */
    @Test(expected = InvalidSearchRequestException.class)
    public void prepareRequestURL_NullEndPointURL_ThrowException() throws InvalidSearchRequestException {

        // Run
        this.clientManager.prepareRequestURL(null, null);

    }

    @Test(expected = InvalidSearchRequestException.class)
    public void prepareRequestURL_BlankEndPointURL_ThrowException() throws InvalidSearchRequestException {

        // Run
        this.clientManager.prepareRequestURL("", null);

    }

    @Test(expected = InvalidSearchRequestException.class)
    public void prepareRequestURL_NullParameters_ThrowException() throws InvalidSearchRequestException {

        // Run
        this.clientManager.prepareRequestURL("/search/repository", null);

    }

    @Test(expected = InvalidSearchRequestException.class)
    public void prepareRequestURL_EmptyParameters_ThrowException() throws InvalidSearchRequestException {

        // Run
        this.clientManager.prepareRequestURL("/search/repository", new ArrayList<>());

    }

    @Test
    public void prepareRequestURL_ValidEndPointUrlAndParameters_ReturnPreparedRequest() throws InvalidSearchRequestException {

        // Prepare
        List<NameValuePair> valuePairs = new ArrayList<>();
        valuePairs.add(new BasicNameValuePair("q", "name"));

        // Run
        HttpGet request = this.clientManager.prepareRequestURL("/search/repository", valuePairs);

        // Test
        assertNotNull(request);
        assertEquals(1, request.getHeaders("Accept").length);
        assertEquals(ClientManager.ACCEPT_HEADER, request.getHeaders("Accept")[0].getValue());

    }

    @Test
    public void prepareRequestURL_ValidEndPointUrlParametersAndOAuth2Token_ReturnPreparedRequest() throws InvalidSearchRequestException {

        // Prepare
        List<NameValuePair> valuePairs = new ArrayList<>();
        valuePairs.add(new BasicNameValuePair("q", "name"));
        ClientManager authenticatedManager = new ClientManager("test");

        // Run
        HttpGet request = authenticatedManager.prepareRequestURL("/search/repository", valuePairs);

        // Test
        assertNotNull(request);

        assertEquals(1, request.getHeaders("Accept").length);
        assertEquals(1, request.getHeaders("Authorization").length);

        assertEquals(ClientManager.ACCEPT_HEADER, request.getHeaders("Accept")[0].getValue());
        assertEquals("token test", request.getHeaders("Authorization")[0].getValue());

    }

    /*
     * ======================================================================
     * Tests for prepareRequestURL(String).
     * ======================================================================
     */
    @Test(expected = InvalidSearchRequestException.class)
    public void prepareRequestURL_NullURL_ThrowException() throws InvalidSearchRequestException {

        // Run
        this.clientManager.prepareRequestURL(null);

    }

    @Test(expected = InvalidSearchRequestException.class)
    public void prepareRequestURL_BlankURL_ThrowException() throws InvalidSearchRequestException {

        // Run
        this.clientManager.prepareRequestURL("");

    }

    @Test
    public void prepareRequestURL_ValidURL_ReturnHttpGetInstance() throws InvalidSearchRequestException {

        // Prepare
        ClientManager authenticatedManager = new ClientManager();

        // Run
        HttpGet request = authenticatedManager.prepareRequestURL("https://api.github.com/search/repository?q=java");

        // Test
        assertNotNull(request);

        assertEquals(1, request.getHeaders("Accept").length);
        assertEquals(ClientManager.ACCEPT_HEADER, request.getHeaders("Accept")[0].getValue());

    }

    @Test
    public void prepareRequestURL_ValidURLAndOAuth2Token_ReturnHttpGetInstance() throws InvalidSearchRequestException {

        // Prepare
        ClientManager authenticatedManager = new ClientManager("test");

        // Run
        HttpGet request = authenticatedManager.prepareRequestURL("https://api.github.com/search/repository?q=java");

        // Test
        assertNotNull(request);

        assertEquals(1, request.getHeaders("Accept").length);
        assertEquals(1, request.getHeaders("Authorization").length);

        assertEquals(ClientManager.ACCEPT_HEADER, request.getHeaders("Accept")[0].getValue());
        assertEquals("token test", request.getHeaders("Authorization")[0].getValue());

    }

    @Test(expected = InvalidSearchRequestException.class)
    public void prepareRequestURL_InvalidStringURL_ThrowException() throws InvalidSearchRequestException {

        // Run
        this.clientManager.prepareRequestURL("https://api.github.com/search/repository?q=java 10%");

    }

    /*
     * ======================================================================
     * Tests for next().
     * ======================================================================
     */
    @Test(expected = InvalidSearchResponseException.class)
    public void next_NullSearchResponse_ThrowException() throws Exception {

        // Run
        this.clientManager.next(null);

    }

    @Test(expected = InvalidSearchResponseException.class)
    public void next_LastPage_ThrowException() throws Exception {

        // Prepare
        SearchResponse mockedResponse = spy(new BasicSearchReponse());
        when(mockedResponse.hasNext()).thenReturn(false);

        // Run
        this.clientManager.next(mockedResponse);

    }

    @Test
    public void next_FirstPage_Execute() throws Exception {

        // Prepare
        SearchResponse mockedResponse = mock(BasicSearchReponse.class);
        when(mockedResponse.hasNext()).thenReturn(true);

        ClientManager mockedClientManager = mock(ClientManager.class);
        when(mockedClientManager.getPage(any(String.class))).thenReturn(new BasicSearchReponse());
        when(mockedClientManager.next(any(SearchResponse.class))).thenCallRealMethod();

        // Run
        SearchResponse response = mockedClientManager.next(mockedResponse);

        // Test
        assertNotNull(response);

    }

    /*
     * ======================================================================
     * Tests for previous().
     * ======================================================================
     */
    @Test(expected = InvalidSearchResponseException.class)
    public void previous_NullSearchResponse_ThrowException() throws Exception {

        // Run
        this.clientManager.previous(null);

    }

    @Test(expected = InvalidSearchResponseException.class)
    public void previous_FirstPage_ThrowException() throws Exception {

        // Prepare
        SearchResponse mockedResponse = spy(new BasicSearchReponse());
        when(mockedResponse.hasPrevious()).thenReturn(false);

        // Run
        this.clientManager.previous(mockedResponse);

    }

    @Test
    public void previous_MiddlePage_Execute() throws Exception {

        // Prepare
        SearchResponse mockedResponse = mock(BasicSearchReponse.class);
        when(mockedResponse.hasPrevious()).thenReturn(true);

        ClientManager mockedClientManager = mock(ClientManager.class);
        when(mockedClientManager.getPage(any(String.class))).thenReturn(new BasicSearchReponse());
        when(mockedClientManager.previous(any(SearchResponse.class))).thenCallRealMethod();

        // Run
        SearchResponse response = mockedClientManager.previous(mockedResponse);

        // Test
        assertNotNull(response);

    }

    /*
     * ======================================================================
     * Tests for prepareRequest().
     * ======================================================================
     */
    @Test(expected = InvalidSearchRequestException.class)
    public void prepareRequest_NullUri_ThrowException() throws Exception {

        this.clientManager.prepareRequest(null);

    }

}


text:
/*
 ---

 name: Locale.de-CH.Date

 description: Date messages for German (Switzerland).

 license: MIT-style license

 authors:
 - Michael van der Weg

 requires:
 - /Locale
 - /Locale.de-DE.Date

 provides: [Locale.de-CH.Date]

 ...
 */

Locale.define('de-CH', 'Date', {

	months: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
	months_abbr: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
	days: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
	days_abbr: ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'],

	// Culture's date order: DD.MM.YYYY
	dateOrder: ['date', 'month', 'year'],
	shortDate: '%d.%m.%Y',
	shortTime: '%H:%M',
	AM: 'vormittags',
	PM: 'nachmittags',
	firstDayOfWeek: 1,

	// Date.Extras
	ordinal: '.',

	lessThanMinuteAgo: 'vor weniger als einer Minute',
	minuteAgo: 'vor einer Minute',
	minutesAgo: 'vor {delta} Minuten',
	hourAgo: 'vor einer Stunde',
	hoursAgo: 'vor {delta} Stunden',
	dayAgo: 'vor einem Tag',
	daysAgo: 'vor {delta} Tagen',
	weekAgo: 'vor einer Woche',
	weeksAgo: 'vor {delta} Wochen',
	monthAgo: 'vor einem Monat',
	monthsAgo: 'vor {delta} Monaten',
	yearAgo: 'vor einem Jahr',
	yearsAgo: 'vor {delta} Jahren',

	lessThanMinuteUntil: 'in weniger als einer Minute',
	minuteUntil: 'in einer Minute',
	minutesUntil: 'in {delta} Minuten',
	hourUntil: 'in ca. einer Stunde',
	hoursUntil: 'in ca. {delta} Stunden',
	dayUntil: 'in einem Tag',
	daysUntil: 'in {delta} Tagen',
	weekUntil: 'in einer Woche',
	weeksUntil: 'in {delta} Wochen',
	monthUntil: 'in einem Monat',
	monthsUntil: 'in {delta} Monaten',
	yearUntil: 'in einem Jahr',
	yearsUntil: 'in {delta} Jahren'

});

/*
 ---

 name: Locale.de-CH.Form.Validator

 description: Form Validator messages for German (Switzerland).

 license: MIT-style license

 authors:
 - Michael van der Weg

 requires:
 - /Locale

 provides: [Locale.de-CH.Form.Validator]

 ...
 */

Locale.define('de-CH', 'FormValidator', {

	required: 'Dieses Feld ist obligatorisch.',
	minLength: 'Geben Sie bitte mindestens {minLength} Zeichen ein (Sie haben {length} Zeichen eingegeben).',
	maxLength: 'Bitte geben Sie nicht mehr als {maxLength} Zeichen ein (Sie haben {length} Zeichen eingegeben).',
	integer: 'Geben Sie bitte eine ganze Zahl ein. Dezimalzahlen (z.B. 1.25) sind nicht erlaubt.',
	numeric: 'Geben Sie bitte nur Zahlenwerte in dieses Eingabefeld ein (z.B. "1", "1.1", "-1" oder "-1.1").',
	digits: 'Benutzen Sie bitte nur Zahlen und Satzzeichen in diesem Eingabefeld (erlaubt ist z.B. eine Telefonnummer mit Bindestrichen und Punkten).',
	alpha: 'Benutzen Sie bitte nur Buchstaben (a-z) in diesem Feld. Leerzeichen und andere Zeichen sind nicht erlaubt.',
	alphanum: 'Benutzen Sie bitte nur Buchstaben (a-z) und Zahlen (0-9) in diesem Eingabefeld. Leerzeichen und andere Zeichen sind nicht erlaubt.',
	dateSuchAs: 'Geben Sie bitte ein gültiges Datum ein. Wie zum Beispiel {date}',
	dateInFormatMDY: 'Geben Sie bitte ein gültiges Datum ein. Wie zum Beispiel TT.MM.JJJJ (z.B. "31.12.1999")',
	email: 'Geben Sie bitte eine gültige E-Mail Adresse ein. Wie zum Beispiel "maria@bernasconi.ch".',
	url: 'Geben Sie bitte eine gültige URL ein. Wie zum Beispiel http://www.example.com.',
	currencyDollar: 'Geben Sie bitte einen gültigen Betrag in Schweizer Franken ein. Wie zum Beispiel 100.00 CHF .',
	oneRequired: 'Machen Sie für mindestens eines der Eingabefelder einen Eintrag.',
	errorPrefix: 'Fehler: ',
	warningPrefix: 'Warnung: ',

	// Form.Validator.Extras
	noSpace: 'In diesem Eingabefeld darf kein Leerzeichen sein.',
	reqChkByNode: 'Es wurden keine Elemente gewählt.',
	requiredChk: 'Dieses Feld ist obligatorisch.',
	reqChkByName: 'Bitte wählen Sie ein {label}.',
	match: 'Dieses Eingabefeld muss mit dem Feld {matchName} übereinstimmen.',
	startDate: 'Das Anfangsdatum',
	endDate: 'Das Enddatum',
	currendDate: 'Das aktuelle Datum',
	afterDate: 'Das Datum sollte zur gleichen Zeit oder später sein {label}.',
	beforeDate: 'Das Datum sollte zur gleichen Zeit oder früher sein {label}.',
	startMonth: 'Wählen Sie bitte einen Anfangsmonat',
	sameMonth: 'Diese zwei Datumsangaben müssen im selben Monat sein - Sie müssen eine von beiden verändern.',
	creditcard: 'Die eingegebene Kreditkartennummer ist ungültig. Bitte überprüfen Sie diese und versuchen Sie es erneut. {length} Zahlen eingegeben.'

});


text:
package org.jclouds.dynect.v3.parse;
import static org.jclouds.dynect.v3.domain.rdata.TXTData.txt;

import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;

import org.jclouds.dynect.v3.domain.Record;
import org.jclouds.dynect.v3.domain.rdata.TXTData;
import org.jclouds.dynect.v3.internal.BaseDynECTParseTest;
import org.jclouds.rest.annotations.SelectJson;
import org.testng.annotations.Test;

@Test(groups = "unit")
public class GetTXTRecordResponseTest extends BaseDynECTParseTest<Record<TXTData>> {

   @Override
   public String resource() {
      return "/get_record_txt.json";
   }

   @Override
   @SelectJson("data")
   @Consumes(MediaType.APPLICATION_JSON)
   public Record<TXTData> expected() {
      return Record.<TXTData> builder()
                   .zone("egg.org")
                   .fqdn("sm._domainkey.email.egg.org")
                   .type("TXT")
                   .id(50959331)
                   .ttl(86400)
                   .rdata(txt("k=rsa\\; p=4KAtUdsUGRtjPHE1rsyFYs8XVzvdke8pXnoo+80Kj5b6C37rnyCmZ0w1R5LY=="))
                   .build();
   }
}


text:
interface IResolver {
    apply(resolve: (path: string) => any): any;
}

export default IResolver;


text:
Here is a paragraph, how nice!

```javascript
if (this) {
  then.that();
}
```

http://google.dk


text:
var LiveSearch = function () {
    var self = this;
    self.input = $('#search');
    self.button = $('#do-search');
    self.match = $('.high');
    return self;
};

LiveSearch.prototype = {

    find: false,

    render: function (data, query) {

        var ul = $('#search-result');
        ul.empty();
        ul.slideDown(200);

        for (var i = 0, l = data.length; i < l; i += 1) {

            var subj = data[i].subject,
                price = data[i].price,
                imgLink = data[i].img,
                userId = data[i].userId,
                adsId = data[i].id,
                li = $('<li>').attr('class', 'media-list-link'),
                a = $('<a>').attr('href', cnst.DETAIL_LINK + adsId),
                img = $('<img>').attr('src',
                    cnst.IMG_HOST + cnst.SEPARATOR +
                    userId + cnst.SEPARATOR +
                    adsId + cnst.SEPARATOR +
                    cnst.PREVIEW + imgLink),
                container = $('<span>'),
                heading = $('<b>').attr('class', 'high').text(subj),
                p = $('<p>').text('$' + price);

            container.append(heading);
            container.append(p);

            a.append(img);
            a.append(container);

            li.append(a);

            ul.append(li);
        }

        var more = $('<li>'),
            link = $('<a>').attr('href', '/search/' + processParameter(query)).attr('class', 'btn btn-default').text('See more');
        more.append(link);
        ul.append(more);
    },

    search: function (query) {

        $.post('/livesearch', {q: query}, function (data) {

            if (data) {
                data = JSON.parse(data);
                LiveSearch.prototype.render(data, query);
                LiveSearch.prototype.find = true;
                $('.high').highlight(query);
            } else {
                $('#search-result').slideUp(100).empty();
                LiveSearch.prototype.find = false;
            }
        });
    }
};

$(function () {
    var search = new LiveSearch();

    search.input.keyup(function () {
        search.search(search.input.val());
    });

    // hide list if input focus out
    search.input.blur(function () {
        setTimeout(function () {
            var focused = $(document.activeElement);
            if (!focused.hasClass('media') && (focused.parents('.media-list').length === 0)) {
                $('#search-result').slideUp(100);
            }
        }, 100);
    });

    // show list if input focus in
    search.input.focus(function () {
        if (search.find) {
            $('#search-result').slideDown(200);
        }
    });

    search.button.click(function () {
        var path = (search.input.val() !== '') ? 'search' + cnst.SEPARATOR + processParameter(search.input.val()) : 'search';
        window.location.href = cnst.HOST + path;
        return false;
    });

});


text:
#ifndef font_h
#define font_h

#include "mymath/mymath.h"

#include "GL/glew.h"

#include <map>
#include <list>
#include <string>
#include <vector>

/*
 * Based on Shikoba
 */

struct glyph;
class font;
class font_inst;

#define FONT_LIB_VBO_SIZE 8

struct fontscalebias
{
  mm::vec4 vertscalebias;
  mm::vec4 texscalebias;

  fontscalebias( const mm::vec2& vertscale, const mm::vec2& vertbias, const mm::vec2& texscale, const mm::vec2& texbias ) :
    vertscalebias( mm::vec4( vertscale, vertbias ) ), texscalebias( mm::vec4( texscale, texbias ) )
  {
  }
};

class library
{
  friend class font;
  friend class face;
  friend class font_inst;
private:
  void* the_library;
  mm::uvec2 texture_pen;
  GLint texture_row_h;
  GLuint tex; //font texture
  GLuint texsampler_point, texsampler_linear;
  mm::uvec2 texsize;
  GLuint vao; //vao
  GLuint vbos[FONT_LIB_VBO_SIZE]; //vbos
  std::vector<fontscalebias> font_data;
  GLuint the_shader; //shader program
  bool is_set_up;
  std::vector<font_inst*> instances;

  void delete_glyphs();

  void* get_library()
  {
    return the_library;
  }

  GLuint& get_shader()
  {
    return the_shader;  //load shader externally
  }

  mm::uvec2 get_texsize()
  {
    return texsize;
  }

  mm::uvec2& get_texture_pen()
  {
    return texture_pen;
  }

  GLint& get_tex_row_h()
  {
    return texture_row_h;
  }

  GLuint get_tex()
  {
    return tex;
  }

  size_t get_font_data_size()
  {
    return font_data.size();
  }

  fontscalebias& get_font_data( size_t i )
  {
    return font_data[i];
  }

  void set_up();
  void destroy();

  void bind_shader()
  {
    glUseProgram( the_shader );
  }

  void bind_texture()
  {
    glActiveTexture( GL_TEXTURE0 );
    glBindTexture( GL_TEXTURE_RECTANGLE, tex );
    glActiveTexture( GL_TEXTURE1 );
    glBindTexture( GL_TEXTURE_RECTANGLE, tex );

    glBindSampler( 0, texsampler_point );
    glBindSampler( 1, texsampler_linear );
  }

  void bind_vao()
  {
    glBindVertexArray( vao );
  }

  template< class t >
  void update_scalebiascolor( unsigned int i, const std::vector< t >& tt )
  {
    glBindBuffer( GL_ARRAY_BUFFER, vbos[i] );

    if( tt.size() > 0 )
      glBufferData( GL_ARRAY_BUFFER, sizeof(t)* tt.size(), &tt[0], GL_DYNAMIC_DRAW );
  }

  bool expand_tex();

  void add_font_data( const fontscalebias& fd )
  {
    font_data.push_back( fd );
  }
protected:
  library(); //singleton
  library( const library& );
  library( library && );
  library& operator=( const library& );
  ~library();
public:

  static library& get()
  {
    static library instance;
    return instance;
  }
};

#ifdef _WIN32
typedef unsigned int uint32_t;
#endif

//this corresponds to a font file '*.ttf'
//meaning if you'd like to switch to another font-type
//you have to switch font instances
//you can switch between sizes though
class font_inst
{
private:
protected:
public:
  class face
  {
    friend class font;
    friend class library;
  private:
    unsigned int size;
    float asc;
    float desc;
    float h;
    float gap;
    float upos;
    float uthick;
    void* the_face; //FT_Face
    std::map< unsigned int, std::map<uint32_t, glyph> >* glyphs;

    void set_size( unsigned int val );
    bool load_glyph( uint32_t val );

    unsigned int get_size()
    {
      return size;
    }

    glyph& get_glyph( uint32_t i );
    bool has_glyph( uint32_t i );
    float advance( const uint32_t current );
    float kerning( const uint32_t prev, const uint32_t next = 0 );
    float height();
    float linegap();
    float ascender();
    float descender();
    float underline_position();
    float underline_thickness();
  protected:
  public:
    face();
    face( const std::string& filename, unsigned int index = 0 );
    ~face();
  }*the_face;

  font_inst() : the_face( 0 )
  {
  }
  ~font_inst()
  {
    delete the_face;
  }
};

class font
{
private:
  mm::uvec2 screensize;
  mm::frame<float> font_frame;

  void add_glyph( font_inst& f, uint32_t c, int counter = 0 );
protected:
  font()
  {
  } //singleton
  font( const font& );
  font( font && );
  font& operator=( const font& );
public:
  void load_font( const std::string& filename, font_inst& font_ptr, unsigned int size );
  mm::vec2 add_to_render_list( const std::wstring& text, font_inst& font_ptr, const mm::vec4& color = mm::vec4( 1 ), const mm::mat4& mat = mm::mat4::identity, const mm::vec4& highlight_color = mm::vec4( 1 ), float line_height = 1, float filter = 0 );
  void render();

  void set_size( font_inst& f, unsigned int s );

  void resize( const mm::uvec2& ss );

  void destroy()
  {
    library::get().destroy();
  }

  GLuint& get_shader()
  {
    return library::get().get_shader();
  }

  static font& get()
  {
    static font instance;
    return instance;
  }
};

#endif


text:
/**
 * @file
 * simple idct header.
 */

#ifndef AVCODEC_SIMPLE_IDCT_H
#define AVCODEC_SIMPLE_IDCT_H

#include <stdint.h>
#include "dsputil.h"

void ff_simple_idct_put_8(uint8_t *dest, int line_size, DCTELEM *block);
void ff_simple_idct_add_8(uint8_t *dest, int line_size, DCTELEM *block);
void ff_simple_idct_8(DCTELEM *block);

void ff_simple_idct_put_10(uint8_t *dest, int line_size, DCTELEM *block);
void ff_simple_idct_add_10(uint8_t *dest, int line_size, DCTELEM *block);
void ff_simple_idct_10(DCTELEM *block);
/**
 * Special version of ff_simple_idct_10() which does dequantization
 * and scales by a factor of 2 more between the two IDCTs to account
 * for larger scale of input coefficients.
 */
void ff_prores_idct(DCTELEM *block, const int16_t *qmat);

void ff_simple_idct_mmx(int16_t *block);
void ff_simple_idct_add_mmx(uint8_t *dest, int line_size, int16_t *block);
void ff_simple_idct_put_mmx(uint8_t *dest, int line_size, int16_t *block);

void ff_simple_idct248_put(uint8_t *dest, int line_size, DCTELEM *block);

void ff_simple_idct84_add(uint8_t *dest, int line_size, DCTELEM *block);
void ff_simple_idct48_add(uint8_t *dest, int line_size, DCTELEM *block);
void ff_simple_idct44_add(uint8_t *dest, int line_size, DCTELEM *block);

#endif /* AVCODEC_SIMPLE_IDCT_H */


text:
<CartClearResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
  <OperationRequest>
    <HTTPHeaders>
      <Header Name="UserAgent" Value="Python-urllib/2.6"/>
    </HTTPHeaders>
    <RequestId>1GC07ZSTGEW6X27K01M6</RequestId>
    <Arguments>
      <Argument Name="AssociateTag" Value="XXXXXXXXXXXXXXX"/>
      <Argument Name="Service" Value="AWSECommerceService"/>
      <Argument Name="Signature" Value="XXXXXXXXXXXXXXX"/>
      <Argument Name="HMAC" Value="ubxCtsc13HBlxPk43aFb2tYcyNs="/>
      <Argument Name="Operation" Value="CartClear"/>
      <Argument Name="CartId" Value="275-4955323-0806016"/>
      <Argument Name="AWSAccessKeyId" Value="XXXXXXXXXXXXXXX"/>
      <Argument Name="Timestamp" Value="2011-11-08T21:46:28Z"/>
      <Argument Name="Version" Value="2011-08-01"/>
    </Arguments>
    <RequestProcessingTime>0.0619640350341797</RequestProcessingTime>
  </OperationRequest>
  <Cart>
    <Request>
      <IsValid>True</IsValid>
      <CartClearRequest>
        <CartId>275-4955323-0806016</CartId>
        <HMAC>ubxCtsc13HBlxPk43aFb2tYcyNs=</HMAC>
      </CartClearRequest>
    </Request>
    <CartId>275-4955323-0806016</CartId>
    <HMAC>ubxCtsc13HBlxPk43aFb2tYcyNs=</HMAC>
    <URLEncodedHMAC>ubxCtsc13HBlxPk43aFb2tYcyNs%3D</URLEncodedHMAC>
  </Cart>
</CartClearResponse>


text:
import os
import numpy as np

from singa import device
from singa import tensor
from singa import sonnx
from singa import autograd
import onnx

import sys
sys.path.append(os.path.dirname(__file__) + '/..')
from utils import download_model

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s')

from transformers import GPT2Tokenizer

tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
length = 20

def preprocess():
    text = "Here is some text to encode : Hello World"
    tokens = tokenizer.encode(text)
    tokens = np.array(tokens)
    return tokens.reshape([1, 1, -1]).astype(np.float32)

def postprocess(out):
    text = tokenizer.decode(out)
    return text

class MyModel(sonnx.SONNXModel):

    def __init__(self, onnx_model):
        super(MyModel, self).__init__(onnx_model)

    def forward(self, *x):
        y = super(MyModel, self).forward(*x)
        return y[0]

    def train_one_batch(self, x, y):
        pass

if __name__ == "__main__":
    url = 'https://github.com/onnx/models/raw/master/text/machine_comprehension/gpt-2/model/gpt2-lm-head-10.tar.gz'
    download_dir = '/tmp/'
    model_path = os.path.join(download_dir, 'GPT-2-LM-HEAD', 'model.onnx')

    logging.info("onnx load model...")
    download_model(url)
    onnx_model = onnx.load(model_path)

    # inference
    logging.info("preprocessing...")
    input_ids = preprocess()

    logging.info("model compling...")
    dev = device.get_default_device()
    x = tensor.Tensor(device=dev, data=input_ids)
    model = MyModel(onnx_model)

    # verifty the test
    # from utils import load_dataset
    # sg_ir = sonnx.prepare(onnx_model) # run without graph
    # inputs, ref_outputs = load_dataset(
    #     os.path.join('/tmp', 'GPT-2-LM-HEAD', 'test_data_set_0'))
    # outputs = sg_ir.run(inputs)
    # for ref_o, o in zip(ref_outputs, outputs):
    #     np.testing.assert_almost_equal(ref_o, o, 4)

    logging.info("model running...")
    output = []

    for i in range(length):
        logging.info("word {} generating...".format(i))
        y = model.forward(x)
        y = autograd.reshape(y, y.shape[-2:])[-1, :]
        y = tensor.softmax(y)
        y = tensor.to_numpy(y)[0]
        y = np.argsort(y)[-1]
        output.append(y)
        y = np.array([y]).reshape([1, 1, -1]).astype(np.float32)
        y = tensor.Tensor(device=dev, data=y)
        x = tensor.concatenate([x, y], 2)

    text = postprocess(output)
    print(text)


text:
title: Cuboid route
localeTitle: الطريق المكعب
---
## المشكلة 86: طريق مكعبة

هذا هو كعب. [ساعد مجتمعنا على توسيعه](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-86-cuboid-route/index.md) .

[سيساعدك دليل النمط السريع هذا على ضمان قبول طلب السحب](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
declare module '@vxna/mini-html-webpack-template' {
	function template(...args: any[]): string;
	export = template;
}


text:
module TheCommentsManager
  VERSION = "0.0.1"
end


text:
import unittest

from mpf.system.machine import MachineController
from MpfTestCase import MpfTestCase
from mock import MagicMock
import time

class TestBallDevicesHoldCoil(MpfTestCase):

  def getConfigFile(self):
      return 'test_hold_coil.yaml'

  def getMachinePath(self):
      return '../tests/machine_files/ball_device/'

  def test_holdcoil_with_direct_release(self):
      self.machine.coils['hold_coil'].enable = MagicMock()
      self.machine.coils['hold_coil'].disable = MagicMock()
      # after hold switch was posted it should enable the hold_coil
      self.machine.events.post('test_hold_event')
      self.machine.coils['hold_coil'].enable.assert_called_once_with()
      assert not self.machine.coils['hold_coil'].disable.called

      # wait some more. coil should stay active
      self.advance_time_and_run(300)
      self.machine.coils['hold_coil'].enable.assert_called_once_with()
      assert not self.machine.coils['hold_coil'].disable.called

      # we trigger entrance switch
      self.assertEqual(0, self.machine.ball_devices['test'].balls)
      self.machine.coils['hold_coil'].enable = MagicMock()
      self.machine.coils['hold_coil'].disable = MagicMock()
      self.machine.switch_controller.process_switch(name='s_entrance',state=1);
      self.machine.switch_controller.process_switch(name='s_entrance',state=0);

      self.advance_time_and_run(300)
      self.assertEqual(0, self.machine.ball_devices['test'].balls)

      # the device should eject the ball right away because nobody claimed it
      self.machine.coils['hold_coil'].disable.assert_called_once_with()
      assert not self.machine.coils['hold_coil'].enable.called

  def test_holdcoil_which_keeps_ball(self):
      # add one ball
      self.assertEqual(0, self.machine.ball_devices['test2'].balls)
      self.machine.coils['hold_coil2'].enable = MagicMock()
      self.machine.coils['hold_coil2'].disable = MagicMock()
      self.machine.events.post('test_hold_event2')
      self.machine.switch_controller.process_switch(name='s_entrance2',state=1);
      self.machine.switch_controller.process_switch(name='s_entrance2',state=0);

      self.advance_time_and_run(300)
      self.machine.coils['hold_coil2'].enable.assert_called_once_with()
      assert not self.machine.coils['hold_coil2'].disable.called
      self.assertEqual(1, self.machine.ball_devices['test2'].balls)

      # add a second ball
      self.machine.coils['hold_coil2'].enable = MagicMock()
      self.machine.coils['hold_coil2'].disable = MagicMock()
      self.machine.events.post('test_hold_event2')
      self.machine.switch_controller.process_switch(name='s_entrance2',state=1);
      self.machine.switch_controller.process_switch(name='s_entrance2',state=0);
      self.advance_time_and_run(300)
      self.machine_run()
      self.machine.coils['hold_coil2'].enable.assert_called_once_with()
      assert not self.machine.coils['hold_coil2'].disable.called
      self.assertEqual(2, self.machine.ball_devices['test2'].balls)

      # eject one ball
      self.machine.coils['hold_coil2'].enable = MagicMock()
      self.machine.coils['hold_coil2'].disable = MagicMock()
      self.machine.ball_devices['test2'].eject()
      self.advance_time_and_run(0.2)
      self.machine.coils['hold_coil2'].disable.assert_called_once_with()
      assert not self.machine.coils['hold_coil2'].enable.called

      # it should reenable the hold coil after 1s because there is a second ball
      self.machine.coils['hold_coil2'].enable = MagicMock()
      self.machine.coils['hold_coil2'].disable = MagicMock()
      self.advance_time_and_run(2)
      assert not self.machine.coils['hold_coil2'].disable.called
      self.machine.coils['hold_coil2'].enable.assert_called_once_with()
      self.assertEqual(1, self.machine.ball_devices['test2'].balls)

  def test_holdcoil_which_keeps_ball_multiple_entries(self):
      # add one ball
      self.machine.ball_devices['test2'].balls = 1

      # eject one ball
      self.machine.coils['hold_coil2'].enable = MagicMock()
      self.machine.coils['hold_coil2'].disable = MagicMock()
      self.machine.ball_devices['test2'].eject()
      self.advance_time_and_run(0.2)
      self.machine.coils['hold_coil2'].disable.assert_called_once_with()
      assert not self.machine.coils['hold_coil2'].enable.called

      # during the hold add another ball. it should not enable hold now
      self.machine.coils['hold_coil2'].enable = MagicMock()
      self.machine.coils['hold_coil2'].disable = MagicMock()
      self.machine.events.post('test_hold_event2')
      self.machine.switch_controller.process_switch(name='s_entrance2',state=1);
      self.machine.switch_controller.process_switch(name='s_entrance2',state=0);
      self.advance_time_and_run(0.2)
      assert not self.machine.coils['hold_coil2'].disable.called
      assert not self.machine.coils['hold_coil2'].enable.called

      # it should reenable the hold coil after 1s because there is a second ball
      self.machine.coils['hold_coil2'].enable = MagicMock()
      self.machine.coils['hold_coil2'].disable = MagicMock()
      self.advance_time_and_run(2)
      assert not self.machine.coils['hold_coil2'].disable.called
      self.machine.coils['hold_coil2'].enable.assert_called_once_with()
      self.assertEqual(1, self.machine.ball_devices['test2'].balls)

      # eject that ball. coil should stay off
      self.machine.coils['hold_coil2'].enable = MagicMock()
      self.machine.coils['hold_coil2'].disable = MagicMock()
      self.machine.ball_devices['test2'].eject()
      self.advance_time_and_run(300)
      self.machine.coils['hold_coil2'].disable.assert_called_once_with()
      assert not self.machine.coils['hold_coil2'].enable.called
      self.assertEqual(0, self.machine.ball_devices['test2'].balls)


text:
package com.coremedia.iso;

import java.nio.ByteBuffer;

public final class IsoTypeReaderVariable {

    public static long read(ByteBuffer bb, int bytes) {
        switch (bytes) {
            case 1:
                return IsoTypeReader.readUInt8(bb);
            case 2:
                return IsoTypeReader.readUInt16(bb);
            case 3:
                return IsoTypeReader.readUInt24(bb);
            case 4:
                return IsoTypeReader.readUInt32(bb);
            case 8:
                return IsoTypeReader.readUInt64(bb);
            default:
                throw new RuntimeException("I don't know how to read " + bytes + " bytes");
        }

    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.spring.cloud.core.resource;

import com.azure.storage.file.share.ShareClient;
import com.azure.storage.file.share.ShareServiceClient;
import com.azure.storage.file.share.models.ListSharesOptions;
import com.azure.storage.file.share.models.ShareItem;
import org.springframework.core.io.ProtocolResolver;
import org.springframework.core.io.Resource;

import java.util.stream.Stream;

/**
 * A {@link ProtocolResolver} implementation for the {@code azure-file://} protocol.
 */
public final class AzureStorageFileProtocolResolver extends AbstractAzureStorageProtocolResolver {

    private ShareServiceClient shareServiceClient;

    /**
     * The storageType of current protocolResolver.
     *
     * @return StorageType.FILE;
     */
    @Override
    protected StorageType getStorageType() {
        return StorageType.FILE;
    }

    @Override
    protected Stream<StorageContainerItem> listStorageContainers(String containerPrefix) {
        ListSharesOptions options = new ListSharesOptions();

        options.setPrefix(containerPrefix);
        options.setIncludeDeleted(false);
        options.setIncludeMetadata(false);
        options.setIncludeSnapshots(false);
        return getShareServiceClient().listShares(options, null, null)
                                 .stream()
                                 .map(ShareItem::getName)
                                 .map(StorageContainerItem::new);
    }

    @Override
    protected StorageContainerClient getStorageContainerClient(String name) {
        return new StorageFileContainerClient(name);
    }

    private class StorageFileContainerClient implements StorageContainerClient {

        private final String name;

        StorageFileContainerClient(String name) {
            this.name = name;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public Stream<StorageItem> listItems(String itemPrefix) {
            ShareClient shareClient = getShareServiceClient().getShareClient(name);
            if (shareClient.exists()) {
                return shareClient.getRootDirectoryClient().listFilesAndDirectories(itemPrefix, null, null, null)
                                  .stream()
                                  .filter(file -> !file.isDirectory())
                                  .map(file -> new StorageItem(name, file.getName(), getStorageType()));
            } else {
                return Stream.empty();
            }
        }
    }

    @Override
    protected Resource getStorageResource(String location, Boolean autoCreate) {
        return new StorageFileResource(getShareServiceClient(), location, autoCreate);
    }

    private ShareServiceClient getShareServiceClient() {
        if (shareServiceClient == null) {
            shareServiceClient = beanFactory.getBean(ShareServiceClient.class);
        }
        return shareServiceClient;
    }
}


text:
'use strict'

// hapi depends on node 0.10.x
if (process.version.split('.')[1] < 10) {
  console.log('TAP version 13\n# disabled because of incompatibility')
  console.log('ok 1 nothing to do\n\n1..1\n\n# ok')
  process.exit(0)
}

var path    = require('path')
  , test    = require('tap').test
  , request = require('request')
  , helper  = require(path.join(__dirname, '..', '..', 'lib', 'agent_helper.js'))

test("Hapi vhost support", function (t) {
  t.plan(1)

  t.test("should not explode when using vhosts", function (t) {
    var agent  = helper.instrumentMockedAgent()
      , hapi   = require('hapi')
      , server = new hapi.Server()

    server.connection({
      port: 8089
    })

    // disabled by default
    agent.config.capture_params = true

    agent.on('transactionFinished', function (transaction) {
      t.ok(transaction.trace, 'transaction has a trace.')
      t.deepEqual(transaction.trace.parameters, {id: 1337, name: 'hapi'}, 'parameters should have name and id')

      helper.unloadAgent(agent)
      server.stop(function () {
        t.end()
      })
    })

    server.route({
      method: 'GET',
      path: '/test/{id}/',
      vhost: 'localhost',
      handler: function (request, reply) {
        t.ok(agent.getTransaction(), "transaction is available")

        reply({status : 'ok'})
      }
    })

    server.route({
      method: 'GET',
      path: '/test/{id}/2',
      vhost: 'localhost',
      handler: function (request, reply) {
        t.ok(agent.getTransaction(), "transaction is available")

        reply({status : 'ok'})
      }
    })

    server.start(function () {
      request.get('http://localhost:8089/test/1337/2?name=hapi',
                  {json : true},
                  function (error, res, body) {

        t.equal(res.statusCode, 200, "nothing exploded")
        t.deepEqual(body, {status : 'ok'}, "got expected response")
      })
    })
  })
})


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${packageName}.${activityClass}" >

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

</RelativeLayout>


text:
var vumigo = require("vumigo_v01");
var jed = require("jed");

if (api === undefined) {
  // testing hook (supplies api when it is not passed in by the real sandbox)
  var api = this.api = new vumigo.dummy_api.DummyApi();
}

var FreeText = vumigo.states.FreeText;
var EndState = vumigo.states.EndState;
var ChoiceState = vumigo.states.ChoiceState;
var PaginatedChoiceState = vumigo.states.PaginatedChoiceState;
var Choice = vumigo.states.Choice;
var InteractionMachine = vumigo.state_machine.InteractionMachine;
var StateCreator = vumigo.state_machine.StateCreator;
var HttpApi = vumigo.http_api.HttpApi;
var Promise = vumigo.promise.Promise;

function Hangman() {
    var self = this;
    StateCreator.call(self, 'new_game');

    self.word_url = 'http://randomword.setgetgo.com/get.php';

    self.load_game = function (msisdn) {
        var p = im.api_request('kv.get', {
            key: msisdn
        });
        p.add_callback(function (result) {
            return result.value;
        });
        return p;
    };

    self.save_game = function (msisdn, game) {
        var p = im.api_request('kv.set', {
            key: msisdn,
            value: game
        });
        p.add_callback(function() {
            return game;
        });
        return p;
    };

    self.draw_board = function (game) {
        var word = game.word.split('').map(function (letter) {
            if(game.guesses.indexOf(letter) > -1)
                return letter;
            return '_';
        }).join('');
        var guesses = game.guesses.join('');
        if(self.won(game)) {
            return [
                game.msg,
                'The word was: ' + word
            ].join('\n');
        } else {
            return [
                game.msg,
                'Word: ' + word,
                'Letters guessed so far: ' + guesses,
                game.prompt + '(0 to quit):'
            ].join('\n');
        }
    };

    self.get_random_word = function () {
        var p = im.api_request('http.get', {
            'url': self.word_url,
            'headers': {
                'content-type': ['text/plain']
            }
        });
        p.add_callback(function (result) {
            return result.body.toLowerCase().trim();
        });
        p.add_callback(function (word) {
            var lp = im.log('Word: "' + word + '"');
            lp.add_callback(function() {
                return word;
            });
            return lp;
        });
        return p;
    };

    self.create_new_game = function (word) {
        return {
            msg: 'New game!',
            word: word,
            guesses: [],
            prompt: ''
        };
    };

    self.game_won = function (game) {
        return game.word.split('').filter(function(letter) {
            return game.guesses.indexOf(letter) == -1;
        }).length === 0;
    };

    self.game_logic_callback = function(im, game) {
        return function (content, done) {
            var p = self.game_logic(im, game, content);
            p.add_callback(function (next_state) {
                done(next_state);
            });
            return p;
        };
    };

    self.game_logic = function (im, game, content) {
        var next_state;
        content = (content || '').toLowerCase();
        if(!content) {
            game.msg = 'Some input required please.';
            game.prompt = 'Enter next guess';
            next_state = 'resume_game';
        } else if (content.length > 1) {
            game.msg = 'Single character only please.';
            game.prompt = 'Enter next guess';
            next_state = 'resume_game';
        } else if (content == '0') {
            next_state = 'end_game';
        } else if (game.guesses.indexOf(content) > -1) {
            game.msg = 'You\'ve already guessed \'' + content + '\'.';
            game.prompt = 'Enter next guess';
            next_state = 'resume_game';
        } else {
            game.guesses.push(content);
            im.log('checking', game.word, 'for', content);
            if(game.word.indexOf(content) > -1) {
                game.msg = 'Word contains at least one \'' + content + '\'! :D';
            } else {
                game.msg = 'Word contains no \'' + content + '\'. :(';
            }
            game.prompt = 'Enter next guess';
            next_state = 'resume_game';
        }

        if(self.won(game)) {
            game.msg = self.victory_message(game);
            next_state = 'win';
        }

        var p = self.save_game(im.user_addr, game);
        p.add_callback(function (game) {
            return {
                next_state: next_state,
                game: game
            };
        });
        return p;
    };

    self.victory_message = function(game) {
        var uniques = game.word.length;
        var guesses = game.guesses.length;
        var win_messages = [
            [1, "Flawless victory!"],
            [1.5, "Epic victory!"],
            [2, "Standard victory!"],
            [3, "Sub-par victory!"],
            [4, "Random victory!"]
        ];

        for(var i=0; i < win_messages.length; i++) {
            var factor = win_messages[i][0],
                msg = win_messages[i][1];

            if(guesses <= (uniques * factor)) {
                return msg;
            }
        }
        return "Button mashing!";
    };

    self.won = function(game) {
        for(var i = 0; i < game.word.length; i++) {
            var letter = game.word[i];
            if(game.guesses.indexOf(letter) == -1 ) {
                return false;
            }
        }
        return true;
    };

    self.add_creator('new_game', function (state_name, im) {
        var p = self.load_game(im.user_addr);
        // NOTE: I suspect this is necessary because this state
        // is called twice
        p.add_callback(function (game) {
            if(game && !self.won(game)) {
                return game.word;
            } else {
                return self.get_random_word();
            }
        });
        p.add_callback(function (word) {
            return self.save_game(im.user_addr,
                                  self.create_new_game(word));
        });
        p.add_callback(function (game) {
            return new FreeText(
                state_name,
                'resume_game',
                self.draw_board(game)
            );
        });
        return p;
    });

    self.add_creator('resume_game', function (state_name, im) {
        var p = self.load_game(im.user_addr);
        p.add_callback(function (game) {
            //  Yoink! I need to get a the content outside of
            //  whatever state the machine thinks I'm in.
            var content = im.msg.content;
            return self.game_logic(im, game, content);
        });
        p.add_callback(function (game_state) {
            return new FreeText(
                state_name,
                game_state.next_state,
                self.draw_board(game_state.game)
            );
        });
        return p;
    });

    self.add_creator('win', function (state_name, im) {
        var p = self.load_game(im.user_addr);
        p.add_callback(function (game) {
            return new EndState(
                state_name,
                self.draw_board(game),
                'new_game');
        });
        return p;
    });

    self.add_state(new EndState(
        'end_game',
        'Adieu!',
        'new_game'));
}

// launch app
var states = new Hangman();
var im = new InteractionMachine(api, states);
im.attach();


text:
import { set } from 'lodash';
import { getModule, addNpmScriptMemory, addNpmPackageMemory, replaceCodeMemory } from '../utils';

export default async function generateTestingJasmine(params) {
  switch (params.framework) {
    case 'express':
      await addNpmPackageMemory('jasmine', params, true);

      // Server-side tests
      set(params.build, ['spec', 'server.spec.js'], await getModule('testing/jasmine/server.spec.js'));
      set(params.build, ['spec', 'support', 'jasmine.json'], await getModule('testing/jasmine/jasmine.json'));

      if (params.jsFramework) {
        await addNpmPackageMemory('karma', params, true);
        await addNpmPackageMemory('karma-coverage', params, true);
        await addNpmPackageMemory('karma-jasmine', params, true);
        await addNpmPackageMemory('karma-phantomjs-launcher', params, true);
        await addNpmPackageMemory('phantomjs-prebuilt', params, true);

        // Client-side tests
        switch (params.jsFramework) {
          case 'angularjs':
            let karmaConfPath;

            if (params.buildTool === 'gulp') {
              karmaConfPath = ['app', 'karma.conf.js'];
              set(params.build, karmaConfPath, await getModule('testing/angularjs/karma.conf.js'));
              set(params.build, ['app', 'test', 'unit', 'controllers', 'contact.spec.js'], await getModule('testing/jasmine/angularjs/unit/contact.spec.js'));
              await addNpmScriptMemory('test:client', 'karma start app/karma.conf.js --single-run', params);
            } else {
              karmaConfPath = ['karma.conf.js'];
              set(params.build, karmaConfPath, await getModule('testing/angularjs/karma.conf-nobuild.js'));
              set(params.build, ['public', 'js', 'test', 'unit', 'controllers', 'contact.spec.js'], await getModule('testing/jasmine/angularjs/unit/contact.spec.js'));
              await addNpmScriptMemory('test:client', 'karma start --single-run', params);
            }

            await replaceCodeMemory(params, karmaConfPath.join('/'), 'KARMA_TESTS', await getModule('testing/angularjs/karma-tests-jasmine.js'));
            await replaceCodeMemory(params, karmaConfPath.join('/'), 'KARMA_PLUGINS', await getModule('testing/angularjs/karma-plugins-jasmine.js'));
            await replaceCodeMemory(params, karmaConfPath.join('/'), 'KARMA_FRAMEWORKS', await getModule('testing/angularjs/karma-frameworks-jasmine.js'));
            break;
          default:
            break;
        }

        // NPM scripts for both server and client tests
        await addNpmScriptMemory('test', 'npm run test:server && npm run test:client', params);
        await addNpmScriptMemory('test:server', 'jasmine', params);
      } else {
        // NPM script only for server tests
        await addNpmScriptMemory('test', 'jasmine', params);
      }
      break;
    case 'meteor':
      break;
    default:
  }
}


text:
package org.lable.oss.dynamicconfig.core.commonsconfiguration;

import org.apache.commons.configuration.tree.ConfigurationNode;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Utility class that converts {@link org.apache.commons.configuration.tree.ConfigurationNode} instances to a plain
 * Java object tree.
 */
public class Objectifier {

    /**
     * Process a node in the Config tree, and store it with its parent node in an object tree.
     * <p>
     * This method recursively calls itself to walk a Config tree.
     *
     * @param parent Parent of the current node, as represented in the Config tree.
     * @return An object tree.
     */
    public static Object traverseTreeAndEmit(ConfigurationNode parent) {
        if (parent.getChildrenCount() == 0) {
            return parent.getValue();
        } else {
            Map<String, Object> map = new LinkedHashMap<>();
            for (Object o : parent.getChildren()) {
                ConfigurationNode child = (ConfigurationNode) o;
                String nodeName = child.getName();
                addToMap(map, nodeName, traverseTreeAndEmit(child));
            }
            return map;
        }
    }

    @SuppressWarnings("unchecked")
    static void addToMap(Map<String, Object> map, String nodeName, Object value) {
        if (map.containsKey(nodeName)) {
            // Trying to add an item with a key that is already used. This means we are
            // dealing with a list.
            Object existing = map.get(nodeName);
            List<Object> list;
            if (existing instanceof List) {
                // Unchecked cast, but correct.
                list = (List<Object>) existing;
            } else {
                list = new ArrayList<>();
                list.add(existing);
            }
            list.add(value);
            map.put(nodeName, list);
        } else {
            map.put(nodeName, value);
        }
    }
}


text:
package com.views;

import java.io.File;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.ImageView;
import com.manniu.manniu.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

public class UserImgShow extends Activity{
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_img_show);
		Bundle bundle = this.getIntent().getExtras();
		String[] trans = bundle.getStringArray("imgs");
		String url = getResources().getString(R.string.server_address)+File.separator+trans[0];
		ImageView img = (ImageView) findViewById(R.id.user_img);

		DisplayImageOptions options  = new DisplayImageOptions.Builder()
		//.showImageForEmptyUri(R.drawable.images_nophoto_bg)
		.showImageOnFail(R.drawable.event_list_fail_pic)
		//.showImageOnLoading(R.drawable.progress_msg_loading)
		.resetViewBeforeLoading(true)
		.cacheOnDisk(true)
		.imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.considerExifParams(true)
		.displayer(new FadeInBitmapDisplayer(300))
		.build();
		ImageLoader.getInstance().displayImage(url, img, options, null);

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		finish();
		return true;
	}

	public void onBackPressed(){
		finish();
		super.onBackPressed();
	}
}


text:
<?php

namespace RoommateBundle\Controller;

use RoommateBundle\Entity\EmailAddress;
use RoommateBundle\Entity\Roommate\Contact;
use RoommateBundle\Entity\Roommate\House;
use RoommateBundle\Entity\Roommate\Roommate;
use RoommateBundle\Form\ContactType;
use RoommateBundle\Provider\AuthenticatedUser;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ContactController extends Controller
{
    public function browseAction()
    {
        $roommates = $this->get('roommate.repositories.roommate_repository')->fetchForHouse($this->getCurrentHouseId());
        $contacts = $this->get('roommate.repositories.contact_repository')->fetchForHouse($this->getCurrentHouseId());

        $groupedContacts = [];
        foreach ($contacts as $contact) {
            $letter = strtoupper($contact['name'][0]);

            if (!isset($groupedContacts[$letter])) {
                $groupedContacts[$letter] = [];
            }

            $groupedContacts[$letter][] = $contact;
        }

        return $this->render('RoommateBundle:Contact:browse.html.twig', [
            'groupedContacts' => $groupedContacts,
            'roommates' => $roommates,
        ]);
    }

    public function addAction()
    {
        $form = $this->createForm(ContactType::class);

        return $this->render('RoommateBundle:Contact:edit.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    public function processAddAction(Request $request)
    {
        $form = $this->createForm(ContactType::class);
        $form->handleRequest($request);

        if (!$form->isValid()) {
            return $this->render('RoommateBundle:Contact:edit.html.twig', [
                'form' => $form->createView(),
            ]);
        }

        $manager = $this->getDoctrine()->getManager();
        $contact = new Contact(
            $manager->find(House::class, $this->getCurrentHouseId()),
            $form->get('name')->getData(),
            $form->get('nickname')->getData() ?: null,
            $form->get('email')->getData() ? new EmailAddress($form->get('email')->getData()) : null,
            $form->get('phoneNumber')->getData() ?: null
        );
        $this->get('roommate.repositories.contact_repository')->add($contact);
        $manager->flush();

        $request->getSession()->getFlashBag()->add(
            'success',
            sprintf('Contact "%s" added', $contact->getName())
        );

        return $this->redirectToRoute('contacts_edit', ['contact' => $contact->getId()]);
    }

    public function editAction($contact)
    {
        $contact = $this->getCurrentContact($contact);
        $form = $this->createForm(ContactType::class, [
            'name' => $contact->getName(),
            'nickname' => $contact->getNickname(),
            'email' => (string)$contact->getEmail(),
            'phoneNumber' => $contact->getPhoneNumber(),
        ]);

        return $this->render('RoommateBundle:Contact:edit.html.twig', [
            'contact' => $contact->getName(),
            'form' => $form->createView(),
        ]);
    }

    public function processEditAction($contact, Request $request)
    {
        $contact = $this->getCurrentContact($contact);
        $form = $this->createForm(ContactType::class);
        $form->handleRequest($request);

        if (!$form->isValid()) {
            return $this->render('RoommateBundle:Contact:edit.html.twig', [
                'contact' => $contact->getName(),
                'form' => $form->createView(),
            ]);
        }

        $contact->setName($form->get('name')->getData());
        $contact->setNickname($form->get('nickname')->getData() ?: null);
        $contact->setEmail($form->get('email')->getData() ? new EmailAddress($form->get('email')->getData()) : null);
        $contact->setPhoneNumber($form->get('phoneNumber')->getData() ?: null);
        $this->getDoctrine()->getManager()->flush();

        $request->getSession()->getFlashBag()->add(
            'success',
            sprintf('Contact "%s" updated', $contact->getName())
        );

        return $this->redirectToRoute('contacts_edit', ['contact' => $contact->getId()]);
    }

    public function deleteAction($contact, Request $request)
    {
        $contact = $this->getCurrentContact($contact);

        $contact->delete();
        $this->getDoctrine()->getManager()->flush();

        $request->getSession()->getFlashBag()->add(
            'success',
            sprintf('Contact "%s" deleted', $contact->getName())
        );

        return $this->redirectToRoute('contacts_browse');
    }

    private function getCurrentHouseId()
    {
        /** @var AuthenticatedUser $user */
        $user = $this->getUser();
        return $user->getHouseId();
    }

    private function getCurrentContact($contactId)
    {
        $contact = $this->get('roommate.repositories.contact_repository')->findForHouse(
            $contactId,
            $this->getCurrentHouseId()
        );
        if (!$contact) {
            throw new NotFoundHttpException();
        }
        return $contact;
    }
}


text:
package me.chanjar.weixin.cp.bean.message;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import lombok.Data;
import lombok.EqualsAndHashCode;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.util.xml.XStreamReplaceNameConverter;

/**
 * The type Wx cp xml out update btn message.
 *
 * @author nickname263  created on  2021-09-23
 */
@XStreamAlias("xml")
@Data
@EqualsAndHashCode(callSuper = false)
public class WxCpXmlOutUpdateBtnMessage extends WxCpXmlOutMessage {
  private static final long serialVersionUID = 976182367423048138L;
  @XStreamAlias("Button")
  @XStreamConverter(value = XStreamReplaceNameConverter.class)
  private String replaceName;

  /**
   * Instantiates a new Wx cp xml out update btn message.
   */
  public WxCpXmlOutUpdateBtnMessage() {
    this.msgType = WxConsts.XmlMsgType.UPDATE_BUTTON;
  }

}


text:
"""Tests the win_symlink_fast functionality."""

import sys
import unittest

if __name__ == '__main__' and sys.platform == 'win32':
  from starboard.tools import port_symlink_test  # pylint: disable=g-import-not-at-top
  from starboard.tools import util  # pylint: disable=g-import-not-at-top
  from starboard.tools import win_symlink  # pylint: disable=g-import-not-at-top
  from starboard.tools import win_symlink_fast  # pylint: disable=g-import-not-at-top

  # Override the port_symlink_test symlink functions to point to our win_symlink
  # and win_symlink_fast versions.
  def MakeSymLink(*args, **kwargs):
    return win_symlink_fast.FastCreateReparseLink(*args, **kwargs)

  def IsSymLink(*args, **kwargs):
    return win_symlink_fast.FastIsReparseLink(*args, **kwargs)

  def ReadSymLink(*args, **kwargs):
    return win_symlink_fast.FastReadReparseLink(*args, **kwargs)

  def Rmtree(*args, **kwargs):
    return win_symlink.RmtreeShallow(*args, **kwargs)

  def OsWalk(*args, **kwargs):
    return win_symlink.OsWalk(*args, **kwargs)

  port_symlink_test.MakeSymLink = MakeSymLink
  port_symlink_test.IsSymLink = IsSymLink
  port_symlink_test.ReadSymLink = ReadSymLink
  port_symlink_test.Rmtree = Rmtree
  port_symlink_test.OsWalk = OsWalk

  # Makes a unit test available to the unittest.main (through magic).
  class WinSymlinkTest(port_symlink_test.PortSymlinkTest):
    pass

  util.SetupDefaultLoggingConfig()
  unittest.main(verbosity=2)


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

namespace MatterHackers.MatterControl.PrinterCommunication.Io
{
    public class PrinterIoGCodeFile : PrinterIoBase
    {
        GCodeFile loadedGCode = new GCodeFile();
        public PrinterIoGCodeFile(GCodeFile loadedGCode)
            : base(null)
        {
            this.loadedGCode = loadedGCode;
        }
    }
}


text:
title: "Deploy to Swarm"
keywords: swarm, swarm services, stacks
description: Learn how to describe and deploy a simple application on Docker Swarm.
redirect_from:
- /get-started/part4/
---

## Prerequisites

- Download and install Docker Desktop as described in [Get Docker](../get-docker.md).
- Work through containerizing an application in [Part 2](02_our_app.md).
- Make sure that Swarm is enabled on your Docker Desktop by typing `docker system info`, and looking for a message `Swarm: active` (you might have to scroll up a little).

  If Swarm isn't running, simply type `docker swarm init` in a shell prompt to set it up.

## Introduction

Now that we've demonstrated that the individual components of our application run as stand-alone containers and shown how to deploy it using Kubernetes, let's look at how to arrange for them to be managed by Docker Swarm. Swarm provides many tools for scaling, networking, securing and maintaining your containerized applications, above and beyond the abilities of containers themselves.

In order to validate that our containerized application works well on Swarm, we'll use Docker Desktop's built in Swarm environment right on our development machine to deploy our application, before handing it off to run on a full Swarm cluster in production. The Swarm environment created by Docker Desktop is _fully featured_, meaning it has all the Swarm features your app will enjoy on a real cluster, accessible from the convenience of your development machine.

## Describe apps using stack files

Swarm never creates individual containers like we did in the previous step of this tutorial. Instead, all Swarm workloads are scheduled as _services_, which are scalable groups of containers with added networking features maintained automatically by Swarm. Furthermore, all Swarm objects can and should be described in manifests called _stack files_. These YAML files describe all the components and configurations of your Swarm app, and can be used to easily create and destroy your app in any Swarm environment.

Let's write a simple stack file to run and manage our Todo app, the container `getting-started` image created in [Part 2](02_our_app.md) of the Quickstart tutorial. Place the following in a file called `bb-stack.yaml`:

```yaml
version: '3.7'

services:
  bb-app:
    image: getting-started
    ports:
      - "8000:3000"
```

In this Swarm YAML file, we have just one object: a `service`, describing a scalable group of identical containers. In this case, you'll get just one container (the default), and that container will be based on your `getting-started` image created in [Part 2](02_our_app.md) of the Quickstart tutorial. In addition, We've asked Swarm to forward all traffic arriving at port 8000 on our development machine to port 3000 inside our getting-started container.

> **Kubernetes Services and Swarm Services are very different!** Despite the similar name, the two orchestrators mean very different things by the term 'service'. In Swarm, a service provides both scheduling _and_ networking facilities, creating containers and providing tools for routing traffic to them. In Kubernetes, scheduling and networking are handled separately: _deployments_ (or other controllers) handle the scheduling of containers as pods, while _services_ are responsible only for adding networking features to those pods.

## Deploy and check your application

1.  Deploy your application to Swarm:

    ```console
    $ docker stack deploy -c bb-stack.yaml demo
    ```

    If all goes well, Swarm will report creating all your stack objects with no complaints:

    ```shell
    Creating network demo_default
    Creating service demo_bb-app
    ```

    Notice that in addition to your service, Swarm also creates a Docker network by default to isolate the containers deployed as part of your stack.

2.  Make sure everything worked by listing your service:

    ```console
    $ docker service ls
    ```

    If all has gone well, your service will report with 1/1 of its replicas created:

    ```shell
    ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
    il7elwunymbs        demo_bb-app         replicated          1/1                 getting-started:latest   *:8000->3000/tcp
    ```

    This indicates 1/1 containers you asked for as part of your services are up and running. Also, we see that port 8000 on your development machine is getting forwarded to port 3000 in your getting-started container.

3.  Open a browser and visit your Todo app at `localhost:8000`; you should see your Todo application, the same as when we ran it as a stand-alone container in Part 2 of the Quickstart tutorial.

4.  Once satisfied, tear down your application:

    ```console
    $ docker stack rm demo
    ```

## Conclusion

At this point, we have successfully used Docker Desktop to deploy our application to a fully-featured Swarm environment on our development machine. We haven't done much with Swarm yet, but the door is now open: you can begin adding other components to your app and taking advantage of all the features and power of Swarm, right on your own machine.

In addition to deploying to Swarm, we have also described our application as a stack file. This simple text file contains everything we need to create our application in a running state; we can check it into version control and share it with our colleagues, allowing us to distribute our applications to other clusters (like the testing and production clusters that probably come after our development environments) easily.

## Swarm and CLI references

Further documentation for all new Swarm objects and CLI commands used in this article are available here:

 - [Swarm Mode](../engine/swarm/index.md)
 - [Swarm Mode Services](../engine/swarm/how-swarm-mode-works/services.md)
 - [Swarm Stacks](../engine/swarm/stack-deploy.md)
 - [`docker stack *`](/engine/reference/commandline/stack/)
 - [`docker service *`](/engine/reference/commandline/service/)