text:
package com.abuabdul.fourt.config;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * @author abuabdul
 *
 */
@Configuration
@Profile("production")
public class FourTStandaloneDataSourceConfig extends FourTConfig {

	@Bean(destroyMethod = "close")
	public DataSource dataSource() {
		BasicDataSource datasource = new BasicDataSource();
		datasource.setDriverClassName(driverClassName);
		datasource.setUrl(getSQLDBUrl());
		datasource.setUsername(username);
		datasource.setPassword(password);
		datasource.setInitialSize(initialSize);
		datasource.setMinIdle(minIdle);
		datasource.setMaxIdle(maxIdle);
		datasource.setMaxTotal(maxTotal);
		datasource.setMaxWaitMillis(maxWaitMillis);
		return datasource;
	}

	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
		LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
		entityManagerFactory.setDataSource(dataSource());
		entityManagerFactory.setPersistenceUnitName("allPrivileges");
		entityManagerFactory.setJpaDialect(new HibernateJpaDialect());
		entityManagerFactory.setPersistenceProvider(new HibernatePersistenceProvider());
		entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
		entityManagerFactory.setPackagesToScan(packagesToScan);
		return entityManagerFactory;
	}

	@Bean(name = "transactionManager")
	public PlatformTransactionManager jpaTransactionManager() {
		JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
		jpaTransactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
		return jpaTransactionManager;
	}

	protected String getSQLDBUrl() {
		return new StringBuilder("jdbc:hsqldb:hsql://").append(host).append(":").append(port).append("/")
				.append(taskTrackerDBName).toString();
	}

	@Bean(destroyMethod = "close")
	public DataSource readOnlyDataSource() {
		BasicDataSource datasource = new BasicDataSource();
		datasource.setDriverClassName(driverClassName);
		datasource.setUrl(getSQLDBUrl());
		datasource.setUsername(readOnlyUser);
		datasource.setPassword(readOnlyPassword);
		datasource.setInitialSize(initialSize);
		datasource.setMinIdle(minIdle);
		datasource.setMaxIdle(maxIdle);
		datasource.setMaxTotal(maxTotal);
		datasource.setMaxWaitMillis(maxWaitMillis);
		return datasource;
	}

	@Bean
	public LocalContainerEntityManagerFactoryBean readOnlyEntityManagerFactoryBean() {
		LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
		entityManagerFactory.setDataSource(readOnlyDataSource());
		entityManagerFactory.setPersistenceUnitName("readOnly");
		entityManagerFactory.setJpaDialect(new HibernateJpaDialect());
		entityManagerFactory.setPersistenceProvider(new HibernatePersistenceProvider());
		entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
		entityManagerFactory.setPackagesToScan(packagesToScan);
		return entityManagerFactory;
	}

	@Bean(name = "readOnlyTransactionManager")
	public PlatformTransactionManager readOnlyJpaTransactionManager() {
		JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
		jpaTransactionManager.setEntityManagerFactory(readOnlyEntityManagerFactoryBean().getObject());
		return jpaTransactionManager;
	}
}


text:
package com.tle.beans.audit;

import com.tle.beans.Institution;
import java.io.Serializable;
import java.util.Date;

public interface AuditLogTable extends Serializable {
  long getId();

  Institution getInstitution();

  Date getTimestamp();

  String getUserId();

  String getSessionId();

  void setInstitution(Institution institution);

  void setId(long id);
}

redpajama_set_name: RedPajamaGithub


text:
import currentPlaceSelector from '../currentPlaceSelector';
import { fromJS } from 'immutable';
import expect from 'expect';

const selector = currentPlaceSelector();

describe('currentPlaceSelector', () => {

});


text:
""" Test NumPy Eigen solver """

import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase

import numpy as np
from ddt import data, ddt

from qiskit.algorithms import NumPyEigensolver
from qiskit.opflow import PauliSumOp, X, Y, Z

@ddt
class TestNumPyEigensolver(QiskitAlgorithmsTestCase):
    """Test NumPy Eigen solver"""

    def setUp(self):
        super().setUp()
        self.qubit_op = PauliSumOp.from_list(
            [
                ("II", -1.052373245772859),
                ("ZI", 0.39793742484318045),
                ("IZ", -0.39793742484318045),
                ("ZZ", -0.01128010425623538),
                ("XX", 0.18093119978423156),
            ]
        )

    def test_ce(self):
        """Test basics"""
        algo = NumPyEigensolver()
        result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=[])
        self.assertEqual(len(result.eigenvalues), 1)
        self.assertEqual(len(result.eigenstates), 1)
        self.assertEqual(result.eigenvalues.dtype, np.float64)
        self.assertAlmostEqual(result.eigenvalues[0], -1.85727503)

    def test_ce_k4(self):
        """Test for k=4 eigenvalues"""
        algo = NumPyEigensolver(k=4)
        result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=[])
        self.assertEqual(len(result.eigenvalues), 4)
        self.assertEqual(len(result.eigenstates), 4)
        self.assertEqual(result.eigenvalues.dtype, np.float64)
        np.testing.assert_array_almost_equal(
            result.eigenvalues, [-1.85727503, -1.24458455, -0.88272215, -0.22491125]
        )

    def test_ce_k4_filtered(self):
        """Test for k=4 eigenvalues with filter"""

        # define filter criterion
        # pylint: disable=unused-argument
        def criterion(x, v, a_v):
            return v >= -1

        algo = NumPyEigensolver(k=4, filter_criterion=criterion)
        result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=[])
        self.assertEqual(len(result.eigenvalues), 2)
        self.assertEqual(len(result.eigenstates), 2)
        self.assertEqual(result.eigenvalues.dtype, np.float64)
        np.testing.assert_array_almost_equal(result.eigenvalues, [-0.88272215, -0.22491125])

    def test_ce_k4_filtered_empty(self):
        """Test for k=4 eigenvalues with filter always returning False"""

        # define filter criterion
        # pylint: disable=unused-argument
        def criterion(x, v, a_v):
            return False

        algo = NumPyEigensolver(k=4, filter_criterion=criterion)
        result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=[])
        self.assertEqual(len(result.eigenvalues), 0)
        self.assertEqual(len(result.eigenstates), 0)

    @data(X, Y, Z)
    def test_ce_k1_1q(self, op):
        """Test for 1 qubit operator"""
        algo = NumPyEigensolver(k=1)
        result = algo.compute_eigenvalues(operator=op)
        np.testing.assert_array_almost_equal(result.eigenvalues, [-1])

    @data(X, Y, Z)
    def test_ce_k2_1q(self, op):
        """Test for 1 qubit operator"""
        algo = NumPyEigensolver(k=2)
        result = algo.compute_eigenvalues(operator=op)
        np.testing.assert_array_almost_equal(result.eigenvalues, [-1, 1])

    def test_aux_operators_list(self):
        """Test list-based aux_operators."""
        aux_op1 = PauliSumOp.from_list([("II", 2.0)])
        aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)])
        aux_ops = [aux_op1, aux_op2]
        algo = NumPyEigensolver()
        result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=aux_ops)
        self.assertEqual(len(result.eigenvalues), 1)
        self.assertEqual(len(result.eigenstates), 1)
        self.assertEqual(result.eigenvalues.dtype, np.float64)
        self.assertAlmostEqual(result.eigenvalues[0], -1.85727503)
        self.assertEqual(len(result.aux_operator_eigenvalues), 1)
        self.assertEqual(len(result.aux_operator_eigenvalues[0]), 2)
        # expectation values
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0][0], 2, places=6)
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0][1][0], 0, places=6)
        # standard deviations
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0][1], 0.0)
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0][1][1], 0.0)

        # Go again with additional None and zero operators
        extra_ops = [*aux_ops, None, 0]
        result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=extra_ops)
        self.assertEqual(len(result.eigenvalues), 1)
        self.assertEqual(len(result.eigenstates), 1)
        self.assertEqual(result.eigenvalues.dtype, np.float64)
        self.assertAlmostEqual(result.eigenvalues[0], -1.85727503)
        self.assertEqual(len(result.aux_operator_eigenvalues), 1)
        self.assertEqual(len(result.aux_operator_eigenvalues[0]), 4)
        # expectation values
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0][0], 2, places=6)
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0][1][0], 0, places=6)
        self.assertIsNone(result.aux_operator_eigenvalues[0][2], None)
        self.assertEqual(result.aux_operator_eigenvalues[0][3][0], 0.0)
        # standard deviations
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0][1], 0.0)
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0][1][1], 0.0)
        self.assertEqual(result.aux_operator_eigenvalues[0][3][1], 0.0)

    def test_aux_operators_dict(self):
        """Test dict-based aux_operators."""
        aux_op1 = PauliSumOp.from_list([("II", 2.0)])
        aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)])
        aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2}
        algo = NumPyEigensolver()
        result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=aux_ops)
        self.assertEqual(len(result.eigenvalues), 1)
        self.assertEqual(len(result.eigenstates), 1)
        self.assertEqual(result.eigenvalues.dtype, np.float64)
        self.assertAlmostEqual(result.eigenvalues[0], -1.85727503)
        self.assertEqual(len(result.aux_operator_eigenvalues), 1)
        self.assertEqual(len(result.aux_operator_eigenvalues[0]), 2)
        # expectation values
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0]["aux_op1"][0], 2, places=6)
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0]["aux_op2"][0], 0, places=6)
        # standard deviations
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0]["aux_op1"][1], 0.0)
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0]["aux_op2"][1], 0.0)

        # Go again with additional None and zero operators
        extra_ops = {**aux_ops, "None_operator": None, "zero_operator": 0}
        result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=extra_ops)
        self.assertEqual(len(result.eigenvalues), 1)
        self.assertEqual(len(result.eigenstates), 1)
        self.assertEqual(result.eigenvalues.dtype, np.float64)
        self.assertAlmostEqual(result.eigenvalues[0], -1.85727503)
        self.assertEqual(len(result.aux_operator_eigenvalues), 1)
        self.assertEqual(len(result.aux_operator_eigenvalues[0]), 3)
        # expectation values
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0]["aux_op1"][0], 2, places=6)
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0]["aux_op2"][0], 0, places=6)
        self.assertEqual(result.aux_operator_eigenvalues[0]["zero_operator"][0], 0.0)
        self.assertTrue("None_operator" not in result.aux_operator_eigenvalues[0].keys())
        # standard deviations
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0]["aux_op1"][1], 0.0)
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0]["aux_op2"][1], 0.0)
        self.assertAlmostEqual(result.aux_operator_eigenvalues[0]["zero_operator"][1], 0.0)

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


