text:
/*global describe, it, before */
var assert = require('power-assert'),
    async  = require('async'),
    _      = require('underscore'),
    fs     = require('fs'),
    sf     = require('../lib/salesforce'),
    config = require('./config/salesforce');

/**
 *
 */
describe("metadata", function() {

  this.timeout(40000); // set timeout to 40 sec.

  var conn = new sf.Connection({ logLevel : config.logLevel });

  /**
   *
   */
  before(function(done) {
    conn.login(config.username, config.password, function(err) {
      if (err) { return done(err); }
      if (!conn.accessToken) { done(new Error("No access token. Invalid login.")); }
      done();
    });
  });

  /**
   *
   */
  describe("create metadata", function() {
    var asyncResults;

    it("should create custom objects", function(done) {
      var metadata = [{
        fullName: 'TestObject1__c',
        label: 'Test Object 1',
        pluralLabel: 'Test Object 1',
        nameField: {
          type: 'Text',
          label: 'Test Object Name'
        },
        deploymentStatus: 'Deployed',
        sharingModel: 'ReadWrite'
      }, {
        fullName: 'TestObject2__c',
        label: 'Test Object 2',
        pluralLabel: 'Test Object 2',
        nameField: {
          type: 'AutoNumber',
          label: 'Test Object #'
        },
        deploymentStatus: 'InDevelopment',
        sharingModel: 'Private'
      }];
      conn.metadata.create('CustomObject', metadata, function(err, results) {
        if (err) { throw err; }
        assert.ok(_.isArray(results));
        assert.ok(results.length === metadata.length);
        _.forEach(results, function(result) {
          assert.ok(_.isString(result.id));
        });
        asyncResults = results;
      }.check(done));
    });

    it("should get finished status in completion", function(done) {
      var ids = _.map(asyncResults, function(ar){ return ar.id; });
      conn.metadata.checkStatus(ids).complete(function(err, results) {
        if (err) { throw err; }
        assert.ok(_.isArray(results));
        assert.ok(results.length === ids.length);
        _.forEach(results, function(result) {
          assert.ok(result.done === true);
          assert.ok(result.state === 'Completed');
        });
      }.check(done));
    });

    it("should create custom fields", function(done) {
      var metadata = [{
        type: 'Text',
        fullName: 'TestObject1__c.TextField__c',
        label: 'Text #1',
        length: 50
      }, {
        type: 'TextArea',
        fullName: 'TestObject1__c.TextAreaField__c',
        label: 'Text Area #1'
      }, {
        type: 'Number',
        fullName: 'TestObject1__c.NumberField__c',
        label: 'Number #1',
        precision: 18,
        scale: 2
      }, {
        type: 'AutoNumber',
        fullName: 'TestObject1__c.AutoNumberField__c',
        label: 'Auto Number #1'
      }];
      conn.metadata.create('CustomField', metadata).complete(function(err, results) {
        if (err) { throw err; }
        assert.ok(_.isArray(results));
        assert.ok(results.length === metadata.length);
        _.forEach(results, function(result) {
          assert.ok(_.isString(result.id));
          assert.ok(result.done === true);
          assert.ok(result.state === "Completed");
        });
      }.check(done));
    });

  });

  /**
   *
   */
  describe("update metadata", function() {
    it("should update custom fields", function(done) {
      var updateMetadata = [{
        currentName: 'TestObject1__c.AutoNumberField__c',
        metadata: {
          type: 'Text',
          fullName: 'TestObject2__c.AutoNumberField2__c',
          label: 'Auto Number #2',
          length: 50
        }
      }];
      conn.metadata.update('CustomField', updateMetadata).complete(function(err, results) {
        if (err) { throw err; }
        assert.ok(_.isArray(results));
        assert.ok(results.length === updateMetadata.length);
        _.forEach(results, function(result) {
          assert.ok(_.isString(result.id));
          assert.ok(result.done === true);
          assert.ok(result.state === "Completed");
        });
      }.check(done));
    });
  });

  /**
   *
   */
  describe("delete metadata", function() {
    it("should delete custom objects", function(done) {
      var metadata = [{
        fullName: 'TestObject1__c',
      }, {
        fullName: 'TestObject2__c',
      }];
      conn.metadata.delete('CustomObject', metadata).complete(function(err, results) {
        if (err) { throw err; }
        assert.ok(_.isArray(results));
        assert.ok(results.length === metadata.length);
        _.forEach(results, function(result) {
          assert.ok(_.isString(result.id));
        });
      }.check(done));
    });
  });

  /**
   *
   */
  describe("deploy metadata in packaged file", function() {
    it("should deploy package", function(done) {
      var zipStream = fs.createReadStream(__dirname + "/data/MyPackage.zip");
      conn.metadata.deploy(zipStream, { runTests: [ 'MyApexTriggerTest' ] }).complete(function(err, result) {
        if (err) { throw err; }
        assert.ok(result.done === true);
        assert.ok(result.success === true);
        assert.ok(result.status === 'Succeeded');
        assert.ok(result.numberComponentErrors === 0);
        assert.ok(result.numberComponentsDeployed === result.numberComponentsTotal);
        assert.ok(result.numberTestsCompleted === 1);
      }.check(done));
    });
  });

  /**
   *
   */
  describe("retrieve metadata in packaged file", function() {
    it("should retrieve package", function(done) {
      var bufs = [];
      conn.metadata.retrieve({ packageNames: [ 'My Test Package' ] })
                   .stream()
                   .on('data', function(d) {
                     bufs.push(d);
                   })
                   .on('end', function() {
                     assert.ok(bufs.length > 0);
                     done();
                   })
                   .on('error', function(err) {
                     done(err);
                   });
    });
  });

});


text:
package org.wso2.carbon.attachment.mgt.core.dao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.attachment.mgt.configuration.AttachmentServerConfiguration;
import org.wso2.carbon.attachment.mgt.core.dao.impl.jpa.Constants;
import org.wso2.carbon.attachment.mgt.server.internal.AttachmentServerHolder;
import org.wso2.carbon.attachment.mgt.util.ConfigurationUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * Abstract implementation of the DAOManager {@link DAOManager}
 */
public abstract class AbstractDAOManager implements DAOManager {
    /**
     * Class Logger
     */
    private static final Log log = LogFactory.getLog(AbstractDAOManager.class);

    /**
     * DAO Manager maintains a DAOConnectionFactory ({@link AttachmentMgtDAOConnectionFactory}
     * where the connections to the JPA based api is managed)
     */
    protected AttachmentMgtDAOConnectionFactory daoConnectionFactory;

    /**
     * DAO Manager maintains a DAOTransformerFactory {@link AttachmentMgtDAOTransformerFactory}
     * where the DAO to API transformations are maintained
     */
    protected AttachmentMgtDAOTransformerFactory daoTransformerFactory;

    /**
     * Maintains the server configurations, which will be reused to configure the DAO Manager
     */
    protected AttachmentServerConfiguration serverConfiguration;

    /**
     * Returns the AttachmentMgtDAOConnectionFactory reference
     *
     * @return
     */
    @Override
    public AttachmentMgtDAOConnectionFactory getDAOConnectionFactory() {
        if (this.daoConnectionFactory != null) {
            return this.daoConnectionFactory;
        } else {
            log.error("DAO Connection Factory is not initialized.");
            throw new NullPointerException("DAO Connection Factory is not initialized.");
        }
    }

    /**
     * Returns the AttachmentMgtDAOTransformerFactory reference
     *
     * @return
     */
    @Override
    public AttachmentMgtDAOTransformerFactory getDAOTransformerFactory() {
        if (this.daoTransformerFactory != null) {
            return this.daoTransformerFactory;
        } else {
            log.error("DAO Transformer Factory is not initialized.");
            throw new NullPointerException("DAO Transformer Factory is not initialized.");
        }
    }

    @Override
    public void init(AttachmentServerConfiguration serverConfig) {
        serverConfiguration = serverConfig;
        initDAOConnectionFactory(serverConfig.getDaoConnectionFactoryClass());
        initDAOTransformerFactory(serverConfig.getDaoTransformerFactoryClass());
    }

    private void initDAOTransformerFactory(String daoTransformerFactoryClassName) {
        try {
            Class daoTransformerFactoryClass = this.getClass().getClassLoader().loadClass
                    (daoTransformerFactoryClassName);
            Object daoTransformerFactory = daoTransformerFactoryClass.newInstance();

            this.daoTransformerFactory = (AttachmentMgtDAOTransformerFactory) daoTransformerFactory;
        } catch (Exception e) {
            log.error("DAO Transformer Factory creation failed. Reason:" + e.getLocalizedMessage(),
                      e);
        }

    }

    private void initDAOConnectionFactory(String daoConnectionFactoryClassName) {
        try {
            Class daoConnectionFactoryClass = this.getClass().getClassLoader().loadClass(daoConnectionFactoryClassName);
            Object daoConnectionFactory = daoConnectionFactoryClass.newInstance();

            this.daoConnectionFactory = (AttachmentMgtDAOConnectionFactory)
                    daoConnectionFactory;

            this.daoConnectionFactory.setDataSource(AttachmentServerHolder.getInstance()
                                                            .getAttachmentServer()
                                                            .getDataSourceManager().getDataSource());

            this.daoConnectionFactory.setDAOConnectionFactoryProperties(getGenericDAOFactoryProperties());
            this.daoConnectionFactory.init();
        } catch (Exception e) {
            log.fatal("DAO Connection Factory creation failed. Reason:" + e.getLocalizedMessage(),
                      e);
        }
    }

    /**
     * Gets the generic properties for DAO Connection Factory.
     *
     * @return
     */
    private Map<String, Object> getGenericDAOFactoryProperties() {
        Map<String, Object> daoFactoryProperties = new HashMap<String, Object>();
        daoFactoryProperties.put(Constants.DATA_SOURCE_PROP, AttachmentServerHolder.getInstance()
                .getAttachmentServer().getDataSourceManager().getDataSource());
        daoFactoryProperties.put(Constants.PROP_ENABLE_DDL_GENERATION, serverConfiguration.isGenerateDdl());
        daoFactoryProperties.put(Constants.PROP_ENABLE_SQL_TRACING, serverConfiguration.isShowSql());
        daoFactoryProperties.put(Constants.DAO_FACTORY_CLASS_PROP, serverConfiguration.getDaoConnectionFactoryClass());

        return daoFactoryProperties;
    }

