text:
Guess the Country
=================

Due at 2:00pm on Tuesday, September 27

This is the last daily assignment before we move on to Chapter 4. In it,
you'll make sure you understand the two most important ways to handle
complex conditional statements.

Prerequisites
-------------

Your Little Quiz (daily 07) should be running well. If you are having problems
with it, you need to get help from the instructor before long. Things are
about to get more complicated soon, and this will continue until the end of
the semester.

Instructions
------------

Implement a simple guessing game in the file `country_guess_compound.c++`. The
game lets the computer try to guess the country the user is thinking of in
three steps. Here are some sample runs. It is not a very smart program, but
that is OK. **MAKE THE OUTPUT LOOK EXACTLY LIKE THE SAMPLE**. You don't need
to detect or guard against bad input. You can assume the user is doing it
right.

Sample 1:
```
Is your country in (1) Africa (2) the Americas (3) Eurasia (4) Oceania? 3
Is your country (1) more east or (2) more west? 2

Then your country must be Portugal!
```

Sample 2:
```
Is your country in (1) Africa (2) the Americas (3) Eurasia (4) Oceania? 1
Is your country (1) more east or (2) more west? 1

Then your country must be Kenya!
```

Sample 3:
```
Is your country in (1) Africa (2) the Americas (3) Eurasia (4) Oceania? 2
Is your country (1) more east or (2) more west? 1

Then your country must be Brazil!
```

Here is a table you can use to fill in the 8 different values if you are too
lazy to think of the answers yourself (you can use whatever answers you want,
but the questions have to be right).

|      | Africa | Americas | Eurasia  | Oceania    |
|------|--------|----------|----------|------------|
| East | Kenya  | Brazil   | Japan    | Fiji       |
| West | Ghana  | Chile    | Portugal | New Guinea |

### Compound conditions only: no nesting

To receive credit, your program in `country_guess_compound.c++` must not use
any nested `if` statements, like this:

    if (condition1)
    {
        if (condition2)
        {
            do stuff
        }
        else
        {
            do stuff
        }
    }

Achieve the results you need with compound conditions, that is, ones that involve
logical operators such as `&&`, `||`, and `!`.

Finish the workshop at home
---------------------------

When you have finished `country_guess_compound.c++`, make a copy of it called
`country_guess_nested.c++`. Rewrite the code in the latter file so that it only
uses nested `if` statements and avoids all logical operators in the conditions.

It may help to remember the keyboard commands to copy, reorder, and reindent lines.

For Windows:

Duplicate line: Ctrl+Shift+D
Move line up/down: Ctrl+Shift+Up/Down
Indent/Dedent: Ctrl+[/Ctrl+]

For Mac:
Duplicate line: Cmd+Shift+D
Move line up/down: Cmd+Ctrl+Up/Down
Indent/Dedent: Cmd+[/Cmd+]

Submitting your work:
--------------------

The following files are due at 2:00pm on Tuesday, September 27:

* `country_guess_compound.c++`
* `country_guess_nested.c++`