text:
get '/signup' do
  erb :'/auth/signup'
end

post '/signup' do
  a_user = User.create(params[:user])
  session[:user] = a_user.id
  redirect '/categories'
end

get '/logout' do
  session.clear
  redirect '/'
end

get '/login' do
  erb :'auth/login'
end

post '/login' do
  a_user = User.find_by(:email => params[:user][:email]).try(:authenticate, params[:user][:password])
  if a_user
    session[:user] = a_user.id
     redirect '/categories'
  else
    @invalid_login = true
    erb :'auth/login'
  end
end

get '/signup_partial' do
  erb :'/auth/signup', :layout => false
end


text:
package de.tbressler.waterrower.subscriptions.values;

import de.tbressler.waterrower.io.msg.in.DataMemoryMessage;
import de.tbressler.waterrower.subscriptions.AbstractMemorySubscription;
import de.tbressler.waterrower.subscriptions.Priority;

import static de.tbressler.waterrower.io.msg.Memory.TRIPLE_MEMORY;
import static de.tbressler.waterrower.model.MemoryLocation.MS_DISTANCE_DEC;
import static de.tbressler.waterrower.subscriptions.Priority.HIGH;
import static de.tbressler.waterrower.utils.MessageUtils.intFromHighAndLow;

/**
 * Subscription for the current distance.
 *
 * The value will be set to 0 by the Performance Monitor when a new row interval begins or
 * the user performs a RESET.
 *
 * @author Tobias Bressler
 * @version 1.0
 */
public abstract class DistanceSubscription extends AbstractMemorySubscription {

    /* The last distance received. */
    private double lastDistance = -1D;

    /**
     * Subscription to the distance values.
     */
    public DistanceSubscription() {
        this(HIGH);
    }

    /**
     * Subscription to the distance values.
     *
     * @param priority The priority (recommended HIGH).
     */
    public DistanceSubscription(Priority priority) {
        super(priority, TRIPLE_MEMORY, MS_DISTANCE_DEC);
    }

    @Override
    protected final void handle(DataMemoryMessage msg) {

        double distance = intFromHighAndLow(msg.getValue3(), msg.getValue2()) + (((double) msg.getValue1()) / 100D);

        // If the received distance is the same as before,
        // don't send an update.
        if (lastDistance == distance)
            return;
        lastDistance = distance;

        // Notify update.
        onDistanceUpdated(distance);
    }

    /**
     * Is called if the value for the current distance was updated.
     *
     * @param distance The new distance (in meter).
     */
    abstract protected void onDistanceUpdated(double distance);

}


text:
package org.python.util.install.driver;

import java.io.File;

import org.python.util.install.JarInstaller;

public interface Verifier {

    public static final String JYTHON_JAR = JarInstaller.JYTHON_JAR;

    public void setTargetDir(File targetDir);

    public File getTargetDir();

    public void verify() throws DriverException;

}


text:
from django.db import models
from django.conf import settings
from django.utils.translation import gettext_lazy as _
import hashlib
import datetime
#from django.utils.text import slugify
from django.template.defaultfilters import slugify
from cambridge.models import Registration
from django.core.mail import send_mail, mail_admins

import logging
log = logging.getLogger("MatriculaEIDE")

class Pago(models.Model):
    importe = models.DecimalField(max_digits=6, decimal_places=2)
    descripcion = models.CharField(_('Concepto'),max_length=250,blank=True)
    fecha_creacion = models.DateField(auto_now_add=True)
    fecha_pago = models.DateField(null=True,blank=True)
    def get_absolute_url(self):
        return "/pagos/pago/%i/" % self.id
    def set_as_paid(self):
        log.debug("Vamos a marcar como pagado el pago: %s con la descripcion %s"%(self.id,self.descripcion))
        self.fecha_pago = datetime.date.today()
        log.debug("Mandamos un mail de confirmacion")
        self.send_paiment_confirmation_email()
        log.debug("Guardamos...")
        self.save()
        return True
    def send_paiment_confirmation_email(self):
		subject = "[PagosOnline] Se ha confirmado un pago manual online"
		message_body = u"""Se acaba de confirmar un pago online creado manualmente. Los datos son: \n
        \tid: %s. \n
        \tfecha creacion: %s. \n
        \tdescripcion: %s. \n
        \timporte: %s. \n
"""%(self.id,self.fecha_creacion,self.descripcion,self.importe)
		mail_admins(subject, message_body)


text:
from django import forms

from Food.models import Food

class FoodForm(forms.ModelForm):
    class Meta:
        model = Food
        fields = ('name', 'description', 'calories')


text:
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace System
{
    static partial class StringNormalizationExtensions
    {
        [SecurityCritical]
        public static bool IsNormalized(this string value, NormalizationForm normalizationForm)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            Contract.EndContractBlock();

            // The only way to know if IsNormalizedString failed is through checking the Win32 last error
            Interop.mincore.SetLastError(Interop.ERROR_SUCCESS);
            bool result = Interop.mincore.IsNormalizedString((int)normalizationForm, value, value.Length);

            int lastError = Marshal.GetLastWin32Error();
            switch (lastError)
            {
                case Interop.ERROR_SUCCESS:
                case Interop.LAST_ERROR_TRASH_VALUE:
                    break;

                case Interop.ERROR_INVALID_PARAMETER:
                case Interop.ERROR_NO_UNICODE_TRANSLATION:
                    throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, nameof(value));

                case Interop.ERROR_NOT_ENOUGH_MEMORY:
                    throw new OutOfMemoryException(SR.Arg_OutOfMemoryException);

                default:
                    throw new InvalidOperationException(SR.Format(SR.UnknownError_Num, lastError));
            }

            return result;
        }

        [SecurityCritical]
        public static string Normalize(this string value, NormalizationForm normalizationForm)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            Contract.EndContractBlock();

            // we depend on Win32 last error when calling NormalizeString
            Interop.mincore.SetLastError(Interop.ERROR_SUCCESS);

            // Guess our buffer size first
            int iLength = Interop.mincore.NormalizeString((int)normalizationForm, value, value.Length, null, 0);

            int lastError = Marshal.GetLastWin32Error();
            // Could have an error (actually it'd be quite hard to have an error here)
            if ((lastError != Interop.ERROR_SUCCESS && lastError != Interop.LAST_ERROR_TRASH_VALUE) ||
                 iLength < 0)
            {
                if (lastError == Interop.ERROR_INVALID_PARAMETER)
                    throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, nameof(value));

                // We shouldn't really be able to get here..., guessing length is
                // a trivial math function...
                // Can't really be Out of Memory, but just in case:
                if (lastError == Interop.ERROR_NOT_ENOUGH_MEMORY)
                    throw new OutOfMemoryException(SR.Arg_OutOfMemoryException);

                // Who knows what happened?  Not us!
                throw new InvalidOperationException(SR.Format(SR.UnknownError_Num, lastError));
            }

            // Don't break for empty strings (only possible for D & KD and not really possible at that)
            if (iLength == 0) return string.Empty;

            // Someplace to stick our buffer
            char[] cBuffer = null;

            for (; ;)
            {
                // (re)allocation buffer and normalize string
                cBuffer = new char[iLength];

                // Reset last error
                Interop.mincore.SetLastError(Interop.ERROR_SUCCESS);
                iLength = Interop.mincore.NormalizeString((int)normalizationForm, value, value.Length, cBuffer, cBuffer.Length);
                lastError = Marshal.GetLastWin32Error();

                if (lastError == Interop.ERROR_SUCCESS || lastError == Interop.LAST_ERROR_TRASH_VALUE)
                    break;

                // Could have an error (actually it'd be quite hard to have an error here)
                switch (lastError)
                {
                    // Do appropriate stuff for the individual errors:
                    case Interop.ERROR_INSUFFICIENT_BUFFER:
                        iLength = Math.Abs(iLength);
                        Debug.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
                        continue;

                    case Interop.ERROR_INVALID_PARAMETER:
                    case Interop.ERROR_NO_UNICODE_TRANSLATION:
                        // Illegal code point or order found.  Ie: FFFE or D800 D800, etc.
                        throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, nameof(value));

                    case Interop.ERROR_NOT_ENOUGH_MEMORY:
                        throw new OutOfMemoryException(SR.Arg_OutOfMemoryException);

                    default:
                        // We shouldn't get here...
                        throw new InvalidOperationException(SR.Format(SR.UnknownError_Num, lastError));
                }
            }

            // Copy our buffer into our new string, which will be the appropriate size
            return new string(cBuffer, 0, iLength);
        }

        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------
    }
}