    @Override
    public void shutdown() {
        this.daoConnectionFactory.shutdown();
        this.daoConnectionFactory = null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<readable><title>3561639055_5ac66ae92f</title><content>
A bicyclist does maneuvers
A biker lands on the ground after flying through the air .
A cyclist in a helmet is driving down a slope on his bike .
A person on a red bike .
One biker wearing a helmet is jumping over an obstacle .
</content></readable>


text:
package com.intellij.vcs.log.graph;

import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Function;
import com.intellij.vcs.log.graph.api.GraphLayout;
import com.intellij.vcs.log.graph.api.elements.GraphEdge;
import com.intellij.vcs.log.graph.api.elements.GraphElement;
import com.intellij.vcs.log.graph.api.permanent.PermanentCommitsInfo;
import com.intellij.vcs.log.graph.impl.facade.ReachableNodes;
import com.intellij.vcs.log.graph.impl.print.EdgesInRowGenerator;
import com.intellij.vcs.log.graph.impl.print.GraphElementComparatorByLayoutIndex;
import com.intellij.vcs.log.graph.parser.CommitParser;
import org.jetbrains.annotations.NotNull;

import java.util.*;

import static com.intellij.vcs.log.graph.parser.EdgeNodeCharConverter.toChar;

public class GraphStrUtils {

  public static final Comparator<GraphElement> GRAPH_ELEMENT_COMPARATOR =
    new GraphElementComparatorByLayoutIndex(nodeIndex -> 0);

  public static <CommitId> String commitsInfoToStr(PermanentCommitsInfo<CommitId> commitsInfo, int size, Function<? super CommitId, String> toStr) {
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < size; i++) {
      if (i != 0) s.append("\n");

      CommitId commitId = commitsInfo.getCommitId(i);
      int commitIndex = commitsInfo.getNodeId(commitId);
      long timestamp = commitsInfo.getTimestamp(i);

      s.append(commitIndex).append(CommitParser.SEPARATOR);
      s.append(toStr.fun(commitId)).append(CommitParser.SEPARATOR);
      s.append(timestamp);
    }
    return s.toString();
  }

  public static String permanentGraphLayoutModelToStr(GraphLayout graphLayout, int nodesCount) {
    StringBuilder s = new StringBuilder();
    for (int nodeIndex = 0; nodeIndex < nodesCount; nodeIndex++) {
      if (nodeIndex != 0) s.append("\n");

      s.append(graphLayout.getLayoutIndex(nodeIndex)).append(CommitParser.SEPARATOR).append(graphLayout.getOneOfHeadNodeIndex(nodeIndex));
    }
    return s.toString();
  }

  public static String containingBranchesGetterToStr(ReachableNodes reachableNodes, Set<Integer> branches, int nodesCount) {
    StringBuilder s = new StringBuilder();
    for (int nodeIndex = 0; nodeIndex < nodesCount; nodeIndex++) {
      if (nodeIndex != 0) s.append("\n");

      List<Integer> branchNodeIndexes = new ArrayList<>(reachableNodes.getContainingBranches(nodeIndex, branches));
      if (branchNodeIndexes.isEmpty()) {
        s.append("none");
        continue;
      }

      Collections.sort(branchNodeIndexes);
      boolean first = true;
      for (int branchNodeIndex : branchNodeIndexes) {
        if (first) {
          first = false;
        }
        else {
          s.append(" ");
        }

        s.append(branchNodeIndex);
      }
    }
    return s.toString();
  }

  public static String edgesInRowToStr(@NotNull EdgesInRowGenerator edgesInRowGenerator, int nodesCount) {
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < nodesCount; i++) {
      if (i > 0) s.append("\n");
      Set<GraphEdge> edgesInRow = edgesInRowGenerator.getEdgesInRow(i);
      s.append(edgesToStr(edgesInRow));
    }
    return s.toString();
  }

  public static String edgesToStr(@NotNull Set<GraphEdge> edges) {
    if (edges.isEmpty()) return "none";

    List<GraphEdge> sortedEdges = new ArrayList<>(edges);
    Collections.sort(sortedEdges, GRAPH_ELEMENT_COMPARATOR);

    return StringUtil.join(sortedEdges,
                           graphEdge -> graphEdge.getUpNodeIndex() + "_" + graphEdge.getDownNodeIndex() + "_" + toChar(graphEdge.getType()), " ");
  }
}


text:
.sangar-pagination-type-text > li {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #fff;
  box-shadow: 0 0 20px #000000;
  margin-right: 10px;
}
.sangar-pagination-type-text > li:hover {
  cursor: pointer;
}
.sangar-pagination-type-text > li.sangar-pagination-active {
  background: #0b97c4;
}


text:
/* */
var getTag = require('./_getTag'),
    isObjectLike = require('./isObjectLike');
var mapTag = '[object Map]';
function baseIsMap(value) {
  return isObjectLike(value) && getTag(value) == mapTag;
}
module.exports = baseIsMap;


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Security.Cryptography
{
  sealed public partial class SHA512CryptoServiceProvider : SHA512
  {
    #region Methods and constructors
    protected override void Dispose(bool disposing)
    {
    }

    protected override void HashCore(byte[] array, int ibStart, int cbSize)
    {
    }

    protected override byte[] HashFinal()
    {
      return default(byte[]);
    }

    public override void Initialize()
    {
    }

    public SHA512CryptoServiceProvider()
    {
    }
    #endregion
  }
}


text:
package liquibase.configuration;

import java.util.Set;

public interface ConfigurationContainer {
    ConfigurationProperty getProperty(String propertyName);

    Set<ConfigurationProperty> getProperties();

    <T> T getValue(String propertyName, Class<T> returnType);

    void init(ConfigurationValueProvider... configurationValueProviders);
}


text:
class Chef::Provider::RepositoryAuth < Chef::Provider
  include WebSphere

  provides :repository_auth

  def initialize(new_resource, run_context)
    super(new_resource, run_context)
  end

  # Boolean indicating if WhyRun is supported by this provider
  #
  # @return [TrueClass, FalseClass]
  #
  # @api private
  def whyrun_supported?
    true
  end

  # Reload the resource state when something changes
  #
  # @return [undefined]
  #
  # @api private
  def load_new_resource_state
    if new_resource.exists.nil?
      new_resource.exists(@current_resource.exists)
    end
  end

  # Load and return the current resource
  #
  # @return [Chef::Resource::RepositoryAuth]
  #
  # @raise [Odsee::Exceptions::ResourceNotFound]
  #
  # @api private
  def load_current_resource
    @current_resource = Chef::Resource::RepositoryAuth.new(new_resource.name)
    @current_resource.exists(exists?)
    @current_resource
  end

  # Saves the specified credentials to the secure storage file.
  #
  # @return [Chef::Provider::RepositoryAuth]
  #
  # @api private
  def action_store
    if @current_resource.exists
      Chef::Log.debug 'Credentials already stored - nothing to do'
    else
      converge_by 'Saving specified credentials to the secure storage file' do
        generate(new_resource.master_passwd, obfuscate(SecureRandom.hex))
        imutilsc :saveCredential,
                  new_resource._?(:authorizing_url, '-url'),
                  new_resource._?(:username,        '-userName'),
                  new_resource._?(:password,        '-userPassword'),
                  new_resource._?(:secure_storage,  '-secureStorageFile'),
                  new_resource._?(:master_passwd,   '-masterPasswordFile')
      end
      new_resource.updated_by_last_action(true)
    end
    load_new_resource_state
    new_resource.exists(true)
  end

  private #   P R O P R I E T À   P R I V A T A   Vietato L'accesso

  def exists?
    ::File.exist?(new_resource.master_passwd) &&
      ::File.exist?(new_resource.secure_storage)
  end

  # Generates a onetime random strings as the passphrase, which is saved to the
  # master password file.
  #
  # @!visibility private
  def generate(file, content)
    f = Chef::Resource::File.new(file, run_context)
    f.sensitive true
    f.owner     new_resource.owner
    f.group     new_resource.group
    f.mode      00600
    f.content   content
    f.run_action :create
  end
end


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

using commercetools.Common;

using Newtonsoft.Json;

namespace commercetools.Types
{
    /// <summary>
    /// Type
    /// </summary>
    /// <see href="https://dev.commercetools.com/http-api-projects-types.html#type"/>
    public class Type
    {
        #region Properties

        [JsonProperty(PropertyName = "id")]
        public string Id { get; private set; }

        [JsonProperty(PropertyName = "version")]
        public int Version { get; private set; }

        [JsonProperty(PropertyName = "key")]
        public string Key { get; private set; }

        [JsonProperty(PropertyName = "createdAt")]
        public DateTime? CreatedAt { get; private set; }

        [JsonProperty(PropertyName = "lastModifiedAt")]
        public DateTime? LastModifiedAt { get; private set; }

        [JsonProperty(PropertyName = "name")]
        public LocalizedString Name { get; private set; }

        [JsonProperty(PropertyName = "description")]
        public LocalizedString Description { get; private set; }

        [JsonProperty(PropertyName = "resourceTypeIds")]
        public List<string> ResourceTypeIds { get; private set; }

        [JsonProperty(PropertyName = "fieldDefinitions")]
        public List<FieldDefinition> FieldDefinitions { get; private set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes this instance with JSON data from an API response.
        /// </summary>
        /// <param name="data">JSON object</param>
        public Type(dynamic data)
        {
            if (data == null)
            {
                return;
            }

            this.Id = data.id;
            this.Version = data.version;
            this.Key = data.key;
            this.CreatedAt = data.createdAt;
            this.LastModifiedAt = data.lastModifiedAt;
            this.Name = new LocalizedString(data.name);
            this.Description = new LocalizedString(data.description);
            this.ResourceTypeIds = Helper.GetListFromJsonArray<string>(data.resourceTypeIds);
            this.FieldDefinitions = Helper.GetListFromJsonArray<FieldDefinition>(data.fieldDefinitions);
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Equals
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            Type type = obj as Type;

            if (type == null)
            {
                return false;
            }

            return type.Id.Equals(this.Id);
        }

        /// <summary>
        /// GetHashCode
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            return this.Id.GetHashCode();
        }

        #endregion
    }
}


text:
import dataclasses
import functools
from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Set, Tuple, Union
import numpy as np
import sympy

from cirq import devices, ops, protocols, qis
from cirq._import import LazyLoader
from cirq.devices.noise_utils import PHYSICAL_GATE_TAG

if TYPE_CHECKING:
    import cirq

linalg = LazyLoader("linalg", globals(), "scipy.linalg")
moment_module = LazyLoader("moment_module", globals(), "cirq.circuits.moment")

def _left_mul(mat: np.ndarray) -> np.ndarray:
    """Superoperator associated with left multiplication by a square matrix."""
    mat = np.asarray(mat)
    if mat.shape[-1] != mat.shape[-2]:
        raise ValueError(
            f'_left_mul only accepts square matrices, but input matrix has shape {mat.shape}.'
        )
    dim = mat.shape[-1]

    return np.kron(mat, np.eye(dim))

def _right_mul(mat: np.ndarray) -> np.ndarray:
    """Superoperator associated with right multiplication by a square matrix."""
    mat = np.asarray(mat)
    if mat.shape[-1] != mat.shape[-2]:
        raise ValueError(
            f'_right_mul only accepts square matrices, but input matrix has shape {mat.shape}.'
        )
    dim = mat.shape[-1]

    return np.kron(np.eye(dim), np.swapaxes(mat, -2, -1))

def _lindbladian(left_op: np.ndarray) -> np.ndarray:
    r"""Superoperator representing a Lindbladian.

    The Lindbladian generated by a single operator A is the superoperator

        $$
        L(\rho) = A \rho A^\dagger - 0.5 (A^\dagger A \rho + \rho A^\dagger A)
        $$

    Args:
        left_op: The operator acting on the left in the Lindbladian (A above).

    Returns:
        Superoperator corresponding to the Lindbladian.
    """
    left_op = np.asarray(left_op)
    right_op = left_op.conj().T
    square = right_op @ left_op
    out = _left_mul(left_op) @ _right_mul(right_op)
    out -= 0.5 * (_left_mul(square) + _right_mul(square))
    return out