text:
<TITLE>Review for Double Jeopardy (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Double Jeopardy (1999)

reviewed by
Fontaine Lien

"Double Jeopardy" Review
by Fontaine Lien
WARNING: CONTAINS PLOT SPOILERS

That is, unless you're one of those people who have seen the preview a
thousand times on TV or in the theaters.  I can tell you one thing
now: they gave the entire movie away.  Why someone would want to base
an entire movie on one premise and then give that crucial detail away
in the trailers is beyond me.  However, if they *hadn't* given it
away, the film would've still been suprisingly devoid of suspense
given its subject matter.  Obviously, the producers thought they could
remake "The Deep End of the Ocean," throw in Tommy Lee Jones and a
couple of cliches and call it an action drama.

"Double Jeopardy" offers solid acting from Ashley Judd and Tommy Lee
Jones, who got first billing even though he didn't see to be on screen
half as much as Judd did.  It also offers some genuinely funny,
clever, or full-of-tension moments (my favorite: Judd waking up in the
coffin), but none of that can salvage the film from its insanely
predictable plot.  Half the time I'm wondering whether I'm watching
one of those overhyped TV miniseries, which always turn out to be less
exciting than advertised.  Judging by the beginning, end, and a huge
chunk of the middle, I might have been watching a special Hallmark
presentation too.  The movie's stretching for an almost two hour long
film with only 30 minutes worth of material.  Implausible material, no
less.  Loose interpretation of one of the amendments aside, too many
times in the movie I thought, "That is *not* possible*." That kind of
stuff is excusable in popcorn movies, but not one like "Double
Jeopardy" that tries to pass itself off as serious drama.  Everything
seems dragged out, overplayed.  When they should've kept us in the
dark, they let the cat out of the bag too early.

Sorry Alex, next category please.

Rating: C- (First viewing, 10/1/99)

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews

redpajama_set_name: RedPajamaGithub


text:
require 'aptible/resource'

module Aptible
  module Auth
    class Resource < Aptible::Resource::Base
      def namespace
        'Aptible::Auth'
      end

      def root_url
        Aptible::Auth.configuration.root_url
      end
    end
  end
end

require 'aptible/auth/client'
require 'aptible/auth/invitation'
require 'aptible/auth/membership'
require 'aptible/auth/organization'
require 'aptible/auth/role'
require 'aptible/auth/session'
require 'aptible/auth/token'
require 'aptible/auth/user'
require 'aptible/auth/ssh_key'


text:
require('react/addons');

var roomStore = require('../room-store.js');

describe('RoomStore', function () {
  describe('onCreateRoom', function () {
    xit('adds a new room to the store', function () {
      var roomsBefore = roomStore.getRooms();
      roomStore.onCreateRoom();
      var roomsAfter = roomStore.getRooms();

      expect(roomsAfter.length).toEqual(roomsBefore.length + 1);

      var createdRoom = roomsAfter[ roomsAfter.length - 1 ];
      expect(createdRoom.title).toBeDefined();
      expect(createdRoom.devices.length).toEqual(0);
    });
  });
});


text:
package com.intellij.execution.junit;

import com.intellij.execution.*;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.execution.configurations.RuntimeConfigurationException;
import com.intellij.execution.configurations.RuntimeConfigurationWarning;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.testframework.SearchForTestsTask;
import com.intellij.execution.testframework.SourceScope;
import com.intellij.execution.testframework.TestSearchScope;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PackageScope;
import com.intellij.psi.util.ClassUtil;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import com.intellij.rt.execution.junit.JUnitStarter;
import gnu.trove.THashSet;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.function.Predicate;

public class TestPackage extends TestObject {

  public TestPackage(JUnitConfiguration configuration, ExecutionEnvironment environment) {
    super(configuration, environment);
  }

  @Nullable
  @Override
  public SourceScope getSourceScope() {
    final JUnitConfiguration.Data data = getConfiguration().getPersistentData();
    return data.getScope().getSourceScope(getConfiguration());
  }

  @Override
  public SearchForTestsTask createSearchingForTestsTask() {
    final JUnitConfiguration.Data data = getConfiguration().getPersistentData();

    return new SearchForTestsTask(getConfiguration().getProject(), myServerSocket) {
      private final THashSet<PsiClass> myClasses = new THashSet<>();
      @Override
      protected void search() {
        myClasses.clear();
        final SourceScope sourceScope = getSourceScope();
        final Module module = getConfiguration().getConfigurationModule().getModule();
        if (sourceScope != null && !JUnitStarter.JUNIT5_PARAMETER.equals(getRunner())) {
          DumbService instance = DumbService.getInstance(myProject);
          try {
            instance.setAlternativeResolveEnabled(true);
            final TestClassFilter classFilter = getClassFilter(data);
            LOG.assertTrue(classFilter.getBase() != null);
            long start = System.currentTimeMillis();
            if (Registry.is("junit4.search.4.tests.in.classpath", false)) {
              String packageName = getPackageName(data);
              String[] classNames = TestClassCollector.collectClassFQNames(packageName, getRootPath(), getConfiguration(), TestPackage::createPredicate);
              PsiManager manager = PsiManager.getInstance(myProject);
              Arrays.stream(classNames)
                .filter(className -> acceptClassName(className)) //check patterns
                .map(name -> ReadAction.compute(() -> ClassUtil.findPsiClass(manager, name, null, true, classFilter.getScope())))
                .filter(aClass -> aClass != null)
                .forEach(myClasses::add);
              LOG.info("Found tests in " + (System.currentTimeMillis() - start));
            }
            else {
              ConfigurationUtil.findAllTestClasses(classFilter, module, myClasses);
            }
          }
          catch (CantRunException ignored) {}
          finally {
            instance.setAlternativeResolveEnabled(false);
          }
        }
      }

      @Override
      protected void onFound() {

        try {
          addClassesListToJavaParameters(myClasses,
                                         psiClass -> psiClass != null ? JavaExecutionUtil.getRuntimeQualifiedName(psiClass) : null, getPackageName(data), createTempFiles(), getJavaParameters());
        }
        catch (ExecutionException ignored) {}
      }
    };
  }

  @Nullable
  protected Path getRootPath() {
    Module module = getConfiguration().getConfigurationModule().getModule();
    boolean chooseSingleModule = getConfiguration().getTestSearchScope() == TestSearchScope.SINGLE_MODULE;
    return TestClassCollector.getRootPath(module, chooseSingleModule);
  }

  protected boolean acceptClassName(String className) {
    return true;
  }

  protected boolean createTempFiles() {
    return false;
  }

  protected String getPackageName(JUnitConfiguration.Data data) throws CantRunException {
    return getPackage(data).getQualifiedName();
  }

  @Override
  protected JavaParameters createJavaParameters() throws ExecutionException {
    final JavaParameters javaParameters = super.createJavaParameters();
    final JUnitConfiguration.Data data = getConfiguration().getPersistentData();
    final Project project = getConfiguration().getProject();
    final SourceScope sourceScope = data.getScope().getSourceScope(getConfiguration());
    if (sourceScope == null || !JUnitStarter.JUNIT5_PARAMETER.equals(getRunner())) { //check for junit 5
      JUnitUtil.checkTestCase(sourceScope, project);
    }
    createTempFiles(javaParameters);

    createServerSocket(javaParameters);
    return javaParameters;
  }

  @Override
  protected boolean configureByModule(Module module) {
    return super.configureByModule(module) && getConfiguration().getPersistentData().getScope() != TestSearchScope.WHOLE_PROJECT;
  }

  protected TestClassFilter getClassFilter(final JUnitConfiguration.Data data) throws CantRunException {
    Module module = getConfiguration().getConfigurationModule().getModule();
    if (getConfiguration().getPersistentData().getScope() == TestSearchScope.WHOLE_PROJECT){
      module = null;
    }
    final TestClassFilter classFilter = TestClassFilter.create(getSourceScope(), module);
    return classFilter.intersectionWith(filterScope(data));
  }

  protected GlobalSearchScope filterScope(final JUnitConfiguration.Data data) throws CantRunException {
    final Ref<CantRunException> ref = new Ref<>();
    final GlobalSearchScope aPackage = ReadAction.compute(() -> {
      try {
        return PackageScope.packageScope(getPackage(data), true);
      }
      catch (CantRunException e) {
        ref.set(e);
        return null;
      }
    });
    final CantRunException exception = ref.get();
    if (exception != null) throw exception;
    return aPackage;
  }

  protected PsiPackage getPackage(JUnitConfiguration.Data data) throws CantRunException {
    final Project project = getConfiguration().getProject();
    final String packageName = data.getPackageName();
    final PsiManager psiManager = PsiManager.getInstance(project);
    final PsiPackage aPackage = JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(packageName);
    if (aPackage == null) throw CantRunException.packageNotFound(packageName);
    return aPackage;
  }

  @Override
  public String suggestActionName() {
    final JUnitConfiguration.Data data = getConfiguration().getPersistentData();
    if (data.getPackageName().trim().length() > 0) {
      return ExecutionBundle.message("test.in.scope.presentable.text", data.getPackageName());
    }
    return ExecutionBundle.message("all.tests.scope.presentable.text");
  }

  @Override
  public RefactoringElementListener getListener(final PsiElement element, final JUnitConfiguration configuration) {
    if (!(element instanceof PsiPackage)) return null;
    return RefactoringListeners.getListener((PsiPackage)element, configuration.myPackage);
  }

  @Override
  public boolean isConfiguredByElement(final JUnitConfiguration configuration,
                                       PsiClass testClass,
                                       PsiMethod testMethod,
                                       PsiPackage testPackage,
                                       PsiDirectory testDir) {
    return testPackage != null
           && Comparing.equal(testPackage.getQualifiedName(), configuration.getPersistentData().getPackageName());
  }

  @Override
  public void checkConfiguration() throws RuntimeConfigurationException {
    super.checkConfiguration();
    final String packageName = getConfiguration().getPersistentData().getPackageName();
    final PsiPackage aPackage =
      JavaPsiFacade.getInstance(getConfiguration().getProject()).findPackage(packageName);
    if (aPackage == null) {
      throw new RuntimeConfigurationWarning(ExecutionBundle.message("package.does.not.exist.error.message", packageName));
    }
    if (getSourceScope() == null) {
      getConfiguration().getConfigurationModule().checkForWarning();
    }
  }

  @TestOnly
  public File getWorkingDirsFile() {
    return myWorkingDirsFile;
  }

  private static Predicate<Class<?>> createPredicate(ClassLoader classLoader) {

    Class<?> testCaseClass = loadClass(classLoader,"junit.framework.TestCase");

    @SuppressWarnings("unchecked")
    Class<? extends Annotation> runWithAnnotationClass = (Class<? extends Annotation>)loadClass(classLoader, "org.junit.runner.RunWith");

    @SuppressWarnings("unchecked")
    Class<? extends Annotation> testAnnotationClass = (Class<? extends Annotation>)loadClass(classLoader, "org.junit.Test");

    return aClass -> {
      //annotation
      if (runWithAnnotationClass != null && aClass.isAnnotationPresent(runWithAnnotationClass)) {
        return true;
      }
      //junit 3
      if (testCaseClass != null && testCaseClass.isAssignableFrom(aClass)) {
        return Arrays.stream(aClass.getConstructors()).anyMatch(constructor -> {
          Class<?>[] parameterTypes = constructor.getParameterTypes();
          return parameterTypes.length == 0 ||
                 parameterTypes.length == 1 && CommonClassNames.JAVA_LANG_STRING.equals(parameterTypes[0].getName());
        });
      }
      else {
        //junit 4 & suite
        for (Method method : aClass.getMethods()) {
          if (Modifier.isStatic(method.getModifiers()) && "suite".equals(method.getName())) {
            return true;
          }
          if (testAnnotationClass != null && method.isAnnotationPresent(testAnnotationClass)) {
            return hasSingleConstructor(aClass);
          }
        }
      }
      return false;
    };
  }

  private static Class<?> loadClass(ClassLoader classLoader, String className) {
    try {
      return Class.forName(className, true, classLoader);
    }
    catch (ClassNotFoundException e) {
      return null;
    }
  }

  private static boolean hasSingleConstructor(Class<?> aClass) {
    Constructor<?>[] constructors = aClass.getConstructors();
    return constructors.length == 1 && constructors[0].getParameterTypes().length == 0;
  }
}


text:
package com.microsoft.azure.management.compute.implementation;

import com.microsoft.azure.AzureEnvironment;
import com.microsoft.azure.AzureResponseBuilder;
import com.microsoft.azure.credentials.AzureTokenCredentials;
import com.microsoft.azure.management.apigeneration.Beta;
import com.microsoft.azure.management.apigeneration.Beta.SinceVersion;
import com.microsoft.azure.management.compute.AvailabilitySets;
import com.microsoft.azure.management.compute.ComputeUsages;
import com.microsoft.azure.management.compute.Disks;
import com.microsoft.azure.management.compute.Snapshots;
import com.microsoft.azure.management.compute.VirtualMachineCustomImages;
import com.microsoft.azure.management.compute.VirtualMachineExtensionImages;
import com.microsoft.azure.management.compute.VirtualMachineImages;
import com.microsoft.azure.management.compute.VirtualMachineScaleSets;
import com.microsoft.azure.management.compute.VirtualMachines;
import com.microsoft.azure.management.compute.ContainerServices;
import com.microsoft.azure.management.graphrbac.implementation.GraphRbacManager;
import com.microsoft.azure.management.network.implementation.NetworkManager;
import com.microsoft.azure.management.resources.fluentcore.arm.AzureConfigurable;
import com.microsoft.azure.management.resources.fluentcore.arm.implementation.AzureConfigurableImpl;
import com.microsoft.azure.management.resources.fluentcore.arm.implementation.Manager;
import com.microsoft.azure.management.resources.fluentcore.utils.ProviderRegistrationInterceptor;
import com.microsoft.azure.management.resources.fluentcore.utils.ResourceManagerThrottlingInterceptor;
import com.microsoft.azure.management.storage.implementation.StorageManager;
import com.microsoft.azure.serializer.AzureJacksonAdapter;
import com.microsoft.rest.RestClient;

/**
 * Entry point to Azure compute resource management.
 */
public final class ComputeManager extends Manager<ComputeManager, ComputeManagementClientImpl> {
    // The service managers
    private StorageManager storageManager;
    private NetworkManager networkManager;
    private GraphRbacManager rbacManager;

    // The collections
    private AvailabilitySets availabilitySets;
    private VirtualMachines virtualMachines;
    private VirtualMachineImages virtualMachineImages;
    private VirtualMachineExtensionImages virtualMachineExtensionImages;
    private VirtualMachineScaleSets virtualMachineScaleSets;
    private ComputeUsages computeUsages;
    private VirtualMachineCustomImages virtualMachineCustomImages;
    private Disks disks;
    private Snapshots snapshots;
    private ContainerServices containerServices;

    /**
     * Get a Configurable instance that can be used to create ComputeManager with optional configuration.
     *
     * @return Configurable
     */
    public static Configurable configure() {
        return new ComputeManager.ConfigurableImpl();
    }

    /**
     * Creates an instance of ComputeManager that exposes Compute resource management API entry points.
     *
     * @param credentials the credentials to use
     * @param subscriptionId the subscription
     * @return the ComputeManager
     */
    public static ComputeManager authenticate(AzureTokenCredentials credentials, String subscriptionId) {
        return new ComputeManager(new RestClient.Builder()
                .withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER)
                .withCredentials(credentials)
                .withSerializerAdapter(new AzureJacksonAdapter())
                .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
                .withInterceptor(new ProviderRegistrationInterceptor(credentials))
                .withInterceptor(new ResourceManagerThrottlingInterceptor())
                .build(), subscriptionId);
    }

    /**
     * Creates an instance of ComputeManager that exposes Compute resource management API entry points.
     *
     * @param restClient the RestClient to be used for API calls.
     * @param subscriptionId the subscription
     * @return the ComputeManager
     */
    public static ComputeManager authenticate(RestClient restClient, String subscriptionId) {
        return new ComputeManager(restClient, subscriptionId);
    }

    /**
     * The interface allowing configurations to be set.
     */
    public interface Configurable extends AzureConfigurable<Configurable> {
        /**
         * Creates an instance of ComputeManager that exposes Compute resource management API entry points.
         *
         * @param credentials the credentials to use
         * @param subscriptionId the subscription
         * @return the ComputeManager
         */
        ComputeManager authenticate(AzureTokenCredentials credentials, String subscriptionId);
    }

    /**
     * The implementation for Configurable interface.
     */
    private static final class ConfigurableImpl extends AzureConfigurableImpl<Configurable> implements  Configurable {
        @Override
        public ComputeManager authenticate(AzureTokenCredentials credentials, String subscriptionId) {
            return ComputeManager.authenticate(buildRestClient(credentials), subscriptionId);
        }
    }

    private ComputeManager(RestClient restClient, String subscriptionId) {
        super(
                restClient,
                subscriptionId,
                new ComputeManagementClientImpl(restClient).withSubscriptionId(subscriptionId));
        storageManager = StorageManager.authenticate(restClient, subscriptionId);
        networkManager = NetworkManager.authenticate(restClient, subscriptionId);
        rbacManager = GraphRbacManager.authenticate(restClient, ((AzureTokenCredentials) (restClient.credentials())).domain());
    }

    /**
     * @return the availability set resource management API entry point
     */
    public AvailabilitySets availabilitySets() {
        if (availabilitySets == null) {
            availabilitySets = new AvailabilitySetsImpl(this);
        }
        return availabilitySets;
    }

    /**
     * @return the availability set resource management API entry point
     */
    @Beta(SinceVersion.V1_1_0)
    public ContainerServices containerServices() {
        if (containerServices == null) {
            containerServices = new ContainerServicesImpl(this);
        }
        return containerServices;
    }

    /**
     * @return the virtual machine resource management API entry point
     */
    public VirtualMachines virtualMachines() {
        if (virtualMachines == null) {
            virtualMachines = new VirtualMachinesImpl(
                    this,
                    storageManager,
                    networkManager,
                    rbacManager);
        }
        return virtualMachines;
    }

    /**
     * @return the virtual machine image resource management API entry point
     */
    public VirtualMachineImages virtualMachineImages() {
        if (virtualMachineImages == null) {
            virtualMachineImages = new VirtualMachineImagesImpl(new VirtualMachinePublishersImpl(super.innerManagementClient.virtualMachineImages(),
                    super.innerManagementClient.virtualMachineExtensionImages()),
                    super.innerManagementClient.virtualMachineImages());
        }
        return virtualMachineImages;
    }

    /**
     * @return the virtual machine extension image resource management API entry point
     */
    public VirtualMachineExtensionImages virtualMachineExtensionImages() {
        if (virtualMachineExtensionImages == null) {
            virtualMachineExtensionImages = new VirtualMachineExtensionImagesImpl(new VirtualMachinePublishersImpl(super.innerManagementClient.virtualMachineImages(),
                    super.innerManagementClient.virtualMachineExtensionImages()));
        }
        return virtualMachineExtensionImages;
    }

    /**
     * @return the virtual machine scale set resource management API entry point
     */
    public VirtualMachineScaleSets virtualMachineScaleSets() {
        if (virtualMachineScaleSets == null) {
            virtualMachineScaleSets = new VirtualMachineScaleSetsImpl(
                    this,
                    storageManager,
                    networkManager,
                    this.rbacManager);
        }
        return virtualMachineScaleSets;
    }

    /**
     * @return the compute resource usage management API entry point
     */
    public ComputeUsages usages() {
        if (computeUsages == null) {
            computeUsages = new ComputeUsagesImpl(super.innerManagementClient);
        }
        return computeUsages;
    }

    /**
     * @return the virtual machine custom image management API entry point
     */
    public VirtualMachineCustomImages virtualMachineCustomImages() {
        if (virtualMachineCustomImages == null) {
            virtualMachineCustomImages = new VirtualMachineCustomImagesImpl(this);
        }
        return virtualMachineCustomImages;
    }

    /**
     * @return the managed disk management API entry point
     */
    public Disks disks() {
        if (disks == null) {
            disks = new DisksImpl(this);
        }
        return disks;
    }

    /**
     * @return the managed snapshot management API entry point
     */
    public Snapshots snapshots() {
        if (snapshots == null) {
            snapshots = new SnapshotsImpl(this);
        }
        return snapshots;
    }
}