text:
module Monads
  # Chain deferred callbacks.
  class Eventually
    # Create a new +Eventually+, pass in the block meant to be run later.
    #
    # @example
    #   e = Eventually.new do |success|
    #     intermediate_result = 5
    #     success.call(intermediate_result)
    #   end.and_then do |intermediate_result|
    #     final_result = intermediate_result * 2
    #
    #     Eventually.new do |success|
    #       success.call(final_result)
    #     end
    #   end
    #
    #   e.run do |result|
    #     puts "The result is #{result}"
    #     # => "The result is 10"
    #   end
    #
    # @param deferred [Proc] Callback to be run later.
    def initialize(&deferred)
      @deferred = deferred
    end

    # Chain another action. This creates a new instance holding a reference
    # to the previous one, but nothing is run at this point.
    #
    # Only when this new instance is run, all other instances are run in order
    # and fed into the next one.
    #
    # It is necessary to return another +Eventually+ from the block otherwise
    # chaining would not be possible
    #
    # @example
    #   e = Eventually.new do |success|
    #     intermediate_result = 5
    #     success.call(intermediate_result)
    #   end.and_then do |intermediate_result|
    #     final_result = intermediate_result * 2
    #
    #     Eventually.new do |success|
    #       success.call(final_result)
    #     end
    #   end
    #
    #   e.run do |result|
    #     puts "The result is #{result}"
    #     # => "The result is 10"
    #   end
    #
    # @param deferred [Proc] New callback to be run later,
    #                        Must return another +Eventually+.
    #
    # @return [Eventually] New monad to be run later.
    def and_then(&deferred)
      self.class.new do |success|
        run do |value|
          new_eventually = deferred.call(value)
          check_type(new_eventually)
          new_eventually.run(&success)
        end
      end
    end

    # Execute the dereffed action and give it the success block.
    # The action may then call the success block.
    #
    # @example
    #   e = Eventually.new do |success|
    #     result = 5
    #     success.call(result)
    #   end
    #
    #   e.run do |result|
    #     puts "The result is #{result}"
    #     # => "The result is 5"
    #   end
    #
    # @param success [Proc] A block to be passed to +@deferred+.
    def run(&success)
      @deferred.call(success)
    end

    protected

    # Check if the result is an +Eventually+ and raise a +TypeError+ if not.
    #
    # @param result [Object] Expected a +Eventually+.
    def check_type(result)
      return if result.is_a?(self.class)

      msg = "Expected an instance of #{self.class}, got #{result.class}"
      fail TypeError, msg
    end
  end
end


text:
package jodd.proxetta.fixtures.inv;

public class SubOne {

	public void sub() {
		System.out.print("####from sub");
	}

	public void callSub() {
		sub();
	}
}


text:
<bill session="110" type="h" number="3628" updated="2009-01-09T00:28:53-05:00">
	<status><introduced date="1190260800" datetime="2007-09-20"/></status>

	<introduced date="1190260800" datetime="2007-09-20"/>
	<titles>
		<title type="short" as="introduced">Promoting Charitable Actions Act of 2007</title>
		<title type="official" as="introduced">To amend the Internal Revenue Code of 1986 to extend for 4 years the enhanced charitable deduction for contributions of food inventory.</title>
	</titles>
	<sponsor id="412229"/>
	<cosponsors>
		<cosponsor id="400279" joined="2007-10-16"/>
	</cosponsors>
	<actions>
		<action date="1190260800" datetime="2007-09-20"><text>Referred to the House Committee on Ways and Means.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	9/20/2007--Introduced.<br/>Promoting Charitable Actions Act of 2007 - Amends the Internal Revenue Code to extend through 2011 the expansion of the tax deduction for charitable contributions of food inventory to taxpayers other than C corporations.
	</summary>
</bill>


text:
FROM ubuntu:20.04
ARG OTB_RELEASE=8.0.0

# Install system dependencies
COPY system-dependencies.txt .
RUN apt-get update -y \
 && apt-get upgrade -y \
 && cat system-dependencies.txt | DEBIAN_FRONTEND=noninteractive xargs apt-get install -y --no-install-recommends \
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/* system-dependencies.txt

# Install pre-compiled OTB binaries
RUN curl https://www.orfeo-toolbox.org/packages/archives/OTB/OTB-$OTB_RELEASE-Linux64.run -o OTB-$OTB_RELEASE-Linux64.run \
 && chmod +x OTB-$OTB_RELEASE-Linux64.run \
 && ./OTB-$OTB_RELEASE-Linux64.run --target /opt/otb \
 && rm OTB-$OTB_RELEASE-Linux64.run

# Symlink Python library to a known path for OTB
RUN ln -s /usr/lib/x86_64-linux-gnu/libpython3.8.so /opt/otb/lib/libpython3.8.so.rh-python38-1.0

# Persistant env
ENV CMAKE_PREFIX_PATH=/opt/otb
ENV PYTHONPATH=/opt/otb/lib/python
ENV GDAL_DRIVER_PATH=disable
ENV GDAL_DATA=/opt/otb/share/gdal
ENV PROJ_LIB=/opt/otb/share/proj
ENV PATH=/opt/otb/bin:$PATH
ENV OTB_APPLICATION_PATH=/opt/otb/lib/otb/applications
ENV LC_NUMERIC=C

# Default command when using 'docker run' or 'docker create'
CMD /bin/bash


text:
"""Time averages of the positions of a list of atoms.

The `TimeAveragedPositions` object is a Filter giving the averaged
positions of the atoms in a list of atoms.  To do this, it acts as an
Observer of the dynamics object moving the atoms, and it can itself be
observed by e.g. a `RestrictedCNA` filter or a Trajectory.
"""

__docformat__ = "restructuredtext en"

from ASE.Utilities.Subject import Subject
import Numeric

class TimeAveragedPositions(Subject):
    """Time averages of the positions of a list of atoms.

    The TimeAveragedPositions object is a Filter giving the averaged
    positions of the atoms in a list of atoms.  To do this, it acts as
    an Observer of the dynamics object moving the atoms, and it can
    itself be observed by e.g. a CNA filter or a Trajectory.  It must
    be attached to a dynamics to work properly.

    Created with the following arguments:

    atoms
        The list of atoms being studied.

    avgtime
        The number of steps over which the average should be calculated.

    avgfrequency
        How often the average should be calculated.  Must be >= avgtime

    modifyAtoms (default False)
        If true, the positions of the original atoms
        are modified to reflect the averaged positions immediately before
        any observers are called, and changed back immediately after.
        Probably only useful for parallel simulations.

    verbose (default False)
        Print debugging info.

    """
    def __init__(self, atoms, avgtime, avgfrequency, modifyAtoms=False,
                 verbose=False):
        Subject.__init__(self)
        self.atoms = atoms
        self.avgtime = avgtime
        self.frequency = avgfrequency
        self.modifyAtoms = modifyAtoms
        self.verbose = verbose
        if avgfrequency < avgtime:
            raise NotImplementedError, "Cannot yet handle observations more frequent than the averaging time."
        self.counter = 0
        self.n = 0
        self.avgpos = Numeric.zeros((len(atoms),3), Numeric.Float)
        self.ready = 0
        # Handle parallel simulations
        try:
            self.avgpos = atoms.RegisterArray(self.avgpos)
        except AttributeError:
            self.register = 0
        else:
            self.register = 1

    def __del__(self):
        if self.register:
            self.atoms.DeregisterArray(self.avgpos)

    def Update(self):
        """Called by the dynamics every time the atoms have changed."""
        self.counter += 1
        if self.ready:
            self.n = 0
            self.ready = 0
        # Only do something if it is time to accumulate an average
        if self.counter > self.frequency - self.avgtime:
            newpos = self.atoms.GetScaledPositions()
            self.n += 1
            if self.n == 1:
                if self.verbose:
                    print "Initializing average."
                self.avgpos[:] = newpos
            else:
                if self.verbose:
                    print "Accumulating average."
                self.avgpos += newpos
        if self.counter == self.frequency:
            if self.verbose:
                print "Calculating average (%d steps)." % self.n
            self.ready = 1
            self.avgpos /= self.n
            if self.modifyAtoms:
                if self.register:
                    newpos = self.atoms.RegisterArray(newpos)
                self.atoms.SetScaledPositions(self.avgpos)
                self.atoms.CheckNeighborLists()
            self.Notify()
            if self.modifyAtoms:
                self.atoms.SetScaledPositions(newpos)
                self.atoms.CheckNeighborLists()
                if self.register:
                    self.atoms.DeregisterArray(newpos)
            self.counter = 0

    def ForceNotify(self):
        """Force an average to be calculated, and notify observers.

        Mostly useful to force an output at the beginning of a calculation.
        In that case, no averaging is done, but the rest of the filter chain
        is activated.
        """
        self.counter = self.frequency - 1
        self.Update()

    def GetScaledPositions(self):
        """Get the time-averaged positions, if they are ready."""
        if self.verbose:
            print "Accessing average."
        if self.ready:
            return self.avgpos
        else:
            raise RuntimeError, "Averaged positions are not ready."

    def GetCartesianPositions(self):
        """Get the time-averaged positions, if they are ready."""
        return Numeric.matrixmultiply(self.GetScaledPositions(),
                                      self.atoms.GetUnitCell())

    def GetGeneralizedPositions(self):
        """Get the time-averaged positions as generalized coordinates, if they are ready."""
        return self.GetCartesianPositions().flat

    def SetCartesianPositions(self, pos):
        raise AttributeError, "It makes no sense to set the time-averaged positions."

    def SetGeneralizedPositions(self, pos):
        raise AttributeError, "It makes no sense to set the time-averaged positions."

    # All other calls are passed onto the atoms.
    # Is this a good idea, or should there be a "whitelist" ??    XXXXX

    def __getattr__(self, attr):
        return getattr(self.atoms, attr)


text:
from QUANTAXIS.QAUtil import QA_util_log_info
from QUANTAXIS.QAUtil import QA_util_date_valid,QA_util_date_stamp
from pandas import DataFrame
from bson.objectid import ObjectId
import numpy
import datetime

"""
按要求从数据库取数据,并转换成dataframe结构

"""
def QA_fetch_data(code,startDate,endDate,collections):
    #print(datetime.datetime.now())
    startDate=str(startDate)[0:10]
    endDate=str(endDate)[0:10]

    coll=collections
    if QA_util_date_valid(endDate)==True:

        list_a=[[],[],[],[],[],[],[]]

        for item in coll.find({'code':str(code)[0:6],"date_stamp":{"$lte":QA_util_date_stamp(endDate),"$gte":QA_util_date_stamp(startDate)}}):
            #print(item['code'])
            list_a[0].append(item['code'])
            list_a[1].append(item['open'])
            list_a[2].append(item['high'])
            list_a[3].append(item['low'])
            list_a[4].append(item['close'])
            list_a[5].append(item['volume'])
            list_a[6].append(item['date'])
            #print(datetime.datetime.now())
        data=numpy.asarray(list_a).transpose()
        #data=DataFrame(list_a).transpose()
        #print(datetime.datetime.now())
        return data
    else:
        QA_util_log_info('something wrong with date')


text:
<?php

declare(strict_types = 1);

use PHPUnit\Framework\TestCase;
use Sop\ASN1\Component\Identifier;
use Sop\ASN1\Element;

/**
 * @group encode
 * @group identifier
 *
 * @internal
 */