@functools.lru_cache(maxsize=256)
def _kraus_ops_from_rates(
    flat_rates: Tuple[float, ...], shape: Tuple[int, int]
) -> Sequence[np.ndarray]:
    """Generate kraus operators from an array of rates.

    Args:
        flat_rates: A tuple of rates, flattened from a numpy array with:
            flat_rates = tuple(rates.reshape(-1))
            This format is necessary to support caching of inputs.
        shape: The shape of flat_rates prior to flattening.
    """
    rates = np.array(flat_rates).reshape(shape)
    num_op = np.diag(np.sqrt(np.diag(rates)))
    annihilation = np.sqrt(np.triu(rates, 1))
    creation = np.sqrt(np.triu(rates.T, 1)).T
    # Lindbladian with three Lindblad ops for the three processes
    # Note: 'time' parameter already specified implicitly through rates
    L = _lindbladian(annihilation) + _lindbladian(creation) + 2 * _lindbladian(num_op)
    superop = linalg.expm(L.real)
    return qis.superoperator_to_kraus(superop)

def _decoherence_matrix(
    cool_rate: float, dephase_rate: float, heat_rate: float = 0.0, dim: int = 2
) -> np.ndarray:
    """Construct a rate matrix associated with decay and dephasing.

    The units of the matrix match the units of the rates specified.
    This matrix can be used to construct a noise channel after rescaling
    by an idling time (to make it dimensionless).

    Args:
        cool_rate: Decay rate of the system, usually 1 / T_1
        dephase_rate: Static dephasing rate of the system, usually 1 / T_phi
        heat_rate: Heating rate of the system (default 0).
        dim: Number of energy levels to include (default 2).

    Returns:
        np.ndarray rate matrix for decay and dephasing.
    """
    # Heating (related to a^dag)
    rate_matrix = np.diag(np.arange(1, dim) * heat_rate, 1).T.astype(float)
    # Cooling (related to a)
    rate_matrix += np.diag(np.arange(1, dim) * cool_rate, 1)
    # Dephasing (related to n=a^dag * a)
    # We specify i^2 since we take square root to get the Lindblad op later.
    rate_matrix += np.diag(dephase_rate * np.arange(dim) ** 2)
    return rate_matrix

def _as_rate_dict(
    rate_or_dict: Optional[Union[float, Dict['cirq.Qid', float]]], qubits: Set['cirq.Qid']
) -> Dict['cirq.Qid', float]:
    """Convert float or None input into dictionary form.

    This method also ensures that no qubits are missing from dictionary keys.
    """
    if rate_or_dict is None:
        return {q: 0.0 for q in qubits}
    elif isinstance(rate_or_dict, dict):
        return {**{q: 0.0 for q in qubits}, **rate_or_dict}
    else:
        return {q: rate_or_dict for q in qubits}

def _validate_rates(qubits: Set['cirq.Qid'], rates: Dict['cirq.Qid', np.ndarray]) -> None:
    """Check all rate matrices are square and of appropriate dimension.

    We check rates are positive in the class validator.
    """
    if qubits != set(rates):
        raise ValueError('qubits for rates inconsistent with those through qubit_dims')
    for q in rates:
        if rates[q].shape != (q.dimension, q.dimension):
            raise ValueError(
                f'Invalid shape for rate matrix: should be ({q.dimension}, {q.dimension}), '
                f'but got {rates[q].shape}'
            )

@dataclasses.dataclass
class ThermalNoiseModel(devices.NoiseModel):
    """NoiseModel representing simulated thermalization of a qubit.

    This model is designed for qubits which use energy levels as their states.
    "Heating" and "cooling" here are used to refer to environmental noise which
    transitions a qubit to higher or lower energy levels, respectively.
    """

    def __init__(
        self,
        qubits: Set['cirq.Qid'],
        gate_durations_ns: Dict[type, float],
        heat_rate_GHz: Union[float, Dict['cirq.Qid', float], None] = None,
        cool_rate_GHz: Union[float, Dict['cirq.Qid', float], None] = None,
        dephase_rate_GHz: Union[float, Dict['cirq.Qid', float], None] = None,
        require_physical_tag: bool = True,
        skip_measurements: bool = True,
        prepend: bool = False,
    ):
        """Construct a ThermalNoiseModel data object.

        Required Args:
            qubits: Set of all qubits in the system.
            gate_durations_ns: Map of gate types to their duration in
                nanoseconds. These values will override default values for
                gate duration, if any (e.g. WaitGate).
        Optional Args:
            heat_rate_GHz: single number (units GHz) specifying heating rate,
                either per qubit, or global value for all.
                Given a rate gh, the Lindblad op will be sqrt(gh)*a^dag
                (where a is annihilation), so that the heating Lindbladian is
                gh(a^dag • a - 0.5{a*a^dag, •}).
            cool_rate_GHz: single number (units GHz) specifying cooling rate,
                either per qubit, or global value for all.
                Given a rate gc, the Lindblad op will be sqrt(gc)*a
                so that the cooling Lindbladian is gc(a • a^dag - 0.5{n, •})
                This number is equivalent to 1/T1.
            dephase_rate_GHz: single number (units GHz) specifying dephasing
                rate, either per qubit, or global value for all.
                Given a rate gd, Lindblad op will be sqrt(2*gd)*n where
                n = a^dag * a, so that the dephasing Lindbladian is
                2 * gd * (n • n - 0.5{n^2, •}).
                This number is equivalent to 1/Tphi.
            require_physical_tag: whether to only apply noise to operations
                tagged with PHYSICAL_GATE_TAG.
            skip_measurements: whether to skip applying noise to measurements.
            prepend: If True, put noise before affected gates. Default: False.

        Returns:
            The ThermalNoiseModel with specified parameters.
        """
        rate_dict = {}

        heat_rate_GHz = _as_rate_dict(heat_rate_GHz, qubits)
        cool_rate_GHz = _as_rate_dict(cool_rate_GHz, qubits)
        dephase_rate_GHz = _as_rate_dict(dephase_rate_GHz, qubits)

        for q in qubits:
            gamma_h = heat_rate_GHz[q]
            gamma_c = cool_rate_GHz[q]
            gamma_phi = dephase_rate_GHz[q]

            rate_dict[q] = _decoherence_matrix(gamma_c, gamma_phi, gamma_h, q.dimension)

        _validate_rates(qubits, rate_dict)
        self.gate_durations_ns: Dict[type, float] = gate_durations_ns
        self.rate_matrix_GHz: Dict['cirq.Qid', np.ndarray] = rate_dict
        self.require_physical_tag: bool = require_physical_tag
        self.skip_measurements: bool = skip_measurements
        self._prepend = prepend

    def noisy_moment(
        self, moment: 'cirq.Moment', system_qubits: Sequence['cirq.Qid']
    ) -> 'cirq.OP_TREE':
        if not moment.operations:
            return [moment]
        if self.require_physical_tag:
            physical_ops = [PHYSICAL_GATE_TAG in op.tags for op in moment]
            if any(physical_ops):
                if not all(physical_ops):
                    raise ValueError(
                        "Moments are expected to be all physical or all virtual ops, "
                        f"but found {moment.operations}"
                    )
            else:
                # Only moments with physical operations should have noise.
                return [moment]

        noise_ops: List['cirq.Operation'] = []
        # Some devices (including Google hardware) require that all gates have
        # the same duration, but this does not. Instead, each moment is assumed
        # to be as long as the longest gate it contains.
        moment_ns: float = 0
        for op in moment:
            op_duration: Optional[float] = None
            for key, duration in self.gate_durations_ns.items():
                if not issubclass(type(op.gate), key):
                    continue  # gate type doesn't match
                # TODO: remove assumption of same time across qubits
                op_duration = duration
                break
            if op_duration is None and isinstance(op.gate, ops.WaitGate):
                # special case for wait gates if not predefined
                nanos = op.gate.duration.total_nanos()
                if isinstance(nanos, sympy.Expr):
                    raise ValueError('Symbolic wait times are not supported')
                op_duration = nanos
            if op_duration is not None:
                moment_ns = max(moment_ns, op_duration)

        if moment_ns == 0:
            return [moment]

        for qubit in system_qubits:
            qubit_op = moment.operation_at(qubit)
            if self.skip_measurements and protocols.is_measurement(qubit_op):
                continue
            rates = self.rate_matrix_GHz[qubit] * moment_ns
            kraus_ops = _kraus_ops_from_rates(tuple(rates.reshape(-1)), rates.shape)
            noise_ops.append(ops.KrausChannel(kraus_ops).on(qubit))
        if not noise_ops:
            return [moment]
        output = [moment, moment_module.Moment(noise_ops)]
        return output[::-1] if self._prepend else output


text:
// @filename: server.ts
export class c {
}
export interface i {
}
export module m {
    export var x = 10;
}
export var x = 10;
export module uninstantiated {
}

// @filename: client.ts
export { c } from "server";
export { c as c2 } from "server";
export { i, m as instantiatedModule } from "server";
export { uninstantiated } from "server";
export { x } from "server";


text:
=======
Credits
=======

* Jonathan Moss <jonathan.moss@snowballone.com.au>
* Francis Reyes <francis.reyes@snowballone.com.au>


text:
namespace CarsAndDrivers.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    using Microsoft.AspNet.Identity;

    using CarsAndDrivers.Data;

    public abstract class BaseController : Controller
    {
        public BaseController(IApplicationData data)
        {
            this.Data = data;
        }

        protected IApplicationData Data { get; set; }

        [NonAction]
        protected void GetCountries()
        {
            var countries = this.Data.Countries.All().OrderBy(c => c.Name);
            ViewBag.Countries = new SelectList(countries, "Name", "Name");
        }

        [NonAction]
        protected void GetManufactures()
        {
            var manufacturers = this.Data.CarManufacturers.All().OrderBy(c => c.Name);
            ViewBag.Manufacturers = new SelectList(manufacturers, "Name", "Name");
        }

        [NonAction]
        protected void GetModels(string value)
        {
            var models = this.Data.CarModels.All().Where(m => m.CarManufacturer.Name == value).ToList();
            ViewBag.Models = new SelectList(models, "Name", "Name");
        }

        [NonAction]
        protected string GetUserProfileDirectory(string username)
        {
            string userDirectory = GetUserDirectory(username);

            string profileDirectory = userDirectory + "/profile";
            bool existProfileDirectory = Directory.Exists(Server.MapPath(profileDirectory));
            if (!existProfileDirectory)
            {
                Directory.CreateDirectory(Server.MapPath(profileDirectory));
            }

            return profileDirectory;
        }

        [NonAction]
        protected string GetUserPicturesDirectory(string username)
        {
            string userDirectory = GetUserDirectory(username);

            string picturesDirectory = userDirectory + "/pictures";
            bool existPicturesDirectory = Directory.Exists(Server.MapPath(picturesDirectory));
            if (!existPicturesDirectory)
            {
                Directory.CreateDirectory(Server.MapPath(picturesDirectory));
            }

            return picturesDirectory;
        }

        [NonAction]
        private string GetUserDirectory(string username)
        {
            string userDirectory = "/uploads/" + username;
            bool exists = Directory.Exists(Server.MapPath(userDirectory));

            if (!exists)
            {
                Directory.CreateDirectory(Server.MapPath(userDirectory));
            }

            return userDirectory;
        }
    }
}


text:
/**
 * @module
 * @description
 * Define angular core API here.
 */
export {appComponentTypeToken} from 'angular2/src/core/application_tokens';
export {ApplicationRef} from 'angular2/src/core/application_common';