text:
TopHN
=====
This document describes how to set up the development and the live
environments of the website [TopHN][WEBSITE].

Note that the TopHN website is developed primarily on a Debian system,
so the steps below are written for Debian system. To develop this
website on any other system, some of the steps below may have to be
modified.

[WEBSITE]: https://tophn.org/

Contents
--------
* [Development Setup](#development-setup)
* [Live Setup](#live-setup)
* [Troubleshooting Tips](#troubleshooting-tips)

Development Setup
-----------------
Perform the following steps to setup the development environment for
the website on local system.

 1. Install necessary tools.

        sudo apt-get update
        sudo apt-get -y install nginx git

 2. Clone this repository.

        mkdir -p ~/git
        cd ~/git
        git clone https://github.com/sunainapai/tophn.git

 3. Configure Nginx for development.

        sudo ln -sf ~/git/tophn/etc/nginx/dev.tophn.org /etc/nginx/sites-enabled/
        sudo ln -sf ~/tophn.org/live /var/www/tophn.org
        sudo systemctl reload nginx

 4. Associate the hostname `tophn` with the loopback interface.

        echo 127.0.2.1 tophn | sudo tee -a /etc/hosts

 5. Install the necessary tools in the virtual environment.

        python3 -m venv ~/.venv/tophn.org/
        . ~/.venv/tophn.org/bin/activate
        pip install jinja2 urllib3
        deactivate

 6. Generate the website.

        cd ~/git/tophn
        sudo ln -sf ~/git/tophn/etc/systemd/tophn.service /etc/systemd/system/
        sudo systemctl start tophn

 7. Visit http://tophn/ with a web browser to see a local copy of the
    website.

Live Setup
----------
Perform the following steps to setup the live environment on an internet
facing server.

 1. Log in as user sunaina and perform steps 1, 2, 3, 5, 6 and 7 from the
    previous section.

 2. Install certbot.

        echo 'deb http://ftp.debian.org/debian jessie-backports main' | sudo tee /etc/apt/sources.list.d/backports.list
        sudo apt-get update
        sudo apt-get install certbot -t jessie-backports

 3. Get TLS certificates.

        sudo certbot certonly --webroot -w /var/www/tophn.org -m sunainapai.in@gmail.com -d tophn.org,www.tophn.org

 4. Configure Nginx for the live website.

        sudo rm /etc/nginx/sites-enabled/dev.tophn.org
        sudo ln -sf ~/git/tophn/etc/nginx/tophn.org /etc/nginx/sites-enabled/tophn.org
        sudo systemctl reload nginx

 5. Visit https://tophn.org/ with a web browser to see the live website.

Troubleshooting Tips
--------------------
### Error When Rendering Unicode Characters

The following error occurred in Debian 8.8 in DigitalOcean droplet.

    2017-10-12 00:29:17 - tophn - INFO - Working ...
    2017-10-12 00:29:17 - tophn - INFO - Current Time: 1507768157: 2017-10-12 00:29:17 GMT
    2017-10-12 00:29:17 - tophn - INFO - Top ID on HN: 15453974
    2017-10-12 00:29:17 - tophn - INFO - Most frequent top ID in the past 24 hours: 15447706
    2017-10-12 00:29:17 - tophn - INFO - Creating /home/sunaina/tophn.org/_stage/ directory ...
    2017-10-12 00:29:17 - tophn - INFO - Copying static directory to /home/sunaina/tophn.org/_stage/ ...
    2017-10-12 00:29:17 - tophn - INFO - Rendering home page ...
    2017-10-12 00:29:17 - tophn - ERROR - Unexpected error occurred
    Traceback (most recent call last):
      File "./tophn.py", line 406, in _main
        _stage_top_hn(config, archive_list)
      File "./tophn.py", line 326, in _stage_top_hn
        _render(config, templates_home, archive_list[-1], home_page)
      File "./tophn.py", line 185, in _render
        f.write(template.render(template_values))
    UnicodeEncodeError: 'ascii' codec can't encode character '\u2019' in position 382: ordinal not in range(128)
    2017-10-12 00:29:17 - tophn - INFO - Sleeping for 60 seconds ...
    2017-10-12 00:30:18 - tophn - INFO - Working ...

Perform the following steps to fix this issue.

 1. Reconfigure locale on Debain 8.8.

        locale-gen en_US.UTF-8
        sudo dpkg-reconfigure locales

    Select en_US.UTF-8 UTF-8 in Configuring Locales - Locales to be
    generated and Default locale for the system environment.

 2. Add the following lines in /etc/enviroment

        LANGUAGE=en_US.UTF-8
        LC_ALL=en_US.UTF-8

 3. Logout and login again and check the locale.

        locale


text:
package service // import "go.opentelemetry.io/collector/service"

import (
	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/service/extensions"
	"go.opentelemetry.io/collector/service/internal/pipelines"
)

var _ component.Host = (*serviceHost)(nil)

type serviceHost struct {
	asyncErrorChannel chan error
	factories         component.Factories
	buildInfo         component.BuildInfo

	pipelines  *pipelines.Pipelines
	extensions *extensions.Extensions
}

// ReportFatalError is used to report to the host that the receiver encountered
// a fatal error (i.e.: an error that the instance can't recover from) after
// its start function has already returned.
func (host *serviceHost) ReportFatalError(err error) {
	host.asyncErrorChannel <- err
}

func (host *serviceHost) GetFactory(kind component.Kind, componentType component.Type) component.Factory {
	switch kind {
	case component.KindReceiver:
		return host.factories.Receivers[componentType]
	case component.KindProcessor:
		return host.factories.Processors[componentType]
	case component.KindExporter:
		return host.factories.Exporters[componentType]
	case component.KindExtension:
		return host.factories.Extensions[componentType]
	}
	return nil
}

func (host *serviceHost) GetExtensions() map[component.ID]component.Component {
	return host.extensions.GetExtensions()
}

func (host *serviceHost) GetExporters() map[component.DataType]map[component.ID]component.Component {
	return host.pipelines.GetExporters()
}


text:
require './test/test-helper.rb'
$:.unshift File.join(File.dirname(__FILE__), "..", "lib")
require 'test/unit'
require 'gems-status'

module GemsStatus
  class GemTest
    attr_accessor :license
  end
  class IsNotGplTest < Test::Unit::TestCase
    def test_check
      gem = GemTest.new
      gem.license = "something"
      assert GemsStatus::IsNotGpl.new(nil).check?(gem)
      gem.license = "GPL"
      assert !GemsStatus::IsNotGpl.new(nil).check?(gem)
      gem.license = "GPLv2"
      assert !GemsStatus::IsNotGpl.new(nil).check?(gem)
      gem.license = "GPLblabla "
      assert !GemsStatus::IsNotGpl.new(nil).check?(gem)
    end

    def test_when_there_is_no_license
      gem = GemTest.new
      assert GemsStatus::IsNotGpl.new(nil).check?(gem)
    end
  end
end


text:
using System.Json;

namespace zsquared
{
    /// <summary>
    /// Calendar entry for site calendar defaults. Deprecated.
    /// </summary>
    public class C_SiteCalendarEntryX
    {
        public bool SiteIsOpen;

        public C_WorkShift[] WorkShifts;

        //public C_HMS OpenTime;
        //public C_HMS CloseTime;
        //public int NumEFilers;
        ///// <summary>
        ///// This is used to remember how many seats are requied and may have been overridded in a calendar; not saved
        ///// in system DB; is preserved across UI screens however
        ///// </summary>
        //public int OverrideNumEFilers;

        //public static readonly string N_OpenTime = "opentime";
        //public static readonly string N_CloseTime = "closetime";
        //public static readonly string N_NumEFilers = "numefilers";
        //public static readonly string N_OverrideNumEFilers = "overridenumefilers";

        public C_SiteCalendarEntryX()
        {
            WorkShifts = new C_WorkShift[3];
            for (int ix = 0; ix != 3; ix++)
                WorkShifts[ix] = new C_WorkShift();
        }

        public C_SiteCalendarEntryX(JsonValue jv)
        {
			//if (jv.ContainsKey(N_OpenTime))
   //             OpenTime = Tools.JsonProcessTime(jv[N_OpenTime], OpenTime);

			//if (jv.ContainsKey(N_CloseTime))
			//	CloseTime = Tools.JsonProcessTime(jv[N_CloseTime], CloseTime);

			//if (jv.ContainsKey(N_NumEFilers))
			//	NumEFilers = Tools.JsonProcessInt(jv[N_NumEFilers], NumEFilers);

			//if (jv.ContainsKey(N_OverrideNumEFilers))
				//OverrideNumEFilers = Tools.JsonProcessInt(jv[N_OverrideNumEFilers], OverrideNumEFilers);
		}
	}
}


text:
package com.uchoice.ucenter.ui;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

/**
 * Created by Administrator on 2017/5/24.
 */
@SpringBootApplication
public class UchoiceUcenterUiApplication {

    public static void main(String[] args){
        new SpringApplicationBuilder(UchoiceUcenterUiApplication.class).web(true).run(args);
    }
}


text:
const fs = require('fs');
const data = require('../data/names.json');
const config = require('../config/config.json');
var pageCount = 0;

data.forEach(function (e) {
    const page = require('webpage').create();

    page.open('http://127.0.0.1:' + config.port + '/pages/' + e + '.html', function(status) {
        setTimeout(function() {
            if(status === "success") {
                page.render('achievements/' + e + '.png');
                pageCount++;

                if (pageCount === data.length - 1) {
                    phantom.exit();
                }
            }
        }, 2000);
    });
    page.onResourceError = function(resourceError) {
        console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
        console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
    };
});


text:
from __future__ import unicode_literals

import datetime

from django.conf import settings
from django.db import transaction, DEFAULT_DB_ALIAS, models
from django.db.utils import ConnectionHandler
from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature

from .models import (Book, Award, AwardNote, Person, Child, Toy, PlayedWith,
    PlayedWithNote, Email, Researcher, Food, Eaten, Policy, Version, Location,
    Item, Image, File, Photo, FooFile, FooImage, FooPhoto, FooFileProxy, Login,
    OrgUnit, OrderedPerson, House)

# Can't run this test under SQLite, because you can't
# get two connections to an in-memory database.
class DeleteLockingTest(TransactionTestCase):

    available_apps = ['delete_regress']

    def setUp(self):
        # Create a second connection to the default database
        new_connections = ConnectionHandler(settings.DATABASES)
        self.conn2 = new_connections[DEFAULT_DB_ALIAS]
        # Put both DB connections into managed transaction mode
        transaction.enter_transaction_management()
        self.conn2.enter_transaction_management()

    def tearDown(self):
        # Close down the second connection.
        transaction.leave_transaction_management()
        self.conn2.abort()
        self.conn2.close()

    @skipUnlessDBFeature('test_db_allows_multiple_connections')
    def test_concurrent_delete(self):
        "Deletes on concurrent transactions don't collide and lock the database. Regression for #9479"

        # Create some dummy data
        b1 = Book(id=1, pagecount=100)
        b2 = Book(id=2, pagecount=200)
        b3 = Book(id=3, pagecount=300)
        b1.save()
        b2.save()
        b3.save()

        transaction.commit()

        self.assertEqual(3, Book.objects.count())

        # Delete something using connection 2.
        cursor2 = self.conn2.cursor()
        cursor2.execute('DELETE from delete_regress_book WHERE id=1')
        self.conn2._commit()

        # Now perform a queryset delete that covers the object
        # deleted in connection 2. This causes an infinite loop
        # under MySQL InnoDB unless we keep track of already
        # deleted objects.
        Book.objects.filter(pagecount__lt=250).delete()
        transaction.commit()
        self.assertEqual(1, Book.objects.count())
        transaction.commit()

class DeleteCascadeTests(TestCase):
    def test_generic_relation_cascade(self):
        """
        Django cascades deletes through generic-related objects to their
        reverse relations.

        """
        person = Person.objects.create(name='Nelson Mandela')
        award = Award.objects.create(name='Nobel', content_object=person)
        note = AwardNote.objects.create(note='a peace prize',
                                        award=award)
        self.assertEqual(AwardNote.objects.count(), 1)
        person.delete()
        self.assertEqual(Award.objects.count(), 0)
        # first two asserts are just sanity checks, this is the kicker:
        self.assertEqual(AwardNote.objects.count(), 0)

    def test_fk_to_m2m_through(self):
        """
        If an M2M relationship has an explicitly-specified through model, and
        some other model has an FK to that through model, deletion is cascaded
        from one of the participants in the M2M, to the through model, to its
        related model.

        """
        juan = Child.objects.create(name='Juan')
        paints = Toy.objects.create(name='Paints')
        played = PlayedWith.objects.create(child=juan, toy=paints,
                                           date=datetime.date.today())
        note = PlayedWithNote.objects.create(played=played,
                                             note='the next Jackson Pollock')
        self.assertEqual(PlayedWithNote.objects.count(), 1)
        paints.delete()
        self.assertEqual(PlayedWith.objects.count(), 0)
        # first two asserts just sanity checks, this is the kicker:
        self.assertEqual(PlayedWithNote.objects.count(), 0)

    def test_15776(self):
        policy = Policy.objects.create(pk=1, policy_number="1234")
        version = Version.objects.create(policy=policy)
        location = Location.objects.create(version=version)
        item = Item.objects.create(version=version, location=location)
        policy.delete()

class DeleteCascadeTransactionTests(TransactionTestCase):

    available_apps = ['delete_regress']

    def test_inheritance(self):
        """
        Auto-created many-to-many through tables referencing a parent model are
        correctly found by the delete cascade when a child of that parent is
        deleted.

        Refs #14896.
        """
        r = Researcher.objects.create()
        email = Email.objects.create(
            label="office-email", email_address="carl@science.edu"
        )
        r.contacts.add(email)

        email.delete()

    def test_to_field(self):
        """
        Cascade deletion works with ForeignKey.to_field set to non-PK.

        """
        apple = Food.objects.create(name="apple")
        eaten = Eaten.objects.create(food=apple, meal="lunch")

        apple.delete()
        self.assertFalse(Food.objects.exists())
        self.assertFalse(Eaten.objects.exists())

class LargeDeleteTests(TestCase):
    def test_large_deletes(self):
        "Regression for #13309 -- if the number of objects > chunk size, deletion still occurs"
        for x in range(300):
            track = Book.objects.create(pagecount=x+100)
        # attach a signal to make sure we will not fast-delete
        def noop(*args, **kwargs):
            pass
        models.signals.post_delete.connect(noop, sender=Book)
        Book.objects.all().delete()
        models.signals.post_delete.disconnect(noop, sender=Book)
        self.assertEqual(Book.objects.count(), 0)

class ProxyDeleteTest(TestCase):
    """
    Tests on_delete behavior for proxy models.

    See #16128.

    """
    def create_image(self):
        """Return an Image referenced by both a FooImage and a FooFile."""
        # Create an Image
        test_image = Image()
        test_image.save()
        foo_image = FooImage(my_image=test_image)
        foo_image.save()

        # Get the Image instance as a File
        test_file = File.objects.get(pk=test_image.pk)
        foo_file = FooFile(my_file=test_file)
        foo_file.save()

        return test_image

    def test_delete_proxy(self):
        """
        Deleting the *proxy* instance bubbles through to its non-proxy and
        *all* referring objects are deleted.

        """
        self.create_image()

        Image.objects.all().delete()

        # An Image deletion == File deletion
        self.assertEqual(len(Image.objects.all()), 0)
        self.assertEqual(len(File.objects.all()), 0)

        # The Image deletion cascaded and *all* references to it are deleted.
        self.assertEqual(len(FooImage.objects.all()), 0)
        self.assertEqual(len(FooFile.objects.all()), 0)

    def test_delete_proxy_of_proxy(self):
        """
        Deleting a proxy-of-proxy instance should bubble through to its proxy
        and non-proxy parents, deleting *all* referring objects.

        """
        test_image = self.create_image()

        # Get the Image as a Photo
        test_photo = Photo.objects.get(pk=test_image.pk)
        foo_photo = FooPhoto(my_photo=test_photo)
        foo_photo.save()

        Photo.objects.all().delete()

        # A Photo deletion == Image deletion == File deletion
        self.assertEqual(len(Photo.objects.all()), 0)
        self.assertEqual(len(Image.objects.all()), 0)
        self.assertEqual(len(File.objects.all()), 0)

        # The Photo deletion should have cascaded and deleted *all*
        # references to it.
        self.assertEqual(len(FooPhoto.objects.all()), 0)
        self.assertEqual(len(FooFile.objects.all()), 0)
        self.assertEqual(len(FooImage.objects.all()), 0)

    def test_delete_concrete_parent(self):
        """
        Deleting an instance of a concrete model should also delete objects
        referencing its proxy subclass.

        """
        self.create_image()

        File.objects.all().delete()

        # A File deletion == Image deletion
        self.assertEqual(len(File.objects.all()), 0)
        self.assertEqual(len(Image.objects.all()), 0)

        # The File deletion should have cascaded and deleted *all* references
        # to it.
        self.assertEqual(len(FooFile.objects.all()), 0)
        self.assertEqual(len(FooImage.objects.all()), 0)

    def test_delete_proxy_pair(self):
        """
        If a pair of proxy models are linked by an FK from one concrete parent
        to the other, deleting one proxy model cascade-deletes the other, and
        the deletion happens in the right order (not triggering an
        IntegrityError on databases unable to defer integrity checks).

        Refs #17918.

        """
        # Create an Image (proxy of File) and FooFileProxy (proxy of FooFile,
        # which has an FK to File)
        image = Image.objects.create()
        as_file = File.objects.get(pk=image.pk)
        FooFileProxy.objects.create(my_file=as_file)

        Image.objects.all().delete()

        self.assertEqual(len(FooFileProxy.objects.all()), 0)

    def test_19187_values(self):
        with self.assertRaises(TypeError):
            Image.objects.values().delete()
        with self.assertRaises(TypeError):
            Image.objects.values_list().delete()

class Ticket19102Tests(TestCase):
    """
    Test different queries which alter the SELECT clause of the query. We
    also must be using a subquery for the deletion (that is, the original
    query has a join in it). The deletion should be done as "fast-path"
    deletion (that is, just one query for the .delete() call).

    Note that .values() is not tested here on purpose. .values().delete()
    doesn't work for non fast-path deletes at all.
    """
    def setUp(self):
        self.o1 = OrgUnit.objects.create(name='o1')
        self.o2 = OrgUnit.objects.create(name='o2')
        self.l1 = Login.objects.create(description='l1', orgunit=self.o1)
        self.l2 = Login.objects.create(description='l2', orgunit=self.o2)

    @skipUnlessDBFeature("update_can_self_select")
    def test_ticket_19102_annotate(self):
        with self.assertNumQueries(1):
            Login.objects.order_by('description').filter(
                orgunit__name__isnull=False
            ).annotate(
                n=models.Count('description')
            ).filter(
                n=1, pk=self.l1.pk
            ).delete()
        self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
        self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())

    @skipUnlessDBFeature("update_can_self_select")
    def test_ticket_19102_extra(self):
        with self.assertNumQueries(1):
            Login.objects.order_by('description').filter(
                orgunit__name__isnull=False
            ).extra(
                select={'extraf':'1'}
            ).filter(
                pk=self.l1.pk
            ).delete()
        self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
        self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())

    @skipUnlessDBFeature("update_can_self_select")
    @skipUnlessDBFeature('can_distinct_on_fields')
    def test_ticket_19102_distinct_on(self):
        # Both Login objs should have same description so that only the one
        # having smaller PK will be deleted.
        Login.objects.update(description='description')
        with self.assertNumQueries(1):
            Login.objects.distinct('description').order_by('pk').filter(
                orgunit__name__isnull=False
            ).delete()
        # Assumed that l1 which is created first has smaller PK.
        self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
        self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())

    @skipUnlessDBFeature("update_can_self_select")
    def test_ticket_19102_select_related(self):
        with self.assertNumQueries(1):
            Login.objects.filter(
                pk=self.l1.pk
            ).filter(
                orgunit__name__isnull=False
            ).order_by(
                'description'
            ).select_related('orgunit').delete()
        self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
        self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())

    @skipUnlessDBFeature("update_can_self_select")
    def test_ticket_19102_defer(self):
        with self.assertNumQueries(1):
            Login.objects.filter(
                pk=self.l1.pk
            ).filter(
                orgunit__name__isnull=False
            ).order_by(
                'description'
            ).only('id').delete()
        self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
        self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())