class IdentifierEncodeTest extends TestCase
{
    public function testUniversal()
    {
        $identifier = new Identifier(Identifier::CLASS_UNIVERSAL,
            Identifier::PRIMITIVE, Element::TYPE_BOOLEAN);
        $this->assertEquals(chr(0b00000001), $identifier->toDER());
    }

    public function testApplication()
    {
        $identifier = new Identifier(Identifier::CLASS_APPLICATION,
            Identifier::PRIMITIVE, Element::TYPE_BOOLEAN);
        $this->assertEquals(chr(0b01000001), $identifier->toDER());
    }

    public function testContextSpecific()
    {
        $identifier = new Identifier(Identifier::CLASS_CONTEXT_SPECIFIC,
            Identifier::PRIMITIVE, Element::TYPE_BOOLEAN);
        $this->assertEquals(chr(0b10000001), $identifier->toDER());
    }

    public function testPrivate()
    {
        $identifier = new Identifier(Identifier::CLASS_PRIVATE,
            Identifier::PRIMITIVE, Element::TYPE_BOOLEAN);
        $this->assertEquals(chr(0b11000001), $identifier->toDER());
    }

    public function testConstructed()
    {
        $identifier = new Identifier(Identifier::CLASS_UNIVERSAL,
            Identifier::CONSTRUCTED, Element::TYPE_SEQUENCE);
        $this->assertEquals(chr(0b00110000), $identifier->toDER());
    }

    public function testLongTag()
    {
        $identifier = new Identifier(Identifier::CLASS_APPLICATION,
            Identifier::CONSTRUCTED, (0x7f << 7) + 0x7f);
        $this->assertEquals(chr(0b01111111) . "\xff\x7f", $identifier->toDER());
    }

    public function testHugeTag()
    {
        $num = gmp_init(str_repeat('1111111', 100) . '1111111', 2);
        $identifier = new Identifier(Identifier::CLASS_APPLICATION,
            Identifier::CONSTRUCTED, gmp_strval($num, 10));
        $this->assertEquals(chr(0b01111111) . str_repeat("\xff", 100) . "\x7f",
            $identifier->toDER());
    }
}


text:
import os
import json
import time
import requests
import socket

from path import Path
from urllib.parse import urljoin

from charmhelpers.core import hookenv, host, unitdata
from charms import layer
from charms.layer.apache_bigtop_base import Bigtop
from charms.reactive import is_state
from jujubigdata import utils