// Compiler Related Dependencies.
export {AppRootUrl} from 'angular2/src/services/app_root_url';
export {UrlResolver} from 'angular2/src/services/url_resolver';
export {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
export {DirectiveResolver} from 'angular2/src/core/compiler/directive_resolver';
export {Compiler} from 'angular2/src/core/compiler/compiler';

export {AppViewManager} from 'angular2/src/core/compiler/view_manager';
export {IQueryList} from 'angular2/src/core/compiler/interface_query';
export {QueryList} from 'angular2/src/core/compiler/query_list';
export {DynamicComponentLoader} from 'angular2/src/core/compiler/dynamic_component_loader';
export {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle';

export {ElementRef} from 'angular2/src/core/compiler/element_ref';
export {TemplateRef} from 'angular2/src/core/compiler/template_ref';
export {RenderElementRef} from 'angular2/src/render/api';
export {ViewRef, HostViewRef, ProtoViewRef} from 'angular2/src/core/compiler/view_ref';
export {ViewContainerRef} from 'angular2/src/core/compiler/view_container_ref';
export {ComponentRef} from 'angular2/src/core/compiler/dynamic_component_loader';

export {NgZone} from 'angular2/src/core/zone/ng_zone';
export {Observable, EventEmitter} from 'angular2/src/facade/async';


text:
<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="https://code.angularjs.org/tools/system.js"></script>
    <script src="https://code.angularjs.org/tools/typescript.js"></script>
    <script src="config.js"></script>
    <script src="lib/angular2-polyfills.js"></script>
    <script src="lib/Rx.js"></script>
    <script src="lib/angular2.js"></script>
    <script>
    System.import('app')
      .catch(console.error.bind(console));
    </script>
</head>
<body>
    <app></app>
</body>
</html>


text:
#ifndef LIBSIMDPP_SIMDPP_CORE_I_MULL_H
#define LIBSIMDPP_SIMDPP_CORE_I_MULL_H

#ifndef LIBSIMDPP_SIMD_H
    #error "This file must be included through simd.h"
#endif

#include <simdpp/types.h>
#include <simdpp/detail/expr/i_mull.h>
#include <simdpp/core/detail/scalar_arg_impl.h>

namespace simdpp {
namespace SIMDPP_ARCH_NAMESPACE {

/*  Note: widening integer multiplication instructions are very different among
    instruction sets. The main difference is in which half of the elements are
    selected for multiplication. Trying to abstract this incurs definite
    overhead.

     - SSE2-SSE4.1 and AVX2 provide only instructions with interfaces similar
        to mul_lo and mul_hi. The result vectors must be interleaved to obtain
        contiguous result values. Multiplying 2 vectors always incurs
        overhead of at least two interleaving instructions.

     - AVX512 only provides 32-bit integer support. Widening multiplication
        can be done only by using PMULDQ, which takes odd elements and produces
        widened multiplication results. Multiplication of two whole vectors
        always incurs overhead of at least two shifts or interleaving
        instructions.

     - NEON, NEONv2 provide instructions that take elements of either the lower
        or higher halves of two 128-bit vectors and multiply them. No
        additional overhead is incurred to obtain contiguous result values.

     - ALTIVEC hav multiply odd and multiply even instructions. No additional
        overhead is incurred to obtain contiguous result values.

    The abstraction below uses the NEON model. No additional overhead is
    incurred on SSE/AVX and NEON. On ALTIVEC, a single additional permute
    instruction is needed for each vector multiplication on average.
*/

/** Multiplies signed 16-bit values and expands the results to 32 bits.

    @par 128-bit version:
    @code
    r0 = a0 * b0
    ...
    rN = aN * bN
    @endcode

    @icost{SSE2-AVX, ALTIVEC, 2-3}

    @par 256-bit version:

    @icost{SSE2-AVX, ALTIVEC, 4-6}
    @icost{AVX2, NEON, 2-3}
*/
template<unsigned N, class E1, class E2> SIMDPP_INL
int32<N, expr_mull<int16<N,E1>,
                   int16<N,E2>>> mull(const int16<N,E1>& a, const int16<N,E2>& b)
{
    return { { a, b } };
}

SIMDPP_SCALAR_ARG_IMPL_EXPR(mull, expr_mull, int32, int16)

/** Multiplies unsigned 16-bit values and expands the results to 32 bits.

    @par 128-bit version:
    @code
    r0 = a0 * b0
    ...
    rN = aN * bN
    @endcode

    @icost{SSE2-AVX2, ALTIVEC, 2-3}

    @par 256-bit version:
    @icost{SSE2-AVX, ALTIVEC, 4-6}
    @icost{AVX2, 2-3}
    @icost{NEON, 2}
*/
template<unsigned N, class E1, class E2> SIMDPP_INL
uint32<N, expr_mull<uint16<N,E1>,
                    uint16<N,E2>>> mull(const uint16<N,E1>& a, const uint16<N,E2>& b)
{
    return { { a, b } };
}

SIMDPP_SCALAR_ARG_IMPL_EXPR(mull, expr_mull, uint32, uint16)

/** Multiplies signed 32-bit values in and expands the results to 64 bits.

    @code
    r0 = a0 * b0
    ...
    rN = aN * bN
    @endcode
    @par 128-bit version:
    @icost{SSE4.1-AVX, 3}
    @unimp{SSE2-SSSE3, ALTIVEC}

    @par 256-bit version:
    @icost{SSE4.1-AVX, 6}
    @icost{AVX2, 3}
    @icost{NEON, 2}
    @unimp{SSE2-SSSE3, ALTIVEC}
*/
template<unsigned N, class E1, class E2> SIMDPP_INL
int64<N, expr_mull<int32<N,E1>,
                   int32<N,E2>>> mull(const int32<N,E1>& a, const int32<N,E2>& b)
{
    return { { a, b } };
}

SIMDPP_SCALAR_ARG_IMPL_EXPR(mull, expr_mull, int64, int32)

/** Multiplies unsigned 32-bit values in the lower halves of the vectors and
    expands the results to 64 bits.

    @par 128-bit version:
    @code
    r0 = a0 * b0
    r1 = a1 * b1
    @endcode
    @icost{SSE2-AVX, 3}
    @unimp{ALTIVEC}

    @icost{SSE2-AVX, 6}
    @icost{AVX2, 3}
    @icost{NEON, 2}
    @unimp{ALTIVEC}
*/
template<unsigned N, class E1, class E2> SIMDPP_INL
uint64<N, expr_mull<uint32<N,E1>,
                    uint32<N,E2>>> mull(const uint32<N,E1>& a, const uint32<N,E2>& b)
{
    return { { a, b } };
}

SIMDPP_SCALAR_ARG_IMPL_EXPR(mull, expr_mull, uint64, uint32)

} // namespace SIMDPP_ARCH_NAMESPACE
} // namespace simdpp

#endif


text:
<?php

/**
 * User: Alex Gusev <alex@flancer64.com>
 */
include_once('../../../phpunit_bootstrap.php');

/**
 * User: Alex Gusev <alex@flancer64.com>
 */
class Praxigento_Ips_Test_Model_Own_Service_Call_UnitTest extends PHPUnit_Framework_TestCase
{
    const TEST_CURR = 'USD';
    const TEST_USERNAME = 'json_user_1';

    public function test_constructor()
    {
        $call = Mage::getModel('prxgt_ips_model/own_service_call');
        $this->assertNotNull($call);
    }

    public function test_getCurrencyBalance()
    {
        /** @var  $call Praxigento_Ips_Model_Own_Service_Call */
        $call = $this->_initServiceCall();

        /** @var  $req Praxigento_Ips_Model_Own_Service_GetCurrencyBalance_Request */
        $req = Mage::getModel('prxgt_ips_model/own_service_getCurrencyBalance_request');
        $req->setCurrencyCode(self::TEST_CURR);
        $req->setUserName(self::TEST_USERNAME);
        $resp = $call->getCurrencyBalance($req);
        $this->assertTrue($resp instanceof Praxigento_Ips_Model_Own_Service_GetCurrencyBalance_Response);
        $this->assertTrue($resp->isSucceed());
        $this->assertEquals(self::TEST_CURR, $resp->getCommonCurrencyCode());
        $this->assertNotNull($resp->getBalance());
    }

    /**
     * Return initialized object to perform tests.
     *
     * @return Praxigento_Ips_Model_Own_Service_Call
     */
    private function _initServiceCall()
    {
        /** @var  $result Praxigento_Ips_Model_Own_Service_Call */
        $result = Mage::getModel('prxgt_ips_model/own_service_call');
        $this->assertNotNull($result);
        $result->setIsInTestMode(true);
        $result->setMerchantGuid(Praxigento_Ips_Config::cfgStoreIpsMerchantGuid());
        $result->setMerchantPassword(Praxigento_Ips_Config::cfgStoreIpsMerchantPassword());
        return $result;
    }

    public function test_registerUser()
    {
        /** @var  $call Praxigento_Ips_Model_Own_Service_Call */
        $call = $this->_initServiceCall();

        /** @var  $req Praxigento_Ips_Model_Own_Service_RegisterUser_Request */
        $req = Mage::getModel('prxgt_ips_model/own_service_registerUser_request');
        $req->setUserName(self::TEST_USERNAME);
        $req->setFirstName('WSTest');
        $req->setLastName('Test');
        $req->setEmailAddress('user@aol.com');
        $resp = $call->registerUser($req);
        $this->assertTrue($resp instanceof Praxigento_Ips_Model_Own_Service_RegisterUser_Response);
        /* user should be created */
        $this->assertFalse($resp->isSucceed());
        $this->assertEquals(
            Praxigento_Ips_Model_Own_Base_Response::CODE_USERNAME_EXISTS,
            $resp->getCommonMessageCode()
        );
    }

    public function test_load()
    {
        /** @var  $call Praxigento_Ips_Model_Own_Service_Call */
        $call = $this->_initServiceCall();

        /** @var  $req Praxigento_Ips_Model_Own_Service_Load_Request */
        $req = Mage::getModel('prxgt_ips_model/own_service_load_request');
        $entry = Mage::getModel('prxgt_ips_model/own_bean_eWalletLoad');
        $entry->setUserName('tpartyrep');
        $entry->setAmount('10.00');
        $entry->setComments('from test units');
        $entry->setMerchantReferenceID('ref id');
        $req->addAccountsEntry($entry);
        $req->setPartnerBatchID(2);
        $resp = $call->load($req);
        $this->assertTrue($resp instanceof Praxigento_Ips_Model_Own_Service_Load_Response);
        /* user should be created */
        $this->assertFalse($resp->isSucceed());
    }

    public function test_depositToMerchant()
    {
        /** @var  $call Praxigento_Ips_Model_Own_Service_Call */
        $call = $this->_initServiceCall();

        /** @var  $req Praxigento_Ips_Model_Own_Service_DepositToMerchant_Request */
        $req = Mage::getModel('prxgt_ips_model/own_service_depositToMerchant_request');
        $req->setUserName('tpartyrep');
        $req->setAmount('10.00');
        $req->setCurrencyCode('USD');
        $req->setReason('from test units');
        $req->setMerchantReferenceID('ref id');
        $resp = $call->depositToMerchant($req);
        $this->assertTrue($resp instanceof Praxigento_Ips_Model_Own_Service_DepositToMerchant_Response);
        /* user should be created */
        $this->assertFalse($resp->isSucceed());
    }
}


text:
OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\n    \"codigoProduto\": \"178\",\n    \"tipoConsumidor\": \"J\",\n    \"documentoConsumidor\": \"02117943000124\",\n    \"cepConsumidor\": \"14401-360\",\n    \"cepOrigem\": \"14401-360\",\n    \"codigoEstacaoConsultante\": \"123\"\n}");
Request request = new Request.Builder()
  .url("http://186.249.34.34/api/consulta")
  .post(body)
  .addHeader("content-type", "application/json")
  .addHeader("authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJjb25zdWx0YUBlbnRlcnBsdWcuY29tLmJyIiwiZXhwIjoxNDcwODU3ODQwfQ.g7E2ABhES7yQXoIfpBTv30yDjal07EEI9i9Tu-d1Jjksxpv1UseaZpbjfqeNKF3pi_-xeX5ihN2EITPg184oaA")
  .addHeader("cache-control", "no-cache")
  .build();

Response response = client.newCall(request).execute();


text:
@implementation MJExtensionConfig
+(void)load
{
    [WYQLoginUserModel setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{@"userId" : @"id"};
    }];
    [STWLoginUserDetail setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{@"userId" : @"id"};
    }];
    [WYQLoginUserModel setupIgnoredPropertyNames:^NSArray *{
        return @[@"loginDetail"];
    }];
}