class OrderedDeleteTests(TestCase):
    def test_meta_ordered_delete(self):
        # When a subquery is performed by deletion code, the subquery must be
        # cleared of all ordering. There was a but that caused _meta ordering
        # to be used. Refs #19720.
        h = House.objects.create(address='Foo')
        OrderedPerson.objects.create(name='Jack', lives_in=h)
        OrderedPerson.objects.create(name='Bob', lives_in=h)
        OrderedPerson.objects.filter(lives_in__address='Foo').delete()
        self.assertEqual(OrderedPerson.objects.count(), 0)


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using NUnit.Framework;
using TestConsole.OutputFormatting;
using TestConsole.OutputFormatting.Internal;
using TestConsole.Tests.OutputFormatting.UnitTestutilities;
using TestConsole.Tests.TestingUtilities;
using TestConsole.Utilities;
using TestConsoleLib.Testing;

namespace TestConsole.Tests.OutputFormatting
{
    [TestFixture]
    public class TestTabularReport
    {
        [SetUp]
        public void SetUp()
        {
            SetUpTests.OverrideCulture();
        }

        [Test]
        public void TabularReportWithoutWrappingIsFormatted()
        {
            SetUpTests.OverrideCulture();
            var data = Enumerable.Range(0, 10)
                .Select(i => new
                {
                    String = string.Format("String value {0}", i),
                    Int = i,
                    Double = 3.0 / (i + 1.0),
                    DateTime = DateTime.Parse(string.Format("2014-{0}-17", i + 1))
                })
                .ToList();

            var report = Run(data, options: ReportFormattingOptions.StretchColumns);
            Approvals.Verify(report);
        }