class Zeppelin(object):
    """
    This class manages Zeppelin.
    """
    def __init__(self):
        self.dist_config = utils.DistConfig(
            data=layer.options('apache-bigtop-base'))

    def _add_override(self, name, value):
        unitdata.kv().update({
            name: value,
        }, prefix='zeppelin.bigtop.overrides.')

    def install(self):
        '''
        Perform initial one-time setup, workaround upstream bugs, and
        trigger puppet.
        '''
        # Dirs are handled by the bigtop deb, so no need to call out to
        # dist_config to do that work.  However, we want to adjust the
        # groups for the `ubuntu` user for better interaction with Juju.
        self.dist_config.add_users()

        # Set ports based on layer.yaml options
        self._add_override('zeppelin::server::server_port',
                           self.dist_config.port('zeppelin'))
        self._add_override('zeppelin::server::web_socket_port',
                           self.dist_config.port('zeppelin_websocket'))

        # Default spark to local mode on initial install. This will be
        # reconfigured if/when hadoop or spark relations are made.
        local_master = 'local[*]'
        self._add_override('zeppelin::server::spark_master_url', local_master)

        # The spark-client role expects hdfs by default. Since we want to
        # keep Hadoop optional, ensure we remove hadoopy bits from our
        # local spark config. This has no effect if/when a remote spark joins,
        # and since there is no spark history server running, the event dirs
        # are not important -- they just need not be 'hdfs:///blah'.
        events_log_dir = 'file:///tmp'
        self._add_override('spark::common::master_url', local_master)
        self._add_override('spark::common::event_log_dir', events_log_dir)
        self._add_override('spark::common::history_log_dir', events_log_dir)

        ##########
        # BUG: BIGTOP-2742
        # Default zeppelin init script looks for the literal '$(hostname)'
        # string. Symlink it so it exists before the apt install from puppet
        # tries to start the service.
        import subprocess
        host = subprocess.check_output(['hostname']).decode('utf8').strip()
        zepp_pid = '/var/run/zeppelin/zeppelin-zeppelin-{}.pid'.format(host)
        utils.run_as('root', 'mkdir', '-p', '/var/run/zeppelin')
        utils.run_as('root', 'ln', '-sf',
                     zepp_pid,
                     '/var/run/zeppelin/zeppelin-zeppelin-$(hostname).pid')
        ##########

        self.trigger_bigtop()

        ##########
        # BUG: BIGTOP-2742
        # Puppet apply will call systemctl daemon-reload, which removes the
        # symlink we just created. Now that the bits are on disk, update the
        # init script $(hostname) that caused this mess to begin with.
        zepp_init_script = '/etc/init.d/zeppelin'
        utils.re_edit_in_place(zepp_init_script, {
            r'^# pidfile.*': '# pidfile: {}'.format(zepp_pid),
        })
        utils.run_as('root', 'systemctl', 'daemon-reload')
        self.restart()
        self.wait_for_api(30)
        ##########

    def trigger_bigtop(self):
        '''
        Trigger the Bigtop puppet recipe that handles the Zeppelin service.
        '''
        bigtop = Bigtop()
        overrides = unitdata.kv().getrange('zeppelin.bigtop.overrides.',
                                           strip=True)

        # The zep deb depends on spark-core which unfortunately brings in
        # most of hadoop. Include appropriate roles here to ensure these
        # packages are configured in the same way as our other Bigtop
        # software deployed with puppet.
        bigtop.render_site_yaml(
            roles=[
                'spark-client',
                'spark-yarn-slave',
                'zeppelin-server',
            ],
            overrides=overrides,
        )

        bigtop.trigger_puppet()
        self.wait_for_api(30)

    def reconfigure_zeppelin(self):
        '''
        Configure zeppelin based on current environment
        '''
        raise NotImplementedError()
        # NB (kwm): this method is not currently called because Bigtop spark
        # doesn't expose these settings. Leaving this here just in case
        # we update the bigtop charms to provide these bits in the future.
        etc_env = utils.read_etc_env()
        hadoop_extra_classpath = etc_env.get('HADOOP_EXTRA_CLASSPATH', '')
        spark_driver_mem = etc_env.get('SPARK_DRIVER_MEMORY', '1g')
        spark_exe_mode = os.environ.get('MASTER', 'yarn-client')
        spark_executor_mem = etc_env.get('SPARK_EXECUTOR_MEMORY', '1g')
        zeppelin_env = self.dist_config.path('zeppelin_conf') / 'zeppelin-env.sh'
        with open(zeppelin_env, "a") as f:
            f.write('export ZEPPELIN_CLASSPATH_OVERRIDES={}\n'.format(hadoop_extra_classpath))
            f.write('export ZEPPELIN_JAVA_OPTS="-Dspark.driver.memory={} -Dspark.executor.memory={}"\n'.format(
                spark_driver_mem,
                spark_executor_mem))
            f.write('export SPARK_SUBMIT_OPTIONS="--driver-memory {} --executor-memory {}"\n'.format(
                spark_driver_mem,
                spark_executor_mem))
            f.write('export MASTER={}\n'.format(spark_exe_mode))

    def configure_hadoop(self):
        # create hdfs storage space
        utils.run_as('hdfs', 'hdfs', 'dfs', '-mkdir', '-p', '/user/zeppelin')
        utils.run_as('hdfs', 'hdfs', 'dfs', '-chown', 'zeppelin', '/user/zeppelin')

        # If spark is ready, let configure_spark() trigger bigtop. Otherwise,
        # put our spark in yarn-client mode since hadoop is here.
        if not is_state('spark.ready'):
            self._add_override('spark::common::master_url', 'yarn-client')
            self._add_override('zeppelin::server::spark_master_url', 'yarn-client')
            self.trigger_bigtop()

    def configure_spark(self, master_url):
        '''
        Configure the zeppelin spark interpreter
        '''
        # TODO: Add config for Spark driver and executor memory overrides
        self._add_override('spark::common::master_url', master_url)
        self._add_override('zeppelin::server::spark_master_url', master_url)
        self.trigger_bigtop()

    def configure_hive(self, hive_url):
        '''
        Configure the zeppelin hive interpreter
        '''
        self._add_override('zeppelin::server::hiveserver2_url', hive_url)
        self.trigger_bigtop()

    def restart(self):
        self.stop()
        self.start()

    def start(self):
        host.service_start('zeppelin')

    def check_connect(self, addr, port):
        try:
            with socket.create_connection((addr, port), timeout=10):
                return True
        except OSError:
            return False

    def wait_for_api(self, timeout):
        start = time.time()
        while time.time() - start < timeout:
            if self.check_connect('localhost', self.dist_config.port('zeppelin')):
                return True
            time.sleep(2)
        raise utils.TimeoutError('Timed-out waiting for connection to Zeppelin')

    def stop(self):
        host.service_stop('zeppelin')

    def open_ports(self):
        for port in self.dist_config.exposed_ports('zeppelin'):
            hookenv.open_port(port)

    def close_ports(self):
        for port in self.dist_config.exposed_ports('zeppelin'):
            hookenv.close_port(port)

    def register_notebook(self, local_id, contents):
        api = ZeppelinAPI()
        kv = unitdata.kv()
        notebook_ids = kv.get('zeppelin.notebooks.ids', {})
        if local_id in notebook_ids:
            hookenv.log('Replacing notebook {} registered as {}'.format(
                local_id, notebook_ids[local_id]))
            api.delete_notebook(notebook_ids[local_id])
        zeppelin_id = api.import_notebook(contents)
        if zeppelin_id:
            notebook_ids[local_id] = zeppelin_id
            hookenv.log('Registered notebook {} as {}'.format(local_id,
                                                              zeppelin_id))
            return True
        else:
            hookenv.log('Unable to register notebook: {}'.format(local_id),
                        hookenv.ERROR)
            return False
        kv.set('zeppelin.notebooks.ids', notebook_ids)

    def remove_notebook(self, local_id):
        api = ZeppelinAPI()
        kv = unitdata.kv()
        notebook_ids = kv.get('zeppelin.notebooks.ids', {})
        if local_id in notebook_ids:
            api.delete_notebook(notebook_ids[local_id])
            del notebook_ids[local_id]
        else:
            hookenv.log('Notebook not registered: {}'.format(local_id),
                        hookenv.ERROR)
        kv.set('zeppelin.notebooks.ids', notebook_ids)

    def register_hadoop_notebooks(self):
        for notebook in ('hdfs-tutorial', 'flume-tutorial'):
            contents = (Path('resources') / notebook / 'note.json').text()
            self.register_notebook(notebook, contents)

    def remove_hadoop_notebooks(self):
        for notebook in ('hdfs-tutorial', 'flume-tutorial'):
            self.remove_notebook(notebook)

class ZeppelinAPI(object):
    """
    Helper for interacting with the Appache Zeppelin REST API.
    """
    def _url(self, *parts):
        dc = utils.DistConfig(
            data=layer.options('apache-bigtop-base'))
        url = 'http://localhost:{}/api/'.format(dc.port('zeppelin'))
        for part in parts:
            url = urljoin(url, part)
        return url

    def import_notebook(self, contents):
        response = requests.post(self._url('notebook'), data=contents)
        if response.status_code != 201:
            return None
        return response.json()['body']

    def delete_notebook(self, notebook_id):
        requests.delete(self._url('notebook/', notebook_id))

    def modify_interpreter(self, interpreter_name, properties):
        response = requests.get(self._url('interpreter/', 'setting'))
        try:
            body = response.json()['body']
        except json.JSONDecodeError:
            hookenv.log('Invalid response from API server: {} {}'.format(
                response, response.text), hookenv.ERROR)
            raise
        for interpreter_data in body:
            if interpreter_data['name'] == interpreter_name:
                break
        else:
            raise ValueError('Interpreter not found: {}'.format(
                interpreter_name))
        interpreter_data['properties'].update(properties)
        response = requests.put(self._url('interpreter/', 'setting/',
                                          interpreter_data['id']),
                                data=json.dumps(interpreter_data))
        if response.status_code != 200:
            raise ValueError('Unable to update interpreter: {}'.format(
                response.text))


text:
"""Test suite for 2to3's parser and grammar files.

This is the place to add tests for changes to 2to3's grammar, such as those
merging the grammars for Python 2 and 3. In addition to specific tests for
parts of the grammar we've changed, we also make sure we can parse the
test_grammar.py files from both Python 2 and Python 3.
"""

from __future__ import with_statement

# Testing imports
from . import support
from .support import driver, test_dir

# Python imports
import os
import sys

# Local imports
from lib2to3.pgen2 import tokenize
from ..pgen2.parse import ParseError

class GrammarTest(support.TestCase):
    def validate(self, code):
        support.parse_string(code)

    def invalid_syntax(self, code):
        try:
            self.validate(code)
        except ParseError:
            pass
        else:
            raise AssertionError("Syntax shouldn't have been valid")

class TestRaiseChanges(GrammarTest):
    def test_2x_style_1(self):
        self.validate("raise")

    def test_2x_style_2(self):
        self.validate("raise E, V")

    def test_2x_style_3(self):
        self.validate("raise E, V, T")

    def test_2x_style_invalid_1(self):
        self.invalid_syntax("raise E, V, T, Z")

    def test_3x_style(self):
        self.validate("raise E1 from E2")

    def test_3x_style_invalid_1(self):
        self.invalid_syntax("raise E, V from E1")

    def test_3x_style_invalid_2(self):
        self.invalid_syntax("raise E from E1, E2")

    def test_3x_style_invalid_3(self):
        self.invalid_syntax("raise from E1, E2")

    def test_3x_style_invalid_4(self):
        self.invalid_syntax("raise E from")

# Adapated from Python 3's Lib/test/test_grammar.py:GrammarTests.testFuncdef
class TestFunctionAnnotations(GrammarTest):
    def test_1(self):
        self.validate("""def f(x) -> list: pass""")

    def test_2(self):
        self.validate("""def f(x:int): pass""")

    def test_3(self):
        self.validate("""def f(*x:str): pass""")

    def test_4(self):
        self.validate("""def f(**x:float): pass""")

    def test_5(self):
        self.validate("""def f(x, y:1+2): pass""")

    def test_6(self):
        self.validate("""def f(a, (b:1, c:2, d)): pass""")

    def test_7(self):
        self.validate("""def f(a, (b:1, c:2, d), e:3=4, f=5, *g:6): pass""")

    def test_8(self):
        s = """def f(a, (b:1, c:2, d), e:3=4, f=5,
                        *g:6, h:7, i=8, j:9=10, **k:11) -> 12: pass"""
        self.validate(s)

class TestExcept(GrammarTest):
    def test_new(self):
        s = """
            try:
                x
            except E as N:
                y"""
        self.validate(s)

    def test_old(self):
        s = """
            try:
                x
            except E, N:
                y"""
        self.validate(s)

# Adapted from Python 3's Lib/test/test_grammar.py:GrammarTests.testAtoms
class TestSetLiteral(GrammarTest):
    def test_1(self):
        self.validate("""x = {'one'}""")

    def test_2(self):
        self.validate("""x = {'one', 1,}""")

    def test_3(self):
        self.validate("""x = {'one', 'two', 'three'}""")

    def test_4(self):
        self.validate("""x = {2, 3, 4,}""")

class TestNumericLiterals(GrammarTest):
    def test_new_octal_notation(self):
        self.validate("""0o7777777777777""")
        self.invalid_syntax("""0o7324528887""")

    def test_new_binary_notation(self):
        self.validate("""0b101010""")
        self.invalid_syntax("""0b0101021""")