@end


text:
import { D1ObjectiveDefinition, D1ObjectiveProgress } from 'app/destiny1/d1-manifest-types';
import RichDestinyText from 'app/dim-ui/RichDestinyText';
import { t } from 'app/i18next-t';
import {
  getValueStyle,
  isBooleanObjective,
  isFlawlessObjective,
  isRoundsWonObjective,
} from 'app/inventory/store/objectives';
import { useDefinitions } from 'app/manifest/selectors';
import { percent, percentWithSingleDecimal } from 'app/shell/formatters';
import { timerDurationFromMs } from 'app/utils/time';
import {
  DestinyObjectiveDefinition,
  DestinyObjectiveProgress,
  DestinyUnlockValueUIStyle,
} from 'bungie-api-ts/destiny2';
import clsx from 'clsx';
import '../item-popup/ItemObjectives.scss';
import ObjectiveDescription from './ObjectiveDescription';

export default function Objective({
  objective,
  suppressObjectiveDescription,
  isTrialsPassage,
  showHidden,
}: {
  objective: DestinyObjectiveProgress | D1ObjectiveProgress;
  suppressObjectiveDescription?: boolean;
  isTrialsPassage?: boolean;
  showHidden?: boolean;
}) {
  const defs = useDefinitions()!;
  const objectiveDef = defs.Objective.get(objective.objectiveHash);

  const progress = objective.progress || 0;

  if (!objectiveDef) {
    return null;
  }

  if (
    'minimumVisibilityThreshold' in objectiveDef &&
    objectiveDef.minimumVisibilityThreshold > 0 &&
    progress < objectiveDef.minimumVisibilityThreshold
  ) {
    return null;
  }

  // These two are to support D1 objectives
  const completionValue =
    'completionValue' in objective ? objective.completionValue : objectiveDef.completionValue;

  const complete = 'complete' in objective ? objective.complete : objective.isComplete;

  const progressDescription =
    // D1 display description
    ('displayDescription' in objectiveDef && objectiveDef.displayDescription) ||
    (!suppressObjectiveDescription &&
      'progressDescription' in objectiveDef &&
      objectiveDef.progressDescription) ||
    (complete ? t('Objectives.Complete') : t('Objectives.Incomplete'));

  const valueStyle = getValueStyle(objectiveDef, progress, completionValue);
  if (!showHidden && valueStyle === DestinyUnlockValueUIStyle.Hidden) {
    return null;
  }

  if (valueStyle === DestinyUnlockValueUIStyle.Integer) {
    return (

          <ObjectiveDescription
            progressDescription={progressDescription}
            objectiveDef={objectiveDef}
          />

{progress.toLocaleString()}

    );
  }

  const isBoolean = isBooleanObjective(objectiveDef, progress, completionValue);
  const showAsCounter = isTrialsPassage && isRoundsWonObjective(objective.objectiveHash);
  const passageFlawed =
    isTrialsPassage && isFlawlessObjective(objective.objectiveHash) && !complete;

  const classes = clsx('objective-row', {
    'objective-complete': complete && !showAsCounter,
    'objective-boolean': isBoolean,
    'passage-flawed': passageFlawed,
  });

  const progressBarStyle = {
    width: percent(progress / completionValue),
  };

  // TODO: green pips, red pips

  return (

      {!showAsCounter &&
}

        {!isBoolean &&
}

          <RichDestinyText text={progressDescription} />

        {!isBoolean && (

            <ObjectiveValue
              objectiveDef={objectiveDef}
              progress={progress}
              completionValue={completionValue}
            />

        )}

      {showAsCounter &&
{progress}
}

  );
}

export function ObjectiveValue({
  objectiveDef,
  progress,
  completionValue = 0,
}: {
  objectiveDef: DestinyObjectiveDefinition | D1ObjectiveDefinition | undefined;
  progress: number;
  completionValue?: number;
}) {
  const valueStyle = getValueStyle(objectiveDef, progress, completionValue);

  // TODO: pips

  switch (valueStyle) {
    case DestinyUnlockValueUIStyle.DateTime:
      return <>{new Date(progress).toLocaleString()}</>;
    case DestinyUnlockValueUIStyle.Percentage:
      if (completionValue === 100) {
        return <>{percent(progress / completionValue)}</>;
      } else if (completionValue === 1000) {
        return <>{percentWithSingleDecimal(progress / completionValue)}</>;
      }
      break;
    case DestinyUnlockValueUIStyle.ExplicitPercentage:
      return <>{progress + '%'}</>;
    case DestinyUnlockValueUIStyle.FractionFloat:
      return <>{percent(progress * completionValue)}</>;
    case DestinyUnlockValueUIStyle.Multiplier:
      return <>{progress.toLocaleString() + '𝗑'}</>;
    case DestinyUnlockValueUIStyle.RawFloat:
      return <>{(progress / 100).toLocaleString()}</>;
    case DestinyUnlockValueUIStyle.TimeDuration:
      return <>{timerDurationFromMs(progress)}</>;
    case DestinyUnlockValueUIStyle.Checkbox:
    case DestinyUnlockValueUIStyle.Hidden:
      return null;
    default:
      break;
  }

  // Default
  return completionValue === 0 ||
    (objectiveDef &&
      'allowOvercompletion' in objectiveDef &&
      objectiveDef.allowOvercompletion &&
      completionValue === 1) ? (
    <>{progress.toLocaleString()}</>
  ) : (
    <>
      {progress.toLocaleString()}
      <wbr />/<wbr />
      {completionValue.toLocaleString()}
    </>
  );
}


text:
<?php
defined("_VALID_ACCESS") || die('Direct access forbidden');

if (ModuleManager::is_installed('CRM_Roundcube') >= 0) {
    foreach(DB::GetCol('SELECT id FROM user_login') as $id) {
	$identity = DB::GetOne("SELECT ".DB::Concat('f_first_name',DB::qstr(' '),'f_last_name')." FROM contact_data_1 WHERE f_login =%d",array($id));
	foreach(DB::GetCol("SELECT f_email FROM rc_accounts_data_1 WHERE f_epesi_user=%d", array($id)) as $f_email)
	    DB::Execute('UPDATE rc_identities SET name=%s WHERE email=%s',array($identity,$f_email));

    }
}
?>


text:
#ifndef __F2N_H_
#define __F2N_H_

#include"mpf.h"

template<typename fmanager>
class f2n {
public:
    typedef typename fmanager::numeral numeral;
    struct exception {};

private:
    fmanager &        m_manager;
    mpf_rounding_mode m_mode;
    unsigned          m_ebits;
    unsigned          m_sbits;
    numeral           m_tmp1;
    numeral           m_one;

    void check(numeral const & n) { if (!m().is_regular(n)) throw exception(); }

public:
    static bool field() { return true; }
    static bool precise() { return false; }

    f2n(fmanager & m, unsigned ebits = 11, unsigned sbits = 53):m_manager(m), m_mode(MPF_ROUND_TOWARD_POSITIVE), m_ebits(ebits), m_sbits(sbits) {
        m_manager.set(m_one, ebits, sbits, 1);
    }

    ~f2n() {
        m().del(m_tmp1);
        m().del(m_one);
    }

    void set_rounding_mode(mpf_rounding_mode m) { m_mode = m; }
    mpf_rounding_mode rounding_mode() const { return m_mode; }
    void round_to_plus_inf() { m_mode = MPF_ROUND_TOWARD_POSITIVE; }
    void round_to_minus_inf() { m_mode = MPF_ROUND_TOWARD_NEGATIVE; }
    void set_rounding(bool to_plus_inf) { if (to_plus_inf) round_to_plus_inf(); else round_to_minus_inf(); }
    unsigned ebits() const { return m_ebits; }
    unsigned sbits() const { return m_sbits; }

    fmanager & m() const { return m_manager; }

    double to_double(numeral & x) const { return m().to_double(x); }

    void del(numeral & x) { m().del(x); }

    void abs(numeral & o) { m().abs(o); }
    void abs(numeral const & x, numeral & o) { m().abs(x, o); }

    void neg(numeral & o) { m().neg(o); }
    void neg(numeral const & x, numeral & o) { m().neg(x, o); }

    bool is_zero(numeral const & x) { return m().is_zero(x); }
    bool is_neg(numeral const & x) { return m().is_neg(x) && !m().is_zero(x); /* it is not clear whether actual hardware returns true for is_neg(0-) */ }
    bool is_pos(numeral const & x) { return m().is_pos(x) && !m().is_zero(x); }
    bool is_nonneg(numeral const & x) { return !is_neg(x); }
    bool is_nonpos(numeral const & x) { return !is_pos(x); }

    void set(numeral & o, int value) { m().set(o, m_ebits, m_sbits, value); check(o); }
    void set(numeral & o, int n, int d) { m().set(o, m_ebits, m_sbits, m_mode, n, d); check(o); }
    void set(numeral & o, double x) { m().set(o, m_ebits, m_sbits, x); check(o); }
    void set(numeral & o, unsigned value) { m().set(o, m_ebits, m_sbits, (double)value); check(o); }
    void set(numeral & o, numeral const & x) { m().set(o, x); check(o); }
    void set(numeral & o, mpq const & x) { m().set(o, m_ebits, m_sbits, m_mode, x); check(o); }
    void reset(numeral & o) { m().reset(o, m_ebits, m_sbits); }
    static void swap(numeral & x, numeral & y) { x.swap(y); }

    void add(numeral const & x, numeral const & y, numeral & o) { m().add(m_mode, x, y, o); check(o); }
    void sub(numeral const & x, numeral const & y, numeral & o) { m().sub(m_mode, x, y, o); check(o); }
    void mul(numeral const & x, numeral const & y, numeral & o) { m().mul(m_mode, x, y, o); check(o); }
    void div(numeral const & x, numeral const & y, numeral & o) { m().div(m_mode, x, y, o); check(o); }
    void inv(numeral & o) { numeral a; set(a, 1); div(a, o, o); del(a);  check(o); }
    void inv(numeral const & x, numeral & o) { set(o, x); inv(o); }
    void inc(numeral & x) { add(x, m_one, x); }
    void dec(numeral & x) { sub(x, m_one, x); }

    void power(numeral const & a, unsigned p, numeral & b) {
        unsigned mask = 1;
        numeral power;
        set(power, a);
        set(b, 1);
        while (mask <= p) {
            if (mask & p)
                mul(b, power, b);
            mul(power, power, power);
            mask = mask << 1;
        }
        del(power);
        check(b);
    }