        [Test]
        public void TabularReportWithWrappingIsFormatted()
        {
            var data = Enumerable.Range(0, 10)
                .Select(i => new
                {
                    String = string.Format("Long string value {0}. This value should be nice and long so that it doesn't fit a line. Then the algorithm has to calculate how many lines it will take to display the value within the allowable space. Better add a bit of variation to each row too: {1}", i, string.Join(" ", Enumerable.Repeat("variation ", i))),
                    Int = i,
                    Double = 3.0 / (i + 1.0),
                    DateTime = DateTime.Parse(string.Format("2014-{0}-17", i + 1))
                })
                .ToList();

            var report = Run(data);
            Approvals.Verify(report);
        }

        [Test]
        public void ColumnHeadingsCanBeOmitted()
        {
            var data = Enumerable.Range(0, 10)
                .Select(i => new
                {
                    String = string.Format("Long string value {0}. This value should be nice and long so that it doesn't fit a line. Then the algorithm has to calculate how many lines it will take to display the value within the allowable space. Better add a bit of variation to each row too: {1}", i, string.Join(" ", Enumerable.Repeat("variation ", i))),
                    Int = i,
                    Double = 3.0 / (i + 1.0),
                    DateTime = DateTime.Parse(string.Format("2014-{0}-17", i + 1))
                })
                .ToList();

            var report = Run(data, options: ReportFormattingOptions.Default | ReportFormattingOptions.OmitHeadings);
            Approvals.Verify(report);
        }

        [Test]
        public void TabularReportWithTwoWrappingTextColumnsIsFormatted()
        {
            var data = Enumerable.Range(0, 10)
                .Select(i => new
                {
                    String = string.Format("First long string value {0}. {1}", i, string.Join(" ", Enumerable.Repeat("variation ", i))),
                    SecondString = string.Format("Second long string value {0}. {1}", i, string.Join(" ", Enumerable.Repeat("variation ", i))),
                    Int = i,
                    Double = 3.0 / (i + 1.0),
                    DateTime = DateTime.Parse(string.Format("2014-{0}-17", i + 1))
                })
                .ToList();

            var report = Run(data);
            Approvals.Verify(report);
        }

        [Test]
        public void TabularReportCanFormatFromCachedData()
        {
            var data = Enumerable.Range(0, 10)
                .Select(i => new
                {
                    String = string.Format("First long string value {0}. {1}", i, string.Join(" ", Enumerable.Repeat("variation ", i))),
                    SecondString = string.Format("Second long string value {0}. {1}", i, string.Join(" ", Enumerable.Repeat("variation ", i))),
                    Int = i,
                    Double = 3.0 / (i + 1.0),
                    DateTime = DateTime.Parse(string.Format("2014-{0}-17", i + 1))
                })
                .ToList();

            var dataCache = CachedRowsFactory.Make(data);

            var report = CachedReport(dataCache);
            Approvals.Verify(report);
        }

        [Test]
        public void HeadingsCanBeOmittedFromCachedData()
        {
            var data = Enumerable.Range(0, 10)
                .Select(i => new
                {
                    String = string.Format("First long string value {0}. {1}", i, string.Join(" ", Enumerable.Repeat("variation ", i))),
                    SecondString = string.Format("Second long string value {0}. {1}", i, string.Join(" ", Enumerable.Repeat("variation ", i))),
                    Int = i,
                    Double = 3.0 / (i + 1.0),
                    DateTime = DateTime.Parse(string.Format("2014-{0}-17", i + 1))
                })
                .ToList();

            var dataCache = CachedRowsFactory.Make(data);

            var report = CachedReport(dataCache, options: ReportFormattingOptions.Default | ReportFormattingOptions.OmitHeadings);
            Approvals.Verify(report);
        }

        [Test]
        public void TabularReportCanFormatRenderableData()
        {
            var data = Enumerable.Range(3, 7)
                .Select(i => new
                {
                    String = MakeRenderable(i),
                    SecondString = string.Format("Second long string value {0}. {1}", i, string.Join(" ", Enumerable.Repeat("variation ", i))),
                    Int = i,
                    Double = 3.0 / (i + 1.0),
                    DateTime = DateTime.Parse(string.Format("2014-{0}-17", i + 1))
                })
                .ToList();

            var dataCache = CachedRowsFactory.Make(data);

            var report = CachedReport(dataCache, options: ReportFormattingOptions.StretchColumns);
            Approvals.Verify(report);
        }

        [Test]
        public void IdealMinimumWidthIsAppliedToStringColumns()
        {
            var data = Enumerable.Range(0, 1)
                .Select(i => new
                {
                    S = "X X X Y",
                    S2 = "X X X YY",
                    S3 = "XXX XXX XXX YYY",
                    S4 = "XXX XXX XXX XXX XXX YYYY",
                    S5 = "XXX XXX XXX YYYYY",
                })
                .ToList();

            var report = Run(data, width: 19);
            Approvals.Verify(report);
        }

        [Test]
        public void LastColumnIsStackedWhenColumnsDoNotFit()
        {
            var data = Enumerable.Range(0, 1)
                .Select(i => new
                {
                    S = "X X X Y",
                    S2 = "X X X YY",
                    S3 = "XXX XXX XXX YYY",
                    S4 = "XXX XXX XXX XXX XXX YYYY",
                    S5 = "XXX XXX XXX YYYYY",
                })
                .ToList();

            var report = Run(data, width: 17);
            Approvals.Verify(report);
        }

        [Test]
        public void BufferWidthIsOveriddenWhenOptionsAllow()
        {
            var data = Enumerable.Range(0, 1)
                .Select(i => new
                {
                    S = "X X X Y",
                    S2 = "X X X YY",
                    S3 = "XXX XXX XXX YYY",
                    S4 = "XXX XXX XXX XXX XXX YYYY",
                    S5 = "XXX XXX XXX YYYYY",
                })
                .ToList();

            var report = Run(data, width: 17, options: ReportFormattingOptions.UnlimitedBuffer);
            Approvals.Verify(report);
        }

        [Test]
        public void AllColumnsCanBeStacked()
        {
            var data = Enumerable.Range(0, 1)
                .Select(i => new
                {
                    Value = 1.5,
                    LongText = "Long text that could be wrapped quite easily if required.",
                    Short = "Short text",
                    Date = DateTime.Parse("2014-05-07 19:59:20"),
                })
                .ToList();

            var report = Run(data, width: 20);
            Approvals.Verify(report);
        }

        [Test]
        public void WordWrappingIsLimitedWhenBufferUnlimited()
        {
            var data = Enumerable.Range(0, 1)
                .Select(i => new
                {
                    S = "X X X Y",
                    S2 = "X X X YY",
                    S3 = "XXX XXX XXX YYY",
                    S4 = "XXX XXX XXX XXX XXX YYYY XXX XXX XXX XXX XXX Linebreak->\r\nYYYY XXX XXX XXX XXX XXX YYYY XXX XXX XXX XXX XXX YYYY XXX XXX XXX XXX XXX YYYY",
                    S5 = "XXX XXX XXX YYYY",
                })
                .ToList();

            var report = Run(data, width: 17, options: ReportFormattingOptions.UnlimitedBuffer);
            Approvals.Verify(report);
        }

        [Test]
        public void FormattingSucceedsWhenAvailableSpaceIsTooSmall()
        {
            var data = Enumerable.Range(0, 1)
                .Select(i => new
                {
                    Value = 1.5,
                    LongText = "Long text that could be wrapped quite easily if required.",
                    Short = "Short text",
                    Date = DateTime.Parse("2014-05-07 19:59:20"),
                })
                .ToList();

            var report = Run(data, width: 4);
            Approvals.Verify(report);
        }