class TestClassDef(GrammarTest):
    def test_new_syntax(self):
        self.validate("class B(t=7): pass")
        self.validate("class B(t, *args): pass")
        self.validate("class B(t, **kwargs): pass")
        self.validate("class B(t, *args, **kwargs): pass")
        self.validate("class B(t, y=9, *args, **kwargs): pass")

class TestParserIdempotency(support.TestCase):

    """A cut-down version of pytree_idempotency.py."""

    def test_all_project_files(self):
        if sys.platform.startswith("win"):
            # XXX something with newlines goes wrong on Windows.
            return
        for filepath in support.all_project_files():
            with open(filepath, "rb") as fp:
                encoding = tokenize.detect_encoding(fp.readline)[0]
            self.assertTrue(encoding is not None,
                            "can't detect encoding for %s" % filepath)
            with open(filepath, "r") as fp:
                source = fp.read()
                source = source.decode(encoding)
            tree = driver.parse_string(source)
            new = unicode(tree)
            if diff(filepath, new, encoding):
                self.fail("Idempotency failed: %s" % filepath)

    def test_extended_unpacking(self):
        driver.parse_string("a, *b, c = x\n")
        driver.parse_string("[*a, b] = x\n")
        driver.parse_string("(z, *y, w) = m\n")
        driver.parse_string("for *z, m in d: pass\n")

class TestLiterals(GrammarTest):

    def validate(self, s):
        driver.parse_string(support.dedent(s) + "\n\n")

    def test_multiline_bytes_literals(self):
        s = """
            md5test(b"\xaa" * 80,
                    (b"Test Using Larger Than Block-Size Key "
                     b"and Larger Than One Block-Size Data"),
                    "6f630fad67cda0ee1fb1f562db3aa53e")
            """
        self.validate(s)

    def test_multiline_bytes_tripquote_literals(self):
        s = '''
            b"""
            <?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN">
            """
            '''
        self.validate(s)

    def test_multiline_str_literals(self):
        s = """
            md5test("\xaa" * 80,
                    ("Test Using Larger Than Block-Size Key "
                     "and Larger Than One Block-Size Data"),
                    "6f630fad67cda0ee1fb1f562db3aa53e")
            """
        self.validate(s)

def diff(fn, result, encoding):
    f = open("@", "w")
    try:
        f.write(result.encode(encoding))
    finally:
        f.close()
    try:
        fn = fn.replace('"', '\\"')
        return os.system('diff -u "%s" @' % fn)
    finally:
        os.remove("@")


text:
title: Skrifstofa-365-Ítarefni-Dýravernd
inshort: Óskilgreint
translator: Microsoft Cognitive Services
---


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>Qt 4.8: QAudioInput Class Reference</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />

      Home

    Qt Reference Documentation

Qt HOME

DEV

          DOC

BLOG

Qt 4.8

ALL VERSIONS

API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

Examples

Examples

Tutorials

Demos

QML Examples

          Search index:

          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />

 Close

All | API | Articles | Examples

 results:

            </fieldset>
          </form>

            API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

            Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

            Examples

Examples

Tutorials

Demos

QML Examples

Home

Modules

QtMultimedia

QAudioInput

A

A

A

                Print

Contents

Public Functions

Signals

Detailed Description

Symbian Platform Security Requirements

QAudioInput Class Reference

The QAudioInput class provides an interface for receiving audio data from an audio input device. More...

 #include <QAudioInput>

Inherits: QObject.

This class was introduced in Qt 4.6.

List of all members, including inherited members

Public Functions

 	QAudioInput ( const QAudioFormat & format = QAudioFormat(), QObject * parent = 0 )

 	QAudioInput ( const QAudioDeviceInfo & audioDevice, const QAudioFormat & format = QAudioFormat(), QObject * parent = 0 )

 	~QAudioInput ()

 int 	bufferSize () const

 int 	bytesReady () const

 qint64 	elapsedUSecs () const

 QAudio::Error 	error () const

 QAudioFormat 	format () const

 int 	notifyInterval () const

 int 	periodSize () const

 qint64 	processedUSecs () const

 void 	reset ()

 void 	resume ()

 void 	setBufferSize ( int value )

 void 	setNotifyInterval ( int ms )

 void 	start ( QIODevice * device )

 QIODevice * 	start ()

 QAudio::State 	state () const

 void 	stop ()

 void 	suspend ()

29 public functions inherited from QObject

Signals

 void 	notify ()

 void 	stateChanged ( QAudio::State state )

1 signal inherited from QObject

Additional Inherited Members

1 property inherited from QObject

1 public slot inherited from QObject

7 static public members inherited from QObject

8 protected functions inherited from QObject

Detailed Description

The QAudioInput class provides an interface for receiving audio data from an audio input device.

You can construct an audio input with the system's default audio input device. It is also possible to create QAudioInput with a specific QAudioDeviceInfo. When you create the audio input, you should also send in the QAudioFormat to be used for the recording (see the QAudioFormat class description for details).

To record to a file:

QAudioInput lets you record audio with an audio input device. The default constructor of this class will use the systems default audio device, but you can also specify a QAudioDeviceInfo for a specific device. You also need to pass in the QAudioFormat in which you wish to record.

Starting up the QAudioInput is simply a matter of calling start() with a QIODevice opened for writing. For instance, to record to a file, you can:

     QFile outputFile;         // class member.
     QAudioInput *audioInput;  // class member.
     ...
     void startRecording()
     {
         outputFile.setFileName("/tmp/test.raw");
         outputFile.open( QIODevice::WriteOnly | QIODevice::Truncate );

         QAudioFormat format;
         // set up the format you want, eg.
         format.setFrequency(8000);
         format.setChannels(1);
         format.setSampleSize(8);
         format.setCodec("audio/pcm");
         format.setByteOrder(QAudioFormat::LittleEndian);
         format.setSampleType(QAudioFormat::UnSignedInt);

         QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
         if (!info.isFormatSupported(format)) {
             qWarning()<<"default format not supported try to use nearest";
             format = info.nearestFormat(format);
         }

         audioInput = new QAudioInput(format, this);
         QTimer::singleShot(3000, this, SLOT(stopRecording()));
         audioInput->start(&outputFile);
         // Records audio for 3000ms
     }