    // Store the floor of a into b. Return true if a is an integer.
    // Throws an exception if the result cannot be computed precisely.
    void floor(numeral const & a, numeral & b) {
        SASSERT(m().is_regular(a));
        // Claim: If a is a regular float, then floor(a) is an integer that can be precisely represented.
        // Justification: (for the case a is nonnegative)
        //       If 0 <= a  > 2^sbits(), then a is an integer, and floor(a) == a
        //       If 0 <= a <= 2^sbits(), then floor(a) is representable since every integer less than 2^sbit
        m().round_to_integral(MPF_ROUND_TOWARD_NEGATIVE, a, m_tmp1);
        SASSERT(m().is_regular(m_tmp1));
        if (m().le(m_tmp1, a)) {
            m().set(b, m_tmp1);
        }
        else {
            // the rounding mode doesn't matter for the following operation.
            m().sub(MPF_ROUND_TOWARD_NEGATIVE, m_tmp1, m_one, b);
        }
        SASSERT(m().is_regular(b));
    }

    void ceil(numeral const & a, numeral & b) {
        SASSERT(m().is_regular(a));
        // See comment in floor
        m().round_to_integral(MPF_ROUND_TOWARD_POSITIVE, a, m_tmp1);
        SASSERT(m().is_regular(m_tmp1));
        if (m().ge(m_tmp1, a)) {
            m().set(b, m_tmp1);
        }
        else {
            // the rounding mode doesn't matter for the following operation.
            m().add(MPF_ROUND_TOWARD_NEGATIVE, m_tmp1, m_one, b);
        }
        SASSERT(m().is_regular(b));
    }

    unsigned prev_power_of_two(numeral const & a) { return m().prev_power_of_two(a); }

    bool eq(numeral const & x, numeral const & y) { return m().eq(x, y); }
    bool lt(numeral const & x, numeral const & y) { return m().lt(x, y); }
    bool le(numeral const & x, numeral const & y) { return m().le(x, y); }
    bool gt(numeral const & x, numeral const & y) { return m().gt(x, y); }
    bool ge(numeral const & x, numeral const & y) { return m().ge(x, y); }

    bool is_int(numeral const & x) { return m().is_int(x); }
    bool is_one(numeral const & x) { return m().is_one(x); }
    bool is_minus_one(numeral const & x) { numeral & _x = const_cast<numeral &>(x); m().neg(_x); bool r = m().is_one(_x); m().neg(_x); return r; }

    std::string to_string(numeral const & a) { return m().to_string(a); }
    std::string to_rational_string(numeral const & a) { return m().to_rational_string(a); }
    void display(std::ostream & out, numeral const & a) { out << to_string(a); }
    void display_decimal(std::ostream & out, numeral const & a, unsigned k) { m().display_decimal(out, a, k); }
    void display_smt2(std::ostream & out, numeral const & a, bool decimal) { m().display_smt2(out, a, decimal); }
};

#endif


text:
var searchData=
[
  ['namedidentifier',['NamedIdentifier',['../class_ilwis_1_1_named_identifier.html',1,'Ilwis']]],
  ['namedidentifierrange',['NamedIdentifierRange',['../class_ilwis_1_1_named_identifier_range.html',1,'Ilwis']]],
  ['nullprojection',['NullProjection',['../class_ilwis_1_1_null_projection.html',1,'Ilwis']]],
  ['numericdomain',['NumericDomain',['../class_ilwis_1_1_numeric_domain.html',1,'Ilwis']]],
  ['numericdomainmerger',['NumericDomainMerger',['../class_ilwis_1_1_numeric_domain_merger.html',1,'Ilwis']]],
  ['numericitem',['NumericItem',['../class_ilwis_1_1_numeric_item.html',1,'Ilwis']]],
  ['numericitemrange',['NumericItemRange',['../class_ilwis_1_1_numeric_item_range.html',1,'Ilwis']]],
  ['numericoperation',['NumericOperation',['../class_ilwis_1_1_numeric_operation.html',1,'Ilwis']]],
  ['numericrange',['NumericRange',['../class_ilwis_1_1_numeric_range.html',1,'Ilwis']]]
];


text:
jQuery(document).ready(function ($) {
	CKEDITOR.plugins.add('cmsplugins', {

		// Register the icons. They must match command names.
		icons: 'cmsplugins',

		// The plugin initialization logic goes inside this method.
		init: function(editor) {
			var that = this;

			this.lang = CMS.CKEditor.options.cmsLang;
			this.plugins = CMS.CKEditor.options.cmsPlugins;
			this.page_id = CMS.CKEditor.options.cmsPage;
			this.editor = editor;

			// don't do anything if there are no plugins defined
			if (this.plugins.length === 0) return;

			this.setupDialog();

			// add the button
			this.editor.ui.add('cmsplugins', CKEDITOR.UI_PANELBUTTON, {
				'toolbar': 'cms,0',
				'label': this.lang.toolbar,
				'title': this.lang.toolbar,
				'className' : 'cke_panelbutton__cmsplugins',
				'modes': { wysiwyg:1 },
				'editorFocus': 1,

				'panel': {
					'css': [CKEDITOR.skin.getPath('editor')].concat(that.editor.config.contentsCss),
					'attributes': { role: 'cmsplugins', 'aria-label': this.lang.aria }
				},

				// this is called when creating the dropdown list
				'onBlock': function (panel, block) {
					block.element.setHtml(that.editor.plugins.cmsplugins.setupDropdown());

					var anchors = $(block.element.$).find('.cke_panel_listItem a');
						anchors.bind('click', function (e) {
							e.preventDefault();

							that.addPlugin($(this), panel);
						});
				}
			});

			// handle edit event via context menu
			if(this.editor.contextMenu) {
				this.setupContextMenu();
				this.editor.addCommand('cmspluginsEdit', {
					exec: function () {
						that.editPlugin(that.editor.getSelection().getSelectedElement());
					}
				});
			}

			// hande event via doubleclick
			// handle edit event on double click
			this.editor.on('doubleclick', function(event) {
				var element = that.editor.getSelection().getSelectedElement();

				if(element && $(element.$).attr('id').split('_')[0] === 'plugin' && !element.isReadOnly()) {
					event.data.dialog = '';
					that.editPlugin(element);
				}
			});
		},

		setupDialog: function () {
			var that = this;
			var definition = function () { return {
				'title': '',
				'minWidth': 600,
				'minHeight': 150,
				'contents': [{
					'elements': [{ type: 'html', html: '' }]
				}],
				'onOk': function () {
					var iframe = $(CKEDITOR.dialog.getCurrent().parts.contents.$).find('iframe').contents();
						iframe.find('form').submit();

					// catch the reload event and reattach
					var reload = CMS.API.Helpers.reloadBrowser;
					CMS.API.Helpers.reloadBrowser = function(id, icon, alt) {
						CKEDITOR.dialog.getCurrent().hide();
						that.insertPlugin({
							'id': id,
							'icon': icon,
							'alt': alt
						});

						CMS.API.Helpers.reloadBrowser = reload;
						return false;
					};
					return false;
				}
			}};

			// set default definition and open dialog
			CKEDITOR.dialog.add('cmspluginsDialog', definition);
		},

		setupDropdown: function () {
			var tpl = '
';

			// loop through the groups
			$.each(this.plugins, function (i, group) {
				// add template
				tpl += '
' + group.group + '
';
				tpl += '
';
				// loop through the plugins
				// TODO the url is static, will change for 3.0
				$.each(group.items, function (ii, item) {
					tpl += '
' + item.title + '
';
				});
				tpl += '
';
			});

			tpl += '
';

			return tpl;
		},

		setupContextMenu: function () {
			this.editor.addMenuGroup('cmspluginsGroup');
			this.editor.addMenuItem('cmspluginsItem', {
				label: this.lang.edit,
				icon: '../ckeditor_plugins/cmsplugins/icons/cmsplugins.png',
				command: 'cmspluginsEdit',
				group: 'cmspluginsGroup'
			});

			this.editor.removeMenuItem('image');

			this.editor.contextMenu.addListener(function(element) {
				if($(element.$).attr('id').split('_')[0] === 'plugin') {
					return { cmspluginsItem: CKEDITOR.TRISTATE_OFF };
				}
			});
		},

		editPlugin: function (el) {
			var id = el.getAttribute('id').replace('plugin_obj_', '');

			this.editor.openDialog('cmspluginsDialog');

			// now tweak in dynamic stuff
			var dialog = CKEDITOR.dialog.getCurrent();
			$(dialog.parts.title.$).text(this.lang.edit);
			$(dialog.parts.contents.$).find('iframe').attr('src', '../' + id + '/?_popup=1&no_preview')
				.bind('load', function () {
					$(this).contents().find('.plugin-submit-row').hide().end()
						.find('#container').css('min-width', 0);
				});
				dialog.data = { 'id': el.getAttribute('id') };
		},

		addPlugin: function (item, panel) {
			var that = this;

			// hide the panel
			panel.hide();

			// lets figure out how to write something to the editor
			this.editor.focus();
			this.editor.fire('saveSnapshot');

			// lets do some ajax
			$.ajax({
				'type': 'POST',
				'url': 'add-plugin/',
				'data': {
					parent_id: that.page_id,
					plugin_type: item.attr('rel')
				},
				'success': function (plugin_id) {
					if(plugin_id === 'error') return false;

					that.addPluginDialog(item, plugin_id);
				},
				'error': function () {
					alert('There was an error creating the plugin.');
				}
			});
		},

		addPluginDialog: function (item, id) {
			// open the dialog
			this.editor.openDialog('cmspluginsDialog');

			// now tweak in dynamic stuff
			var dialog = CKEDITOR.dialog.getCurrent();
				$(dialog.parts.title.$).text(this.lang.add);
				$(dialog.parts.contents.$).find('iframe').attr('src', '../' + id + '/?_popup=1')
					.bind('load', function () {
						$(this).contents().find('.plugin-submit-row').hide().end()
							.find('#container').css('min-width', 0);
					});
				// set new data
				dialog.data = { 'id': id };
		},

		insertPlugin: function (data) {
			var element = new CKEDITOR.dom.element('img', this.editor.document);
				element.setAttributes({
					'id': 'plugin_obj_' + data.id,
					'src': data.icon,
					'alt': data.alt,
					'title': data.alt
				});

			this.editor.insertElement(element);
		}

	});
});


text:
from pyramid.view import view_config
from datetime import datetime
from pyramid.httpexceptions import HTTPFound
import os
from pyramid.threadlocal import get_current_registry

import re

settings = get_current_registry().settings
_re_line = re.compile(settings['message_format'], re.VERBOSE)

@view_config(route_name='home')
def my_view(request):
    year = datetime.now().year
    month = datetime.now().strftime("%m")
    day = datetime.now().strftime("%d")
    channels = settings['channels']
    if '\n' in channels:
        channels = [chan for chan in channels.splitlines() if chan]
    return HTTPFound(
            location=request.route_url(
                'date',
                day = day,
                month = month,
                year = year,
                channel = channels[0]))