        [Test]
        public void SizesAreOnlyCalculatedFromSpecifiedRows()
        {
            var data = Enumerable.Range(0, 20)
                .Select(i => new
                {
                    Value = 1.5,
                    X = i
                })
                .ToList();

            var report = Run(data, width: 9, numRowsToUseForSizing: 9);
            Approvals.Verify(report);
        }

        [Test]
        public void ReportDegradesGracefully()
        {
            var data = Enumerable.Range(0, 1)
                .Select(i => new
                {
                    Value = 1.5,
                    LongText = "Long text that could be wrapped quite easily if required.",
                    Short = "Short text",
                    Date = DateTime.Parse("2014-05-07 19:59:20"),
                })
                .ToList();

            var sb = new StringBuilder();

            for (var width = 80; width > 0; width -= 5)
            {
                sb.AppendLine(string.Format("Test width {0}:", width));
                sb.Append(Run(data, width: width));
                sb.AppendLine();
            }
            Approvals.Verify(sb.ToString());
        }

        [Test]
        public void ReportWithFixedWidthColumnDegradesGracefully()
        {
            var data = Enumerable.Range(0, 1)
                .Select(i => new
                {
                    Value = 1.5,
                    LongText = "Long text that could be wrapped quite easily if required.",
                    Short = "Short text",
                    Date = DateTime.Parse("2014-05-07 19:59:20"),
                })
                .ToList();

            var cols = FormatAnalyser.Analyse(data.First().GetType(), null, true);
            cols[0].Format.FixedWidth = 10;
            cols[1].Format.FixedWidth = 10;

            var sb = new StringBuilder();

            for (var width = 80; width > 0; width -= 5)
            {
                sb.AppendLine(string.Format("Test width {0}:", width));
                sb.Append(Run(data, width, columnFormats: cols.Select(c => c.Format)));
                sb.AppendLine();
            }
            sb.ToString().Verify();
        }

        [Test]
        public void ReportWithProportionalWidthColumnsDegradesGracefully()
        {
            var data = Enumerable.Range(0, 1)
                .Select(i => new
                {
                    Value = 1.5,
                    LongText = "Long text that could be wrapped quite easily if required.",
                    Short = "Short text",
                    Date = DateTime.Parse("2014-05-07 19:59:20"),
                })
                .ToList();

            var cols = FormatAnalyser.Analyse(data.First().GetType(), null, true);
            cols[0].Format.ProportionalWidth = 10;
            cols[1].Format.ProportionalWidth = 10;
            cols[0].Format.MinWidth = 4;
            cols[0].Format.MaxWidth = 15;
            cols[1].Format.MinWidth = 4;

            var sb = new StringBuilder();

            for (var width = 80; width > 0; width -= 5)
            {
                sb.AppendLine(string.Format("Test width {0}:", width));
                sb.Append(Run(data, width, columnFormats: cols.Select(c => c.Format)));
                sb.AppendLine();
            }
            Approvals.Verify(sb.ToString());
        }

        [Test]
        public void ColumnsCanBeDividedWithCustomText()
        {
            var data = Enumerable.Range(0, 1)
                .Select(i => new
                {
                    Value = 1.5,
                    LongText = "Long text that could be wrapped quite easily if required.",
                    Short = "Short text",
                    Date = DateTime.Parse("2014-05-07 19:59:20"),
                })
                .ToList();

            var sb = new StringBuilder();

            sb.Append(Run(data, width: 50, columnDivider: "XXX"));
            sb.AppendLine();

            Approvals.Verify(sb.ToString());
        }

        [Test]
        public void ColumnWidthsDoNotTakeHeadingIntoAccountIfHeadingsSkipped()
        {
            var data = Enumerable.Range(0, 1)
                .Select(i => new
                {
                    Value = "X",
                    Text = "Text.",
                })
                .ToList();

            var sb = new StringBuilder();

            sb.AppendLine("With headings:");
            sb.AppendLine();
            sb.Append(Run(data, width: 50));
            sb.AppendLine();
            sb.AppendLine();
            sb.AppendLine("Without headings:");
            sb.AppendLine();

            sb.Append(Run(data, width: 50, options: ReportFormattingOptions.OmitHeadings));
            sb.AppendLine();

            Approvals.Verify(sb.ToString());
        }

        [Test]
        public void AChildReportsIsRendered()
        {
            var data = Enumerable.Range(0, 1)
                .AsReport(p => p.AddColumn(r => "X", cc => cc.Heading("Value"))
                                .AddColumn(r => "Text", cc => cc.Heading("Text."))
                                .AddChild(i => Enumerable.Range(0, 2), cr => cr.AddColumn(i => i, cc => cc.Heading("Child Int"))));

            var sb = new StringBuilder();

            sb.Append(Run(data, 50));

            Approvals.Verify(sb.ToString());
        }

        [Test]
        public void ChildReportsCanHaveChildren()
        {
            var data = Enumerable.Range(0, 1)
                .AsReport(p => p.AddColumn(r => "X", cc => cc.Heading("Value"))
                    .AddColumn(r => "Text", cc => cc.Heading("Text."))
                    .AddChild(i => Enumerable.Range(0, 2),
                        cr => cr.AddColumn(i => i, cc => cc.Heading("Child Int"))
                                .AddChild(j => Enumerable.Range(0, 2),
                                    ccr => ccr.AddColumn(i => i, cc => cc.Heading("Child of Child Int")))));

            var sb = new StringBuilder();

            sb.Append(Run(data, 50));

            Approvals.Verify(sb.ToString());
        }

        [Test]
        public void APrimitiveProducesAOneColumnReport()
        {
            var data = Enumerable.Range(0, 15);

            var sb = new StringBuilder();

            sb.Append(Run(data, width: 50, numRowsToUseForSizing: 10));

            Approvals.Verify(sb.ToString());
        }

        [Test]
        public void APrimitiveOneColumnReportCanHaveAColumnFormat()
        {
            var data = Enumerable.Range(0, 15)
                .AsReport(p => p.AddColumn(r => r, cc => cc.Heading("Int Value").LeftAlign()));

            var sb = new StringBuilder();

            sb.Append(Run(data, 50, 10));

            Approvals.Verify(sb.ToString());
        }

        [Test]
        public void EmptyListCanBeFormatted()
        {
            var data = new List<Tuple<int, int>>();

            var sb = new StringBuilder();

            sb.Append(Run(data, 50, 10));

            Approvals.Verify(sb.ToString());
        }

        [Test]
        public void RenderableInObjectColumnShouldBeRendered()
        {
            var renderTableData = new[]
            {
                new {Col1 = 1, Col2 = "Two", Col3 = 3.0, Col4 = "Four"},
                new {Col1 = 2, Col2 = "Three", Col3 = 3.1, Col4 = "One Two Three Four Five"},
                new {Col1 = 3, Col2 = "Four point zero", Col3 = 3.2, Col4 = "One Two Three Four Five Six Seven"},
            };
            var renderable = new RecordingConsoleAdapter();
            renderable.WrapLine("Wrapped text longer than allowed for by avalable space limitations. Should be wrapped in the column");
            renderable.FormatTable(renderTableData);
            var data = new []
            {
                new {Item = "Item 1", Value = (object)15},
                new {Item = "Item 2", Value = (object)"string"},
                new {Item = "Item 3", Value = (object)new {X = 100, Y = 200}},
                new {Item = "Item 3", Value = (object)renderable},
            };

            var sb = new StringBuilder();

            sb.Append(Run(data, 50, 10));

            Approvals.Verify(sb.ToString());
        }

        [Test]
        public void HeadingRepeatsCanBeSuppressed()
        {
            var data = Enumerable.Range(0, 1)
                .AsReport(p => p.SuppressHeadingRepetition()
                    .AddColumn(r => "X", cc => cc.Heading("Value"))
                    .AddColumn(r => "Text", cc => cc.Heading("Text."))
                    .AddChild(i => Enumerable.Range(0, 2),
                        cr => cr.SuppressHeadingRepetition()
                                .AddColumn(i => i, cc => cc.Heading("Child Int"))
                                .AddChild(j => Enumerable.Range(0, 2),
                                    ccr => ccr.AddColumn(i => i, cc => cc.Heading("Child of Child Int")))));

            var sb = new StringBuilder();

            sb.Append(Run(data, 50));

            Approvals.Verify(sb.ToString());
        }

        [Test]
        public void ComputedColumnsCanBeUsed()
        {
            var data = Enumerable.Range(0, 2)
                .AsReport(p => p
                    .AddColumn(p.Lambda(r =>
                    {
                        if (r == 0) return "X";
                        return "Y";
                    }), cc => cc.Heading("Value"))
                    .AddColumn(p.Lambda(r => new string(".txeT".Reverse().ToArray())), cc => cc.Heading("Text."))
                );

            Approvals.Verify(Run(data, 50));
        }

        private RecordingConsoleAdapter MakeRenderable(int number, bool narrow = false)
        {
            var output = new RecordingConsoleAdapter();
            if (narrow)
                output.WrapLine("Narrow text");
            else
                output.WrapLine("Some wrapped text containing the index number :{0} and some more stuff.", number);

            var table = Enumerable.Range(0, number)
                .Select(i => new { Text = string.Format("Nested row {0}", i) });
            output.FormatTable(table, ReportFormattingOptions.StretchColumns);

            return output;
        }

        private static string Run<T>(IEnumerable<T> data, int width = 80, int numRowsToUseForSizing = 0, ReportFormattingOptions options = ReportFormattingOptions.Default, string columnDivider = null, IEnumerable<ColumnFormat> columnFormats = null)
        {
            var report = RulerFormatter.MakeRuler(width)
                         + Environment.NewLine
                         + string.Join(string.Empty, TabularReport.Format<T, T>(data, columnFormats, width,
                                            numRowsToUseForSizing, options, columnDivider));
            Console.WriteLine(report);
            return report;
        }

        private static string Run<T>(Report<T> report, int width = 80, int numRowsToUseForSizing = 0)
        {
            var formatMethod = MakeFormatMethodInfo(report);
            var parameters = new object[]
                                 {
                                     report.Query,
                                     report.Columns,
                                     width,
                                     numRowsToUseForSizing, //rows to use for sizing
                                     report.Options,
                                     report.ColumnDivider,
                                     report.Children
                                 };

            var tabular = MethodInvoker.Invoke(formatMethod, null, parameters) as IEnumerable<string>;
            var output = RulerFormatter.MakeRuler(width)
                         + Environment.NewLine
                         + string.Join(string.Empty, tabular);
            return output;
        }

        private static MethodInfo MakeFormatMethodInfo<T>(Report<T> report)
        {
            var genericMethod = typeof(TabularReport)
                .GetMethods(BindingFlags.Static | BindingFlags.Public)
                .FirstOrDefault(m => m.Name == "Format"
                                     && m.GetParameters()[0].ParameterType.GetInterfaces()
                                                            .Any(i => i == typeof(IEnumerable)));
            var formatMethod = genericMethod.MakeGenericMethod(report.RowType, typeof(T));
            return formatMethod;
        }