This will start recording if the format specified is supported by the input device (you can check this with QAudioDeviceInfo::isFormatSupported(). In case there are any snags, use the error() function to check what went wrong. We stop recording in the <tt>stopRecording()</tt> slot.

     void stopRecording()
     {
         audioInput->stop();
         outputFile.close();
         delete audioInput;
     }

At any point in time, QAudioInput will be in one of four states: active, suspended, stopped, or idle. These states are specified by the QAudio::State enum. You can request a state change directly through suspend(), resume(), stop(), reset(), and start(). The current state is reported by state(). QAudioOutput will also signal you when the state changes (stateChanged()).

QAudioInput provides several ways of measuring the time that has passed since the start() of the recording. The <tt>processedUSecs()</tt> function returns the length of the stream in microseconds written, i.e., it leaves out the times the audio input was suspended or idle. The elapsedUSecs() function returns the time elapsed since start() was called regardless of which states the QAudioInput has been in.

If an error should occur, you can fetch its reason with error(). The possible error reasons are described by the QAudio::Error enum. The QAudioInput will enter the StoppedState when an error is encountered. Connect to the stateChanged() signal to handle the error:

     void stateChanged(QAudio::State newState)
     {
         switch(newState) {
             case QAudio::StoppedState:
             if (audioInput->error() != QAudio::NoError) {
                  // Perform error handling
             } else {

             }
             break;

Symbian Platform Security Requirements

On Symbian, processes which use this class must have the <tt>UserEnvironment</tt> platform security capability. If the client process lacks this capability, calls to either overload of start() will fail. This failure is indicated by the QAudioInput object setting its error() value to QAudio::OpenError and then emitting a stateChanged(QAudio::StoppedState) signal.

Platform security capabilities are added via the TARGET.CAPABILITY qmake variable.

See also QAudioOutput and QAudioDeviceInfo.

Member Function Documentation

QAudioInput::QAudioInput ( const QAudioFormat & format = QAudioFormat(), QObject * parent = 0 )

Construct a new audio input and attach it to parent. The default audio input device is used with the output format parameters.

QAudioInput::QAudioInput ( const QAudioDeviceInfo & audioDevice, const QAudioFormat & format = QAudioFormat(), QObject * parent = 0 )

Construct a new audio input and attach it to parent. The device referenced by audioDevice is used with the input format parameters.

QAudioInput::~QAudioInput ()

Destroy this audio input.

int QAudioInput::bufferSize () const

Returns the audio buffer size in milliseconds.

If called before start(), returns platform default value. If called before start() but setBufferSize() was called prior, returns value set by setBufferSize(). If called after start(), returns the actual buffer size being used. This may not be what was set previously by setBufferSize().

See also setBufferSize().

int QAudioInput::bytesReady () const

Returns the amount of audio data available to read in bytes.

NOTE: returned value is only valid while in QAudio::ActiveState or QAudio::IdleState state, otherwise returns zero.

qint64 QAudioInput::elapsedUSecs () const

Returns the microseconds since start() was called, including time in Idle and Suspend states.

QAudio::Error QAudioInput::error () const

Returns the error state.

QAudioFormat QAudioInput::format () const

Returns the QAudioFormat being used.

void QAudioInput::notify ()<tt> [signal]</tt>

This signal is emitted when x ms of audio data has been processed the interval set by setNotifyInterval(x).

int QAudioInput::notifyInterval () const

Returns the notify interval in milliseconds.

See also setNotifyInterval().

int QAudioInput::periodSize () const

Returns the period size in bytes.

Note: This is the recommended read size in bytes.

qint64 QAudioInput::processedUSecs () const

Returns the amount of audio data processed since start() was called in microseconds.

void QAudioInput::reset ()

Drops all audio data in the buffers, resets buffers to zero.

void QAudioInput::resume ()

Resumes processing audio data after a suspend().

Sets error() to QAudio::NoError. Sets state() to QAudio::ActiveState if you previously called start(QIODevice*). Sets state() to QAudio::IdleState if you previously called start(). emits stateChanged() signal.

void QAudioInput::setBufferSize ( int value )

Sets the audio buffer size to value milliseconds.

Note: This function can be called anytime before start(), calls to this are ignored after start(). It should not be assumed that the buffer size set is the actual buffer size used, calling bufferSize() anytime after start() will return the actual buffer size being used.

See also bufferSize().

void QAudioInput::setNotifyInterval ( int ms )

Sets the interval for notify() signal to be emitted. This is based on the ms of audio data processed not on actual real-time. The minimum resolution of the timer is platform specific and values should be checked with notifyInterval() to confirm actual value being used.

See also notifyInterval().

void QAudioInput::start ( QIODevice * device )

Uses the device as the QIODevice to transfer data. Passing a QIODevice allows the data to be transferred without any extra code. All that is required is to open the QIODevice. QAudioInput does not take ownership of device.

The QAudioInput will write to the device when new data is available. You can subclass QIODevice and reimplement writeData() if you wish to access the data. If you simply want to save data to a file, you can pass a QFile to this function.

If able to successfully get audio data from the systems audio device the state() is set to either QAudio::ActiveState or QAudio::IdleState, error() is set to QAudio::NoError and the stateChanged() signal is emitted.

If a problem occurs during this process the error() is set to QAudio::OpenError, state() is set to QAudio::StoppedState and stateChanged() signal is emitted.

QAudioInput#Symbian Platform Security Requirements

See also QIODevice.

QIODevice * QAudioInput::start ()

Returns a pointer to a new QIODevice that will be used to handle the data transfer. This QIODevice can be used to read() audio data directly. You will typically connect to the readyRead() signal, and read from the device in the slot you connect to. QAudioInput keeps ownership of the device.

If able to access the systems audio device the state() is set to QAudio::IdleState, error() is set to QAudio::NoError and the stateChanged() signal is emitted.

If a problem occurs during this process the error() is set to QAudio::OpenError, state() is set to QAudio::StoppedState and stateChanged() signal is emitted.

QAudioInput#Symbian Platform Security Requirements

See also QIODevice.

QAudio::State QAudioInput::state () const

Returns the state of audio processing.

void QAudioInput::stateChanged ( QAudio::State state )<tt> [signal]</tt>

This signal is emitted when the device state has changed.

void QAudioInput::stop ()

Stops the audio input, detaching from the system resource.

Sets error() to QAudio::NoError, state() to QAudio::StoppedState and emit stateChanged() signal.

void QAudioInput::suspend ()

Stops processing audio data, preserving buffered audio data.

Sets error() to QAudio::NoError, state() to QAudio::SuspendedState and emit stateChanged() signal.

      <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.

      The documentation provided herein is licensed under the terms of the
      GNU Free Documentation
      License version 1.3 as published by the Free Software Foundation.

      Documentation sources may be obtained from
      www.qt-project.org.

      Digia, Qt and their respective logos are trademarks of Digia Plc
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. Privacy Policy


text:
{template 'common/header'}

	菜单管理

			+新建菜单

排序

菜单

开关

操作

				{loop $system_menu $permission_name $menu}
				{if $menu['title']!=''}

								<input type="text" class="form-control" value="{php echo intval($menu['displayorder'])}">

{$menu['title']}

								{if empty($menu['is_system'])}
								删除
								{/if}
								编辑

						{loop $menu['section'] $section_name $section}

										<input type="text" class="form-control" value="{php echo intval($section['displayorder'])}">

{$section['title']}

										{if $section_name != 'platform_module'}
										+添加子菜单
										{/if}

								{loop $section['menu'] $sub_permission_name $sub_menu}
								{if $sub_permission_name == 'wxapp_platform_material'}
									{php continue;}
								{/if}

												<input type="text" class="form-control" value="{php echo intval($sub_menu['displayorder'])}">

{$sub_menu['title']}

											{if $sub_permission_name == 'system_setting_menu'}
											不可关闭
											{else}

											{/if}

												编辑
												{if empty($sub_menu['is_system'])}删除{/if}

								{/loop}

						{/loop}

				{/if}
				{/loop}

					<button type="button" class="close" data-dismiss="modal">×Close</button>

编辑菜单

				<form action="" method="post" enctype="multipart/form-data" class="we7-form form" >

							菜单排序

								<input type="text"  min="0" ng-model="mainMenu.displayorder" class="form-control">
								注:生序排列。数字越小,排名越靠前

						<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
						<button type="button" class="btn btn-primary" name="submit" value="保存" ng-click="saveorder()">保存</button>

				</form>

					<button type="button" class="close" data-dismiss="modal">×Close</button>

编辑菜单

				<form action="" method="post" enctype="multipart/form-data" class="we7-form form" >

							菜单排序

								<input type="text" name="displayorder" ng-model="activeItem.displayorder" class="form-control">

							菜单名称

								<input type="text" name="title" ng-model="activeItem.title" class="form-control">

							 菜单标识

								<input type="text" name="permission_name" ng-readonly="activeItem.isSystem == '1'" ng-model="activeItem.permissionName" class="form-control">

							 菜单链接

								<input type="text" name="url" ng-readonly="activeItem.isSystem == '1'" ng-model="activeItem.url" class="form-control">
								注:支持相对链接。非相对链接请填写以http或https开头的完整链接

							 菜单图标

									<input type="text" name="icon" value="" ng-model="activeItem.icon" class="form-control">

									  选择图标

						<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
						<button type="button" class="btn btn-primary" name="submit" value="保存" ng-click="editItem()">保存</button>

				</form>

{template 'common/footer'}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<title>AspectJ 5 Development Kit v1.5.4 Readme</title>

© Copyright 2006 Contributors.
All rights reserved.

AspectJ 5 v1.5.4 Readme

This release includes a number of bug fixes and enhancements.  The full list of resolved issues can be found with
<a href="https://bugs.eclipse.org/bugs/buglist.cgi?query_format=advanced&short_desc_type=allwordssubstr&short_desc=&product=AspectJ&target_milestone=1.5.4&long_desc_type=allwordssubstr&long_desc=&bug_file_loc_type=allwordssubstr&bug_file_loc=&status_whiteboard_type=allwordssubstr&status_whiteboard=&keywords_type=allwords&keywords=&bug_status=RESOLVED&bug_status=VERIFIED&bug_status=CLOSED&emailtype1=substring&email1=&emailtype2=substring&email2=&bugidtype=include&bug_id=&votes=&chfieldfrom=&chfieldto=Now&chfieldvalue=&cmdtype=doit&order=Reuse+same+sort+as+last+time&field0-0-0=noop&type0-0-0=noop&value0-0-0=">
this bugzilla query.

Some key fixes include better handling of generic type declarations, both in regular Java classes and in combination with AspectJ constructs (for example, inter-type declarations)


text:
Tema 6
======

Ejercicio 1
-----------

**Instalar los paquetes necesarios para usar KVM. Se pueden seguir estas instrucciones. Ya lo hicimos en el primer tema, pero volver a comprobar si nuestro sistema está preparado para ejecutarlo o hay que conformarse con la paravirtualización.**

Para ver si funciona, podemos ver las maquinas que tenemos instalas con el siguiente comando:
```bash
virsh list --all
```
![t6ej1.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej1.png)

Vemos que no tenemos ninguna maquina instalada.

Ejercicio 2
-----------

**1. Crear varias máquinas virtuales con algún sistema operativo libre tal como Linux o BSD. Si se quieren distribuciones que ocupen poco espacio con el objetivo principalmente de hacer pruebas se puede usar CoreOS (que sirve como soporte para Docker) GALPon Minino, hecha en Galicia para el mundo, Damn Small Linux, SliTaz (que cabe en 35 megas) y ttylinux (basado en línea de órdenes solo).**

Vamos a instalar una maquina con ttylinux:

Nos descargamos el archivo iso de la pagina oficial. Despues, tenemos que crear un disco virtual con el siguiente comando:
```bash
qemu-img create -f qcow2 imagen1.qcow2 2000M
```

Iniciamos el disco con la imagen slitaz para instalarla:
```bash
qemu-system-x86_64 -hda imagen1.qcow2 -cdrom ttylinux-pc_i686-2015.01.iso
```
![t6ej2.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej2.png)

Ahora, vamos a instalar otra maquina con slitaz:

Nos descargamos el archivo iso de la pagina oficial. Despues, tenemos que crear un disco virtual con el siguiente comando:
```bash
qemu-img create -f qcow2 imagen2.qcow2 2000M
```

Iniciamos el disco con la imagen slitaz para instalarla:
```bash
qemu-system-x86_64 -hda imagen2.qcow2 -cdrom slitaz-4.0.iso
```
![t6ej2b.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej2b.png)

**2. Hacer un ejercicio equivalente usando otro hipervisor como Xen, VirtualBox o Parallels.**

Para este ejercicio, se va a instalar ttylinux en una maquina virtual usando VirtualBox.
Para ello, necesitamos crear una maquina nueva.
![t6ej2c.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej2c.png)

Completamos la configuracion de la maquina como la memoria, etc.

Despues, una vez instalada, iniciamos la maquina y le indicamos la imagen con la que se va a arrancar, que se trata de la imagen de ttylinux que nos hemos descargado antes.
Mostramos en la imagen siguiente, la maquina ejecutandose con ttylinux.
![t6ej2d.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej2d.png)

Ejercicio 3
-----------

**Crear un benchmark de velocidad de entrada salida y comprobar la diferencia entre usar paravirtualización y arrancar la máquina virtual simplemente con ``qemu-system-x86_64 -hda /media/Backup/Isos/discovirtual.img``**

- Paravirtualizacion: ``qemu-system-x86_64 -boot order=c -drive file=img-cow.qcow2,if=virtio``

|Medición    | Tiempo     |
| ---------- | ---------- |
| 1          | 8.257      |
| 2          | 8.254      |
| 3          | 8.220      |
| 4          | 8.283      |

- Usando ``qemu-system-x86_64 -hda img-cow.qcow2``

|Medición    | Tiempo     |
| ---------- | ---------- |
| 1          | 8.294      |
| 2          | 8.148      |
| 3          | 8.090      |
| 4          | 8.223      |

Como podemos ver en las tablas anteriores, es ligeramente mas rapido usando directamente ``qemu-system-x86_64 -hda /media/Backup/Isos/discovirtual.img``

Ejercicio 4
-----------

**Crear una máquina virtual Linux con 512 megas de RAM y entorno gráfico LXDE a la que se pueda acceder mediante VNC y ssh.**

Para empezar, hay que crear la imagen:
```bash
qemu-img create -f qcow2 debian.img 15G
```
Despues, la ejecutamos:
```bash
qemu-system-x86_64 -hda debian.img -cdrom debian-7.7.0-amd64-netinst.iso -m 512M
```
Instalamos lxde siguiendo estas indicaciones:

- Entramos en opciones avanzadas.
![t6ej4.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej4.png)

- Accedemos a "Alternative desktop environments"
![t6ej4b.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej4b.png)

- Elegimos LXDE.
![t6ej4c.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej4c.png)

Una vez instalado, ya tenemos el escritorio LXDE.

Ahora, salidmos de la maquina y la iniciamos de nuevo:
```bash
qemu-system-x86_64 -boot order=c -drive file=debian.img,if=virtio -m 512M -name debian -vnc :1
```

En una terminal aparte, ejecutaremos ``ifconfig``, vemos la direccion ip de la interfaz a la que nos vamos a conectar y nos conectaremos con el comando:
```bash
vinagre [direccion]:[puerto]
```

Despues, iniciamos la maquina de nuevo con el siguiente comando, para indicarle el puerto por el que vamos a acceder a la maquina:
```bash
qemu-system-x86_64 -boot order=c -drive file=debian.img,if=virtio -m 512M -name debian -redir tcp:[puerto]::22
```

Despues, instalamos en la maquina ssh para poder acceder:
```bash
sudo apt-get install ssh
```

Para acceder a la maquina, desde la anfitriona, ejecutamos el comando:
```bash
ssh alberto@localhost -p [puerto]
```

Ejercicio 5
-----------

**Crear una máquina virtual ubuntu e instalar en ella un servidor nginx para poder acceder mediante web.**

Ya tengo una maquina virtual ubuntu instalada.
Iniciamos la maquina e instalamos nginx con el comando:
```bash
sudo apt-get install nginx
```

Despues, iniciamos el servicio ejecutando:
```bash
sudo service nginx start
```

Ahora, miramos la direccion ip de la maquina virtual para ponerla en la barra de direcciones del navegador y nos aparecerá la pantalla de inicio de nginx.
![t6ej5.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej5.png)
```

Ejercicio 7
-----------

**Instalar una máquina virtual con Linux Mint para el hipervisor que tengas instalado.**

Para la instalacion de una maquina con linux Mint, se va a usar VirtualBox.
Lo primero que hay que hacer, es descargarnos de su pagina oficial un archivo iso con la imagen de linux mint.

Lo siguiente, es crear una maquina virtual nueva y rellenar algunos datos.
![t6ej7.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej7.png)

Despues, hay que indicarle que cree un disco virtual para ello, como se indica en la siguiente imagen.
![t6ej7b.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej7b.png)

Una vez terminada la creacion, iniciamos la maquina y le indicamos el fichero iso con la imagen que va a cargar para iniciarse.
![t6ej7c.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej7c.png)

Cuando termine de iniciarse, tendremos una maquina con linux Mint lista para usarse, como vemos en la siguiente imagen.
![t6ej7d.png](https://raw.githubusercontent.com/albertomoreno/iv-images/master/t6ej7d.png)


text:
'use strict';

let path = require('path');
let webpack = require('webpack');
let baseConfig = require('./base');
let defaultSettings = require('./defaults');

let config = Object.assign({}, baseConfig, {
  entry: [
    './src/index'
  ],
  cache: true,
  devtool: 'eval-source-map',
  plugins: [
    new webpack.NoErrorsPlugin()
  ],
  module: defaultSettings.getDefaultModules()
});

// Add needed loaders to the defaults here
config.module.loaders.push({
  test: /\.(js|jsx)$/,
  loader: 'babel',
  include: [].concat(
    config.additionalPaths,
    [path.join(__dirname, '/../src')]
  )
});

module.exports = config;


text:
"use strict";

module.exports = function(sequelize, DataTypes) {
    var Comment = sequelize.define("Comment", {
        name: DataTypes.STRING,
        email: {
            type: DataTypes.STRING,
            validate: {
                isEmail: true
            }
        },
        data: DataTypes.STRING,
        type: DataTypes.STRING,
    }, {
        classMethods: {
            associate: function(models) {
                Comment.belongsTo(models.Place, {
                    onDelete: "CASCADE",
                    foreignKey: {
                        allowNull: false
                    }
                })/*,
                Comment.belongsTo(models.User, {
                    onDelete: "CASCADE",
                    foreignKey: {
                        allowNull: false
                    }
                })*/
            }
        }
    });

    return Comment;
};


text:
require "requirement"

class LanguageModuleRequirement < Requirement
  fatal true

  def initialize(language, module_name, import_name = nil)
    @language = language
    @module_name = module_name
    @import_name = import_name || module_name
    super([language, module_name, import_name])
  end

  satisfy(build_env: false) { quiet_system(*the_test) }

  def message
    s = <<-EOS.undent
      Unsatisfied dependency: #{@module_name}
      Homebrew does not provide special #{@language.to_s.capitalize} dependencies; install with:
        `#{command_line} #{@module_name}`
    EOS

    unless [:python, :perl, :ruby].include? @language
      s += <<-EOS.undent

      You may need to: `brew install #{@language}`

      EOS
    end

    s
  end

  def the_test
    case @language
    when :lua
      ["/usr/bin/env", "luarocks-5.2", "show", @import_name.to_s]
    when :lua51
      ["/usr/bin/env", "luarocks-5.1", "show", @import_name.to_s]
    when :perl
      ["/usr/bin/env", "perl", "-e", "use #{@import_name}"]
    when :python
      ["/usr/bin/env", "python", "-c", "import #{@import_name}"]
    when :python3
      ["/usr/bin/env", "python3", "-c", "import #{@import_name}"]
    when :ruby
      ["/usr/bin/env", "ruby", "-rubygems", "-e", "require '#{@import_name}'"]
    end
  end

  def command_line
    case @language
    when :lua     then "luarocks-5.2 install"
    when :lua51   then "luarocks-5.1 install"
    when :perl    then "cpan -i"
    when :python  then "pip install"
    when :python3 then "pip3 install"
    when :ruby    then "gem install"
    end
  end

  def display_s
    "#{@module_name} (#{@language} module)"
  end
end


text:
print(hash(False))
print(hash(True))
print({():1}) # hash tuple
print({1 << 66:1}) # hash big int
print(hash in {hash:1}) # hash function

try:
    hash([])
except TypeError:
    print("TypeError")

class A:
    def __hash__(self):
        return 123
    def __repr__(self):
        return "a instance"

print(hash(A()))
print({A():1})

# all user-classes have default __hash__
class B:
    pass
hash(B())

# if __eq__ is defined then default __hash__ is not used
class C:
    def __eq__(self, another):
        return True
try:
    hash(C())
except TypeError:
    print("TypeError")

# __hash__ must return an int
class D:
    def __hash__(self):
        return None
try:
    hash(D())
except TypeError:
    print("TypeError")

# __hash__ returning a bool should be converted to an int
class E:
    def __hash__(self):
        return True
print(hash(E()))

# __hash__ returning a large number should be truncated
class F:
    def __hash__(self):
        return 1 << 70 | 1
print(hash(F()) != 0)