@view_config(route_name='date', renderer='templates/template.pt')
def date_view(request):
    if request.method == 'POST':
        channel = request.POST['channel']
        return HTTPFound(
                location=request.route_url(
                    'date',
                    day = request.matchdict['day'],
                    month = request.matchdict['month'],
                    year = request.matchdict['year'],
                    channel = channel))
    else:
        channel = request.matchdict['channel']
    logs = []
    day = request.matchdict['day']
    month = request.matchdict['month']
    year = request.matchdict['year']
    channels = settings['channels']
    if '\n' in channels:
        channels = [chan for chan in channels.splitlines() if chan]
    date = '%s/%s/%s' % (day,month,year)
    path_log = settings['log_path'].format(channel = '#%s' % channel, year=year,month=month,day=day)
    file_format = settings['file_format']
    log_file = os.path.join(path_log, file_format.format(channel = '#%s' % channel, year=year,month=month,day=day))
    if os.path.exists(log_file):
        with open(log_file) as f:
            for line in f.readlines():
                try:
                    match = _re_line.search(line.decode('utf-8','replace'))
                    if not match:
                        raise ValueError('Unhandled line %r' % line)
                    data = match.groupdict()
                    logs.append(data)
                except:
                    pass
        return {
                'logs': logs,
                'date': date,
                'channel': channel,
                'channels' : channels}
    else:
        return {'date' : date,
                'channel':channel,
                'channels':channels}


text:
import styled from 'styled-components';
export default styled.div`
  ${props=>props.lang==='ar' ? 'float: right' : 'float: left'};
  text-align: left;
`;


text:
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from datetime import date
from dateutil.relativedelta import *
from email_template.email.email_template import *
from custom_form_app.forms.base_form_class import *
from account_app.models import *
from website.exceptions import *
import logging, sys

# force utf8 read data
reload(sys);
sys.setdefaultencoding("utf8")

# Get an instance of a logger
logger = logging.getLogger(__name__)

class ReportUserForm(forms.Form, FormCommonUtils):

    email = forms.CharField(label='La tua email', max_length=75, required=True)
    report_user_id = forms.IntegerField(required=True)
    report_text = forms.CharField(label='Dettagli segnalazione', max_length=1000, required=True, widget=forms.Textarea)

    # list of validator for this form
    custom_validation_list = (
        'check_all_fields_valid',
	'check_email_is_valid',
    )

    # list of addictional validator fied
    addictional_validation_fields = {
        "email":"email",
    }

    def __init__(self, *args, **kwargs):
        # parent forms.Form init
        super(ReportUserForm, self).__init__(*args, **kwargs)
        FormCommonUtils.__init__(self)

	# current form instance
        self.validation_form = super(ReportUserForm, self)

    def clean(self):
	super(ReportUserForm, self).clean_form_custom()
        return True

    def send_email(self):
        account_obj =  Account()
        return_var = False
        try:
            # retrieve report user data
            account_info = account_obj.custom_user_id_data(user_id=self.form_validated_data["report_user_id"])
        except User.DoesNotExist:
            # wtf: user id doesn't exists
            pass
        else:
            # send report user email
            email_context = {
                "email": self.form_validated_data["email"],
                "report_text": self.form_validated_data["report_text"],
                "report_user_id": self.form_validated_data["report_user_id"],
                "report_user_email": account_info["email"],
                "report_user_profile_url": settings.SITE_URL + "/passerella/dettaglio-utente/" + str(self.form_validated_data["report_user_id"]) + "/",
            }

            CustomEmailTemplate(
                email_name="report_user_email",
                email_context=email_context,
                template_type="user",
		email_from=self.form_validated_data["email"],
            )
            return_var = True

        return return_var

    def form_actions(self):
        """Function to update user email and password"""
        return_var = False
        if super(ReportUserForm, self).form_can_perform_actions():
            # send help mail
            if self.send_email():
                return_var = True

        return return_var


text:
using UnityEngine;
using System.Collections;

public class AddBuildingPickerButton : TouchableObject
{
    public GameObject buildingPickerBar;
    public GameObject content;
    public float normaledScaleFactor = 0.95f;
    private Vector3 touchScaleSize;
    private Vector3 untouchedScaleSize;

    bool isPickerOpened = false;

    void Start() {
        m_raycastCamera = GameObject.FindGameObjectWithTag("UICamera").GetComponent<Camera>();
        touchScaleSize = normaledScaleFactor * content.transform.localScale;
        untouchedScaleSize = content.transform.localScale;
        // Reset the picker position.
        buildingPickerBar.transform.position = new Vector3(Statics.buildingPickerSlideOutPosX,
                                                           buildingPickerBar.transform.position.y,
                                                           buildingPickerBar.transform.position.z);
    }

    protected override void OnTouch() {
        content.gameObject.transform.localScale = touchScaleSize;
    }

    protected override void OutTouch() {
        content.gameObject.transform.localScale = untouchedScaleSize;
    }

    protected override void TouchUp() {
        content.gameObject.transform.localScale = untouchedScaleSize;

        StartCoroutine(ButtonRotationAnimation());
    }

    protected override void Update() {
        base.Update();
    }

    float counter = 0.0f;
    float totalTime = 0.25f;
    IEnumerator ButtonRotationAnimation () {
        while(counter< totalTime) {
            counter += Time.deltaTime;
            float rotValue;
            float posValue;
            if (isPickerOpened) {
                rotValue = Mathf.Lerp(-45.0f, 0.0f, counter/totalTime);
                posValue = Mathf.Lerp(Statics.buildingPickerSlideInPosX,
                                      Statics.buildingPickerSlideOutPosX,
                                      counter/totalTime);

            } else {
                rotValue = Mathf.Lerp(0.0f, -45.0f, counter/totalTime);
                posValue = Mathf.Lerp(Statics.buildingPickerSlideOutPosX,
                                      Statics.buildingPickerSlideInPosX,
                                      counter/totalTime);
            }
            transform.rotation = Quaternion.Euler(new Vector3(0, 0, rotValue));
            buildingPickerBar.transform.position = new Vector3(posValue,
                                                               buildingPickerBar.transform.position.y,
                                                               buildingPickerBar.transform.position.z);
            yield return null;
        }
        isPickerOpened = !isPickerOpened;
        counter = 0.0f;
        yield return null;
    }
}


text: from RsCalibrator import *


text:
<!DOCTYPE html>

    <title>
        Truck
    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="style.css">

Tony's Fry Truck

Best food truck in town.

                    Metrics

                    Add Menu Item

Menu

Pork Belly Bao

$4.00

Fried Chicken Bao

$4.00

Kimchi Fries

$4.00

Having issues? Get in touch with us

                        2017 Copyright


text:
use crate::*;
use interner::Intern;
use lazy_static::lazy_static;

/// Return if the changes are safe to skip full rebuild,
/// doing the same check as our JS implmentation.
impl SchemaChange {
    pub fn is_safe(self: &SchemaChange, schema: &Schema) -> bool {
        match self {
            SchemaChange::None => true,
            SchemaChange::GenericChange => false,
            SchemaChange::DefinitionChanges(changes) => {
                for change in changes {
                    match change {
                        DefinitionChange::ObjectChanged {
                            changed,
                            added,
                            removed,
                            interfaces_added,
                            interfaces_removed,
                            ..
                        } => {
                            if !interfaces_added.is_empty()
                                || !interfaces_removed.is_empty()
                                || !is_field_changes_safe(added, removed, changed)
                            {
                                return false;
                            }
                        }
                        DefinitionChange::InterfaceChanged {
                            changed,
                            added,
                            removed,
                            ..
                        } => {
                            if !is_field_changes_safe(added, removed, changed) {
                                return false;
                            }
                        }
                        DefinitionChange::ObjectAdded(name) => {
                            if !is_object_add_safe(*name, schema) {
                                return false;
                            }
                        }
                        // safe changes
                        DefinitionChange::InterfaceAdded(_) => {}
                        DefinitionChange::ScalarAdded(_) => {}
                        DefinitionChange::EnumAdded(_) => {}
                        DefinitionChange::UnionAdded(_) => {}
                        DefinitionChange::InputObjectAdded(_) => {}
                        // unsafe changes
                        _ => {
                            return false;
                        }
                    }
                }
                true
            }
        }
    }
}

lazy_static! {
    static ref ID_FIELD_KEY: StringKey = "id".intern();
    static ref NODE_INTERFACE_KEY: StringKey = "Node".intern();
}

/// If the type has an `id` field and the type implments interfaces
/// other than `Node`, then the change isn't safe:
/// If the object type implements an `Actor` interfaces (for example).
/// We may need to add an inline spread with
///   ... on ThisNewType {
///     id
///   }
/// But we have a special case for `Node`. The `id` field is automatically
/// added to the selection for all types that implements `Node`.
fn is_object_add_safe(name: StringKey, schema: &Schema) -> bool {
    if let Type::Object(id) = schema.get_type(name).unwrap() {
        let object = schema.object(id);
        if object
            .fields
            .iter()
            .any(|id| schema.field(*id).name == *ID_FIELD_KEY)
            && object
                .interfaces
                .iter()
                .any(|id| schema.interface(*id).name != *NODE_INTERFACE_KEY)
        {
            return false;
        }
    } else {
        panic!("Object not found in the schema")
    }
    true
}

fn is_field_changes_safe(
    added: &[TypeChange],
    removed: &[TypeChange],
    changed: &[ArgumentChange],
) -> bool {
    if !removed.is_empty() {
        return false;
    }
    // Addition of non id field is safe
    if added.iter().any(|add| add.name == *ID_FIELD_KEY) {
        return false;
    }

    // Addition of optional field arg is safe
    for change in changed {
        if !change.removed.is_empty() {
            return false;
        }
        for add in &change.added {
            if let AstType::Named(_) = add.type_ {
            } else {
                return false;
            }
        }
    }
    true
}


text:
package JobDB::JobInfo;

use strict;
use warnings;
use MGRAST::Metadata;

1;

# this class is a stub, this file will not be automatically regenerated
# all work in this module will be saved

sub populate_job {
  my ($self, $job) = @_;

  my $master    = $self->_master();
  my $coords    = $job->lat_lon;
  my $job_stats = $job->stats;
  my $attribs   = { job => $job };

  $attribs->{project_name}  = $job->primary_project->name if $job->primary_project;
  $attribs->{project_pi}    = $job->primary_project->pi if $job->primary_project;
  $attribs->{sequence_type} = $job->seq_type if $job->seq_type;
  $attribs->{sequence_tech} = $job->seq_method if $job->seq_method;
  $attribs->{latitude}      = $coords->[0] if @$coords;
  $attribs->{longitude}     = $coords->[1] if @$coords;
  $attribs->{country}       = $job->country if $job->country;
  $attribs->{location}      = $job->location if $job->location;
  $attribs->{biome}         = $job->biome if $job->biome;
  $attribs->{feature}       = $job->feature if $job->feature;
  $attribs->{material}      = $job->material if $job->material;
  $attribs->{env_package}   = $job->env_package_type if $job->env_package_type;
  $attribs->{bp_count}      = $job_stats->{bp_count_raw} if $job_stats->{bp_count_raw};
  $attribs->{seq_count}     = $job_stats->{sequence_count_raw} if $job_stats->{sequence_count_raw};
  $attribs->{avg_len}       = $job_stats->{average_length_raw} if $job_stats->{average_length_raw};
  $attribs->{drisee}        = $job_stats->{drisee_score_raw} if $job_stats->{drisee_score_raw};
  $attribs->{alpha_diverse} = $job_stats->{alpha_diversity_shannon} if $job_stats->{alpha_diversity_shannon};

  $master->JobInfo->create($attribs);
}


text:
"""Set of utilities to add commands to a buildbot factory.

This is based on commands.py and adds chromium-specific commands."""

from buildbot.steps import shell

from master.factory import commands