        private static string CachedReport<T>(CachedRows<T> data, int width = 80, ReportFormattingOptions options = ReportFormattingOptions.Default | ReportFormattingOptions.IncludeAllColumns, string columnDivider = null)
        {
            var report = RulerFormatter.MakeRuler(width)
                         + Environment.NewLine
                         + string.Join(string.Empty, TabularReport.Format(data, null, width, options, columnDivider));
            Console.WriteLine(report);
            return report;
        }
    }
}


text:
package distribution // import "github.com/docker/docker/distribution"

import (
	"errors"
	"strings"
	"syscall"
	"testing"

	"github.com/docker/distribution/registry/api/errcode"
	"github.com/docker/distribution/registry/client"
)

var errUnexpected = errors.New("some totally unexpected error")

var alwaysContinue = []error{
	&client.UnexpectedHTTPResponseError{},
	errcode.Errors{},
	errUnexpected,
	// nested
	errcode.Errors{errUnexpected},
	ErrNoSupport{Err: errUnexpected},
}

var continueFromMirrorEndpoint = []error{
	ImageConfigPullError{},
	errcode.Error{},
	// nested
	errcode.Errors{errcode.Error{}},
	ErrNoSupport{Err: errcode.Error{}},
}

var neverContinue = []error{
	errors.New(strings.ToLower(syscall.ESRCH.Error())), // No such process
}

func TestContinueOnError_NonMirrorEndpoint(t *testing.T) {
	for _, err := range alwaysContinue {
		if !continueOnError(err, false) {
			t.Errorf("Should continue from non-mirror endpoint: %T: '%s'", err, err.Error())
		}
	}

	for _, err := range continueFromMirrorEndpoint {
		if continueOnError(err, false) {
			t.Errorf("Should only continue from mirror endpoint: %T: '%s'", err, err.Error())
		}
	}
}

func TestContinueOnError_MirrorEndpoint(t *testing.T) {
	var errs []error
	errs = append(errs, alwaysContinue...)
	errs = append(errs, continueFromMirrorEndpoint...)
	for _, err := range errs {
		if !continueOnError(err, true) {
			t.Errorf("Should continue from mirror endpoint: %T: '%s'", err, err.Error())
		}
	}
}

func TestContinueOnError_NeverContinue(t *testing.T) {
	for _, isMirrorEndpoint := range []bool{true, false} {
		for _, err := range neverContinue {
			if continueOnError(err, isMirrorEndpoint) {
				t.Errorf("Should never continue: %T: '%s'", err, err.Error())
			}
		}
	}
}


text:
import mock
import six

from dci.common import utils
from dci.stores.s3 import S3

AWSS3 = "dci.stores.s3.S3"

# team_user_id is subscribing to topic_user_id

def test_topics_export_control_true(user, epm, team_user_id, topic_user_id):
    topic = epm.get("/api/v1/topics/%s" % topic_user_id).data["topic"]
    res = epm.post(
        "/api/v1/products/%s/teams" % topic["product_id"],
        data={"team_id": team_user_id},
    )
    assert res.status_code == 201

    epm.put(
        "/api/v1/topics/%s" % topic_user_id,
        data={"export_control": True},
        headers={"If-match": topic["etag"]},
    )
    topic = epm.get("/api/v1/topics/%s" % topic_user_id).data["topic"]
    assert topic["export_control"] is True
    # team_user_id is associated to the product and the topic is exported
    # then it should have access to the topic's components
    assert user.get("/api/v1/topics/%s/components" % topic_user_id).status_code == 200

def test_topics_export_control_false(user, admin, team_user_id, topic_user_id):
    topic = admin.get("/api/v1/topics/%s" % topic_user_id).data["topic"]

    assert topic["export_control"] is False
    assert user.get("/api/v1/topics/%s/components" % topic_user_id).status_code == 200

    # team_user_id is no associated to the product nor to the topic
    admin.delete("/api/v1/topics/%s/teams/%s" % (topic_user_id, team_user_id))
    assert user.get("/api/v1/topics/%s/components" % topic_user_id).status_code == 401

def test_components_export_control_true(
    user, epm, team_user_id, topic_user_id, components_user_ids
):
    topic = epm.get("/api/v1/topics/%s" % topic_user_id).data["topic"]
    res = epm.post(
        "/api/v1/products/%s/teams" % topic["product_id"],
        data={"team_id": team_user_id},
    )
    assert res.status_code == 201
    epm.put(
        "/api/v1/topics/%s" % topic_user_id,
        data={"export_control": True},
        headers={"If-match": topic["etag"]},
    )
    topic = epm.get("/api/v1/topics/%s" % topic_user_id).data["topic"]
    assert topic["export_control"] is True

    with mock.patch(AWSS3, spec=S3) as mock_s3:

        mockito = mock.MagicMock()
        mockito.get.return_value = ["test", six.StringIO("lollollel")]
        head_result = {
            "etag": utils.gen_etag(),
            "content-type": "stream",
            "content-length": 1,
        }
        mockito.head.return_value = head_result
        mock_s3.return_value = mockito

        url = "/api/v1/components/%s/files" % components_user_ids[0]
        c_file = epm.post(url, data="lol")
        c_file_1_id = c_file.data["component_file"]["id"]
        # team_user_id is not subscribing to topic_user_id but it's
        # associated to the product thus it can access the topic's components
        assert (
            user.get("/api/v1/components/%s" % components_user_ids[0]).status_code
            == 200
        )
        assert (
            user.get("/api/v1/components/%s/files" % components_user_ids[0]).status_code
            == 200
        )
        assert (
            user.get(
                "/api/v1/components/%s/files/%s" % (components_user_ids[0], c_file_1_id)
            ).status_code
            == 200
        )
        assert (
            user.get(
                "/api/v1/components/%s/files/%s/content"
                % (components_user_ids[0], c_file_1_id)
            ).status_code
            == 200
        )

def test_components_export_control_false(
    user, epm, team_user_id, topic_user_id, components_user_ids
):
    topic = epm.get("/api/v1/topics/%s" % topic_user_id).data["topic"]
    res = epm.post(
        "/api/v1/products/%s/teams" % topic["product_id"],
        data={"team_id": team_user_id},
    )
    assert res.status_code == 201

    with mock.patch(AWSS3, spec=S3) as mock_s3:

        mockito = mock.MagicMock()
        mockito.get.return_value = ["test", six.StringIO("lollollel")]
        head_result = {
            "etag": utils.gen_etag(),
            "content-type": "stream",
            "content-length": 1,
        }
        mockito.head.return_value = head_result
        mock_s3.return_value = mockito

        url = "/api/v1/components/%s/files" % components_user_ids[0]
        c_file = epm.post(url, data="lol")
        c_file_1_id = c_file.data["component_file"]["id"]

        assert topic["export_control"] is False
        assert (
            user.get("/api/v1/components/%s" % components_user_ids[0]).status_code
            == 200
        )
        assert (
            user.get("/api/v1/components/%s/files" % components_user_ids[0]).status_code
            == 200
        )
        assert (
            user.get(
                "/api/v1/components/%s/files/%s" % (components_user_ids[0], c_file_1_id)
            ).status_code
            == 200
        )
        assert (
            user.get(
                "/api/v1/components/%s/files/%s/content"
                % (components_user_ids[0], c_file_1_id)
            ).status_code
            == 200
        )

        # team_user_id is associated to the product but not to the topic,
        # since the topic is not exported the user doesn't have the access
        epm.delete("/api/v1/topics/%s/teams/%s" % (topic_user_id, team_user_id))
        assert (
            user.get("/api/v1/components/%s" % components_user_ids[0]).status_code
            == 401
        )
        assert (
            user.get("/api/v1/components/%s/files" % components_user_ids[0]).status_code
            == 401
        )
        assert (
            user.get(
                "/api/v1/components/%s/files/%s" % (components_user_ids[0], c_file_1_id)
            ).status_code
            == 401
        )
        assert (
            user.get(
                "/api/v1/components/%s/files/%s/content"
                % (components_user_ids[0], c_file_1_id)
            ).status_code
            == 401
        )


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EleicaoBrasil.Model
{
    public class User
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int id { get; set; }
        public string name { get; set; }
        public string photo { get; set; }
        public string email { get; set; }
        public string idSocial { get; set; }
        public string lastName { get; set; }
        public string firstName { get; set; }
        public string gender { get; set; }
        public string birthday { get; set; }
    }
}


text:
<?php
namespace SC\UserBundle\Entity;

use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\OrderBy;
use FOS\UserBundle\Entity\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;

use SC\CommonBundle\Entity\Photo;

/**
 * @ORM\Entity
 * @ORM\Table(name="Users")
 * @ORM\Entity(repositoryClass="SC\UserBundle\Entity\Repositories\UserRepository")
 */
class User extends BaseUser
{
    use TimestampableEntity;

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    protected $name;
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    protected $surname;
    /**
     * @ORM\ManyToOne(targetEntity="SC\CommonBundle\Entity\Photo")
     * @ORM\JoinColumn(name="photo", referencedColumnName="id", onDelete="SET NULL")
     * @var Photo
     */
    protected $photo;
    /**
     * @Assert\File(
     *     mimeTypes={"image/jpeg", "image/pjpeg", "image/png", "image/x-png"}
     * )
     */
    protected $newPhoto;
    /**
     * @ORM\ManyToMany(targetEntity="SC\UserBundle\Entity\Lesson", cascade={"persist"})
     * @ORM\JoinTable(name="students_lessons",
     *      joinColumns={@ORM\JoinColumn(name="lesson_id", referencedColumnName="id", onDelete="CASCADE")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="student_id", referencedColumnName="id")}
     *      )
     */
    protected $lessons;
    /**
     * @ORM\ManyToOne(targetEntity="SC\UserBundle\Entity\Department", cascade={"persist"})
     * @ORM\JoinColumn(name="department_id", referencedColumnName="id", onDelete="RESTRICT")
     */
    protected $department;
    /**
     * @ORM\OneToMany(targetEntity="SC\SiteBundle\Entity\Post", mappedBy="student")
     */
    protected $posts;
    /**
     * @ORM\OneToMany(targetEntity="SC\UserBundle\Entity\PrivateMessage", mappedBy="sender")
     */
    protected $sentMessages;
    /**
     * @ORM\OneToMany(targetEntity="SC\UserBundle\Entity\PrivateMessage", mappedBy="receiver")
     */
    protected $receivedMessages;
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    protected $fbId;
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    protected $fbEmail;
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    protected $fbAccessToken;