class OmahaCommands(commands.FactoryCommands):
  """Encapsulates methods to add omaha commands to a buildbot factory."""

  def __init__(self, factory=None, target=None, build_dir=None,
               target_platform=None, target_arch=None,
               shard_count=1, shard_run=1, shell_flags=None, isolates=False):

    commands.FactoryCommands.__init__(self, factory, target, build_dir,
                                      target_platform)

    self._omaha_script_dir = self.PathJoin(self._script_dir, 'omaha')
    self._hammer_tool = self.PathJoin(self._omaha_script_dir, 'hammer.py')

  def AddHammer(self, target=None, options=None):
    options = options or []
    cmd = [self._hammer_tool,
           '--target', target]
    cmd.extend(options)

    self.AddTestStep(shell.ShellCommand, 'Hammer', cmd, timeout=3600)


text:
<?xml version="1.0" encoding="UTF-8"?>
<database>
    <table name="m_template_m_templatemappers">
        <comment>table explaination</comment>
        <field name="m_template_id" key="MUL" type="bigint(20)">
            <comment>field explaination</comment>
        </field>
        <field name="mappers_id" key="PRI" type="bigint(20)">
            <comment>field explaination</comment>
        </field>
    </table>
</database>


text:
import React from 'react';
import { shallow } from 'enzyme';

describe('test/app/web/Routes.test.js', () => {
  let Routes;

  beforeAll(() => {
    jest.mock('assets/images/loading.gif', () => 'mockLoading');
    Routes = require('web/Routes').default; // eslint-disable-line
  });

  it('Render: props: null', () => {
    const wrapper = shallow(<Routes />);
    expect(wrapper).toMatchSnapshot();
  });
});


text:
import { Method } from './util/Method';
import { Pair } from './util/Pair';
export declare class FormContainer {
    method: Method;
    baseUrl: string;
    actionUrl: string;
    nameValuePairs: Pair<string, string>[];
    requestId: string;
    constructor(method: Method, baseUrl: string, actionUrl: string, nameValuePairs: Pair<string, string>[], requestId: string);
    getAction(): string;
}


text:
package io.pivotal.pccpizza.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;

@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class Customer implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    private String firstName;

    private String lastName;

    private String email;

    private String address;

    public Customer() {}

    public Customer(String firstName, String lastName, String email, String address) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.address = address;
    }

    public long getId() {
        return id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="WATCH PART 2 HERE: https://vimeo.com/94747106 | PART 3: https://vimeo.com/95647770 | PART 4: https://vimeo.com/98352797 License the footage here: https://app.nimia.com/collections/3703/new-zealand-timelapse-ultimate-collection Part…">
    <meta name="author" content="Jacob Fulton Buckle">
    <link rel="icon" href="/favicon.ico">
    <link rel="apple-touch-icon" sizes="120x120" href="/touch-icon-iphone-retina.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/touch-icon-ipad-retina.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/touch-icon-iphone-6-plus.png">

    <title>Sintel - Third Open Movie by Blender Foundation</title>

    <link href="../css/bootstrap.min.css" rel="stylesheet">

    <link href="../css/base.css" rel="stylesheet">

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

                <svg class="masthead-brand" height="64" width="64" viewBox="0 0 114 114" version="1.1">
                  <rect stroke-dashoffset="0" height="110" width="110" stroke="#3d3d62" stroke-dasharray="none" stroke-miterlimit="4" y="2" x="2" stroke-width="4" fill="none"/>
                  <path stroke-linejoin="miter" d="m12,12,0,80,10,0,0,10,10,0,10-10,0-20,20,0,10-10,0-10-30,0,0-20,60,0,0-20z" stroke="#3d3d62" stroke-linecap="butt" stroke-miterlimit="4" stroke-dasharray="none" stroke-width="2" fill="none"/>
                  <path fill="#3d3d62" d="m12,12,0,70,10,0,0,10,20,0,0-20,20,0,10-10,0-10-30,0,0-20,60,0,0-20z"/>
                </svg>

Home

About

Contact

            <button type="button" class="btn btn-primary btn-xs" data-toggle="videoSize">Toggle video size</button>

Download progress

Sintel - Third Open Movie by Blender Foundation Blender Foundation

Help us making Free/Open Movies: https://cloud.blender.org/join

"Sintel" is an independently produced short film, initiated by the Blender Foundation as a means to further improve and validate the free/open source 3D creation suite Blender. With initial funding provided by 1000s of donations via the internet community, it has again proven to be a viable development model for both open 3D technology as for independent animation film.

This 15 minute film has been realized in the studio of the Amsterdam Blender Institute, by an international team of artists and developers. In addition to that, several crucial technical and creative targets have been realized online, by developers and artists and teams all over the world.

www.sintel.org

AWAKENING | NEW ZEALAND 4K

AMPLITUDE | NEW ZEALAND 4K

SOLITUDE | NEW ZEALAND 4K

AGITATION | NEW ZEALAND 4K

Cityscape Chicago

Cityscape Chicago II

Yosemite HD

Yosemite HD II

Clockwork 4 - NikkyyHD [CS:GO]

Kim Dotcom - Good Life

Kim Dotcom - Party Amplifier

TIMEDRIFT | ALPINE 4K TIMELAPSE

© 2020 Fastcast. Powered by WebTorrent.


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta name="author" content="Daniel Fernandez">
		<meta name="description" content="Hugo testing">
		<meta name="generator" content="Hugo 0.15" />
		<title>about · dfr</title>
		<link rel="shortcut icon" href="http://blayhem.github.io/blog/images/favicon.ico">
		<link rel="stylesheet" href="http://blayhem.github.io/blog/css/style.css">
		<link rel="stylesheet" href="http://blayhem.github.io/blog/css/highlight.css">
		<link rel="stylesheet" href="http://blayhem.github.io/blog/css/monosocialiconsfont.css">

		 ←Home

about

December 24, 2015

My name is Daniel Fernandez Rico, and I’m a Computer Science student in Madrid. I enjoy both programming and design.
You can find me in the links at the bottom of the page, or send me an email.

This blog is an experiment to work with Hugo -the website framework-, together with VIM editing, Github Pages and HTML/CSS design.

                            Daniel Fernandez

                     Tweet

 Share

Read more

            Visualizing Data with PynetDec 31

            Under ConstructionDec 25

            Press StartDec 24

            Hello WorldDec 24

        circlefacebook

        circlegithub

        circletwitterbird

        © Copyright 2016 Daniel Fernandez


text:
using System;
using System.Collections.Generic;
using System.Text;
using XenAdmin.Core;
using XenAPI;

namespace XenAdmin.Actions
{
    public class RescanPIFsAction : AsyncAction
    {
        public RescanPIFsAction(Host h)
            : base(h.Connection, string.Format(Messages.ACTION_PIF_SCAN_TITLE, Helpers.GetName(h)), Messages.ACTION_PIF_SCAN_START_DESC, false)
        {
            Host = h;
            #region RBAC Dependencies
            ApiMethodsToRoleCheck.Add("pif.scan");
            #endregion
        }

        protected override void Run()
        {
            PercentComplete = 40;
            PIF.scan(Session, Host.opaque_ref);
            Description = Messages.COMPLETED;
            PercentComplete = 100;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Simple_FTP_Client
{
    /// <summary>
    /// The class with the methods which handle all the interactions with the user
    /// </summary>
    class UserInteraction
    {
        // User interaction methods

        /// <summary>
        /// Prints all the available commands
        /// </summary>
        public static void Help()
        {
            Console.WriteLine("The available commands are: \n Upload File \n Download File \n Get files in dir \n Download all files in dir \n Enable logging \n Disable logging \n Write log to file \n Help");
        }

        public static void Exit()
        {
            if (Program.Logging == true)
            {
                // Write the log to the file
                Log.WriteLogToFile();

                // Wait for 500 miliseconds, I'm not sure why but the code doesn't work properly without it.
                System.Threading.Thread.Sleep(500);
            }

            // Actually exit the program
            Environment.Exit(0);
        }

        /// <summary>
        /// Gets the variables needed from the user to create a FTP object
        /// </summary>
        public static void GetStartVariables()
        {
            if (File.Exists("Credentials"))
            {
                CredentialsHandling.LoadCredentials();
            }
            else
            {
                Console.Write("Username = ");
                string username = Console.ReadLine();

                Console.Write("Password = ");
                string password = Console.ReadLine();

                Program.username = username;
                Program.password = password;
            }

            Console.Write("FTP Server = ");
            string ftpServer = Console.ReadLine();

            Program.ftpServer = ftpServer;
        }

        /// <summary>
        /// Gets the variables for the UploadFile method and then calls it.
        /// </summary>
        public static void GetVariablesForUploadFile(bool silent)
        {
            // First get the variable
            Console.Write("File = ");
            string filePath = Console.ReadLine();

            // Call the UploadFile method
            Program.ftp.UploadFile(filePath, silent);
        }

        /// <summary>
        /// Gets the variables for the DownloadFile method and then calls it.
        /// </summary>
        public static void GetVariablesForDownloadFile(bool silent)
        {
            // First get the variables
            Console.Write("Filename on FTP Server = ");
            string ftpServerFileName = Console.ReadLine();

            Console.Write("Local Filename = ");
            string localFileName = Console.ReadLine();

            // Call the DownloadFile method
            Program.ftp.DownloadFile(Program.ftpServer + "/" + ftpServerFileName, localFileName, silent);
        }

        /// <summary>
        /// Get the variables to call GetFilesInDir and then print the returned values
        /// </summary>
        public static void PrintAllFilesInDir(bool silent)
        {
            // First get the variable directoryOnServer
            Console.Write("Folder on server = ");
            string directoryOnServer = Console.ReadLine();

            // Call the method and store the return variables
            string[] FilesInDir = Program.ftp.GetFilesInDir(Program.ftpServer + "/" + directoryOnServer, silent);

            // Print out the contents of the FilesInDir array
            foreach (string file in FilesInDir)
            {
                Console.WriteLine(file);
            }
        }

        /// <summary>
        /// Downloads all the files in one dir on the FTP server
        /// </summary>
        /// <param name="silent"></param>
        public static void DownloadAllFilesInDir(bool silent)
        {
            // First get the variables
            Console.Write("Folder on server = ");
            string directoryOnServer = Console.ReadLine();

            // Call the FilesInDir method to see which files are in the dir, and save them in a stringp[]
            string[] filesInDir = Program.ftp.GetFilesInDir(Program.ftpServer + "/" + directoryOnServer, silent);

            // Create a new local dir if it doesn't exists already
            if (!(Directory.Exists("/" + directoryOnServer)))
            {
                Directory.CreateDirectory(directoryOnServer);
                Console.WriteLine("Created new dir...");
            }

            // Foreach file in the folder, download it
            foreach (string file in filesInDir)
            {
                // Print which file is going to be uploaded
                Console.WriteLine("    File : " + file);

                // Make a FTP File address
                string ftpFileAddress = Program.ftpServer + "/" + file;

                // Download the file
                Program.ftp.DownloadFile(ftpFileAddress, file, silent);
            }
        }

        /// <summary>
        /// Uploads one local folder, including it's content to a FTP server
        /// </summary>
        /// <param name="silent"></param>
        public static void UploadLocalFolder(bool silent)
        {
            // First get the variable localFolder
            Console.Write("Folder = ");
            string localFolder = Console.ReadLine();

            // Get the contents of the LocalFolder
            string[] FilesInLocalFolder = Directory.GetFiles(localFolder);

            // Foreach file in the local folder, upload it
            foreach (string File in FilesInLocalFolder)
            {
                // Print which file is going to be uploaded
                Console.WriteLine("    File : " + File);

                // Upload the file
                Program.ftp.UploadFile(File, silent);
            }
        }
    }
}