    public function __construct() {
        parent::__construct();
        $this->lessons = new ArrayCollection();
        $this->posts = new ArrayCollection();
        $this->sentMessages = new ArrayCollection();
        $this->receivedMessages = new ArrayCollection();
    }

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

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

    public function getName() {
        return $this->name;
    }

    public function setName($name) {
        $this->name = $name;
    }

    public function getSurname() {
        return $this->surname;
    }

    public function setSurname($surname) {
        $this->surname = $surname;
    }

    public function getPhoto() {
        if(!isset($this->photo)) { $this->photo = new Photo(); }
        return $this->photo;
    }

    public function setPhoto(Photo $photo) {
        $this->photo = $photo;
    }

    public function getAvatarUrl() {
        return $this->getPhoto()->getImagePath();
    }

    public function getNewPhoto() {
        return $this->newPhoto;
    }

    public function setNewPhoto($newPhoto) {
        $this->newPhoto = $newPhoto;
    }

    public function getLessons() {
        return $this->lessons;
    }

    public function setLessons($lessons) {
        $this->lessons = $lessons;
    }

    public function getAllLessons() {
        global $kernel;
        return $kernel->getContainer()->get('doctrine')->getRepository('SC\UserBundle\Entity\Lesson')->findAll();
    }

    public function getDepartment() {
        return $this->department;
    }

    public function setDepartment($department) {
        $this->department = $department;
    }

    public function getPosts() {
        return $this->posts;
    }

    public function setPosts($posts) {
        $this->posts = $posts;
    }

    public function getSentMessages() {
        return $this->sentMessages;
    }

    public function setSentMessages($sentMessages) {
        $this->sentMessages = $sentMessages;
    }

    public function getReceivedMessages() {
        return $this->receivedMessages;
    }

    public function setReceivedMessages($receivedMessages) {
        $this->receivedMessages = $receivedMessages;
    }

    public function getFbId() {
        return $this->fbId;
    }

    public function setFbId($fbId) {
        $this->fbId = $fbId;
    }

    public function getFbEmail() {
        return $this->fbEmail;
    }

    public function setFbEmail($fbEmail) {
        $this->fbEmail = $fbEmail;
    }

    public function getFbAccessToken() {
        return $this->fbAccessToken;
    }

    public function setFbAccessToken($fbAccessToken) {
        $this->fbAccessToken = $fbAccessToken;
    }

    public function getExpiresAt() {
        return $this->expiresAt;
    }

    public function getCredentialsExpireAt() {
        return $this->credentialsExpireAt;
    }
}


text:
<?php

namespace Base\Www\Html\Tag;

interface Tag
{
    public function getTagName();
}


text:
require 'spec_helper'

RSpec.describe Cryptoexchange::Exchanges::Koinx::Market do
  it { expect(described_class::NAME).to eq 'koinx' }
  it { expect(described_class::API_URL).to eq 'https://koinx.id/api' }
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- ================================================== -->

	<bean id="userRepoCache" class="com.mossle.user.support.UserRepoCacheImpl">
		<property name="cacheStrategy" ref="localCacheStrategy"/>
	</bean>

	<bean id="userRepoConnector" class="com.mossle.user.support.UserRepoConnectorFactoryBean">
		<property name="type" value="${bridge.userrepo.type}"/>
		<property name="userRepoCache" ref="userRepoCache"/>
		<property name="jdbcTemplate" ref="jdbcTemplate"/>
	</bean>

	<bean class="com.mossle.user.support.UserRepoPopulator">
		<property name="debug" value="${bridge.userrepo.debug}"/>
	</bean>

	<!-- ================================================== -->

	<bean id="userCache" class="com.mossle.user.support.UserCacheImpl">
		<property name="cacheStrategy" ref="remoteCacheStrategy"/>
	</bean>

	<bean id="userConnector" class="com.mossle.user.support.UserConnectorFactoryBean">
		<property name="type" value="${bridge.user.type}"/>
		<property name="userCache" ref="userCache"/>
		<property name="jdbcTemplate" ref="jdbcTemplate"/>
	</bean>

	<!-- ================================================== -->

	<bean id="userAuthCache" class="com.mossle.auth.support.UserAuthCacheImpl">
		<property name="cacheStrategy" ref="remoteCacheStrategy"/>
	</bean>

	<bean id="userAuthConnector" class="com.mossle.auth.support.UserAuthConnectorFactoryBean">
		<property name="type" value="${bridge.userauth.type}"/>
		<property name="userAuthCache" ref="userAuthCache"/>
		<property name="jdbcTemplate" ref="jdbcTemplate"/>
		<property name="userConnector" ref="userConnector"/>
		<property name="scopeConnector" ref="scopeConnector"/>
	</bean>

	<!-- ================================================== -->

	<!-- 这个是SPI,仅在spring security认证时获取密码用 -->
	<bean id="accountCredentialConnector" class="${user.accountCredentialConnector}"/>

	<!-- 管理用户时,同步party的工具(应该是人事模块吗?还没想明白) -->
	<bean id="userNotification" class="com.mossle.user.notification.PartyUserNotification"/>

	<!-- 获取账号状态的工具(应该是spi吗?还没想明白) -->
	<bean id="accountStatusHelper" class="com.mossle.user.support.LocalAccountStatusHelper"/>

</beans>


text:
ActiveRecord::Schema.define(:version => 20130401061829) do

  create_table "github_users", :force => true do |t|
    t.string   "login"
    t.boolean  "admin"
    t.boolean  "approved"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  add_index "github_users", ["login"], :name => "index_github_users_on_login", :unique => true

  create_table "watched_repos", :force => true do |t|
    t.string   "owner"
    t.string   "repo_name"
    t.string   "event"
    t.string   "secret"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MyController extends CI_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->model('model');
	}
	public function index()
	{
		//$data['err_message'] = ""; //untuk load controllet ke view biasanya data butuh dibuat array, didfunction loginalam array data tersembut ada error message.
		$this->load->view('sebelum/index');
	}
	function home(){
		$this->load->view('sebelum/index');
	}
	function homee(){
		$this->load->view('sesudah/index');
	}
	function login(){
		$username = $this->input->post('username');
		$enpass = $this->input->post('pass');
		$password = md5($enpass);
		//get data
		$isLogin = $this->model->login_authen($username,$password);
		$i=$this->model->authen_user($username);
		if($isLogin->num_rows()==1 ){
			foreach ($isLogin->result()as $user) {
                            $session_data = array(
						'username'	=> $username,
                                                'role'          => 'user',
						'logged_in'	=> TRUE
						);
			//$user_sess['username'] = $user->username;
			$this->session->set_userdata($session_data);
			}
			$this->homee($username);
		}
		else{
                                redirect('MyController/home');
		}

	}
	function aksi(){
		$this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[5]|max_length[200]');
		$this->form_validation->set_rules('phone','Phone','trim|required|min_length[11]|numeric|is_natural');
		$this->form_validation->set_rules('address', 'Address', 'trim|required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[user.email]');
		$this->form_validation->set_rules(
        'username', 'Username',
        'required|min_length[5]|max_length[12]|is_unique[user.username]',
        array(
                'required'      => 'You have not provided %s.',
                'is_unique'     => 'This %s already exists.'
        ));
		$this->form_validation->set_rules('password','Password','required');
		$this->form_validation->set_rules('confirmpw','Confirmpw','required|matches[password]');
		$this->form_validation->set_message('name','required min length 5 max length 100');
                $this->form_validation->set_message('phone','required');
                $this->form_validation->set_message('email','email already exist or you don\'t enter a valid mail');
		$this->form_validation->set_message('confirmpw','The Confirm password doesnt match password');
		if($this->form_validation->run() != false){
			$this->createakun();
		}else{
                    redirect('MyController/home');
		}
	}

	function createakun(){
		$passen = $this->input->post('password');
		 $email = $this->input->post('email');
		$newpass = md5($passen);
		$data = array(
				'username' => $this->input->post('username'),
				'name' => $this->input->post('name'),
				'email' => $this->input->post('email'),
				'phone' => $this->input->post('phone'),
				'password'=> $newpass,
				'address' => $this->input->post('address'),
				'value' => 0
			);

		$username = $this->model->addAkun($data);
		//$this->index();
		}
	function logout(){
		$this->session->unset_userdata('username');
		$this->session>session_destroy();
		//$this->index();
                redirect('MyController/home');}
}


text:
package org.kie.workbench.common.forms.editor.client.editor.properties.binding;

import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Consumer;
import java.util.function.Supplier;

import org.junit.Before;
import org.kie.workbench.common.forms.model.FieldDefinition;
import org.mockito.Mock;

import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

public abstract class DataBinderEditorTest<EDITOR extends DataBindingEditor> {

    public static final String FIELD_BINDING = "field";
    public static final String NAME = "name";
    public static final String LAST_NAME = "lastName";
    public static final String ADDRESS = "address";
    public static final String CITY = "city";
    public static final String CP = "cp";

    protected Set<String> fields = new TreeSet<>();

    @Mock
    protected FieldDefinition fieldDefinition;

    protected Consumer<String> bindingChangeConsumer;

    protected Supplier<Collection<String>> bindingsSupplier;

    protected EDITOR editor;

    @Before
    public void initTest() {

        fields.add(FIELD_BINDING);
        fields.add(NAME);
        fields.add(LAST_NAME);
        fields.add(ADDRESS);
        fields.add(CITY);
        fields.add(CP);

        bindingsSupplier = spy(new Supplier<Collection<String>>() {
            @Override
            public Collection<String> get() {
                return fields;
            }
        });

        bindingChangeConsumer = spy(new Consumer<String>() {
            @Override
            public void accept(String s) {

            }
        });

        when(fieldDefinition.getBinding()).thenReturn(FIELD_BINDING);
    }
}


text:
<?php

class Google_Service_AdExchangeBuyer_GetOrderNotesResponse extends Google_Collection
{
  protected $collection_key = 'notes';
  protected $notesType = 'Google_Service_AdExchangeBuyer_MarketplaceNote';
  protected $notesDataType = 'array';

  public function setNotes($notes)
  {
    $this->notes = $notes;
  }
  public function getNotes()
  {
    return $this->notes;
  }
}


text:
/**
 * @file	E:\projects\imcore\src\im-conn.h
 *
 * @brief	Declares the im connection class.
 */
#ifndef __IMCORE_CONN_H__
#define __IMCORE_CONN_H__
#endif //  __IMCORE_CONN_H__


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Sérgio Porto</logradouro><bairro>Ideal</bairro><cidade>Ipatinga</cidade><uf>MG</uf><cep>35162538</cep></feed>


text:
Use collection view to implement an effect like transferring a book.

##功能
使用collectionview实现翻书效果