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

/**
 *
 * @author Josy
 */
public class Mineracao extends javax.swing.JFrame {

    /**
     * Creates new form Mineracao
     */
    public Mineracao() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 736, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 555, Short.MAX_VALUE)
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

//    /**
//     * @param args the command line arguments
//     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(Mineracao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(Mineracao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(Mineracao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(Mineracao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new Mineracao().setVisible(true);
//            }
//        });
//    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}


text:
<?php

//FIXME Is this even needed since we are using the custom PDOStatement?

redpajama_set_name: RedPajamaGithub


text:
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.twilio.jwt.client.ClientCapability;
import com.twilio.jwt.client.IncomingClientScope;
import com.twilio.jwt.client.Scope;

public class TwilioServlet extends HttpServlet {

  // Get your Account SID and Auth Token from https://twilio.com/console
  // To set up environment variables, see http://twil.io/secure
  public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
  public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    List<Scope> scopes = Lists.newArrayList(new IncomingClientScope("joey"));

    ClientCapability capability = new ClientCapability.Builder(ACCOUNT_SID, AUTH_TOKEN)
      .scopes(scopes)
      .build();

    String token = capability.toJwt();

    response.setContentType("application/jwt");
    response.getWriter().print(token);
  }
}


text:
declare const ContentItemsMixin: StateMixin<
  {},
  {},
  {},
  {
    items: ListItemElement[];
  }
>;

export default ContentItemsMixin;


text:
using System.Web;
using System.Web.Optimization;

namespace AppGamer
{
    public class BundleConfig
    {
        // Para obter mais informações sobre o agrupamento, visite https://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use a versão em desenvolvimento do Modernizr para desenvolver e aprender. Em seguida, quando estiver
            // pronto para a produção, utilize a ferramenta de build em https://modernizr.com para escolher somente os testes que precisa.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}


text:
package dpm.lejos.test;

import dpm.lejos.Lab3Code.Vector;
import junit.framework.TestCase;

/**
 * Unit tests for the Vector type
 */
public class VectorTest extends TestCase {

    public void testGetMagnitude() throws Exception {
        Vector vector = new Vector(10, Math.PI);

        assertEquals(10.0, vector.getMagnitude(), 0.001);
    }

    public void testGetOrientation() throws Exception {
        Vector vector = new Vector(10, Math.PI);

        assertEquals(Math.PI, vector.getOrientation(), 0.001);
    }

    public void testSetMagnitude() throws Exception {
        Vector vector = new Vector();
        vector.setMagnitude(10);
        assertEquals(10.0, vector.getMagnitude(), 0.001);
    }

    public void testSetOrientation() throws Exception {
        Vector vector = new Vector();
        vector.setOrientation(Math.PI);
        assertEquals(Math.PI, vector.getOrientation(), 0.001);
    }

    public void testToCartesian() throws Exception {
        Vector vector = new Vector(Math.sqrt(2),Math.PI/4);
        double[] coords = vector.toCartesian();

        assertEquals(coords[0], 1.0, 0.001);
        assertEquals(coords[1], 1.0, 0.001);
    }
}


text:
import styled from 'styled-components'

import Img from '@/Img'
import css, { theme } from '@/utils/css'

export const Wrapper = styled.div`
  ${css.flex()};
  width: 100%;
  min-height: 160px;
  color: ${theme('thread.articleTitle')};
  margin-top: 30px;
`

const Block = styled.div`
  ${css.flexColumn('justify-between')};
  padding: 16px;
  padding-right: 10px;
  background: ${theme('haveADrinkPage.bg')};
  border-radius: 5px;
  border: 1px solid;
  border-color: transparent;

  &:hover {
    border-color: #074c61;
  }
`
export const AboutBlock = styled(Block)`
  width: 250px;
  margin-right: 18px;
`
export const ContributorBlock = styled(Block)`
  width: calc(100% - 500px);
`
export const ContributorsWrapper = styled.div`
  ${css.flex()};
  margin-top: -35px;
`
export const Avatar = styled(Img)`
  ${css.size(20)};
  margin-right: 10px;
  border-radius: 100%;
`
export const Desc = styled.div`
  margin-top: -10px;
  opacity: 0.6;

  ${Block}:hover & {
    opacity: 0.8;
  }
  transition: opacity 0.2s;
`


text:
package com.all.client.services.delegates;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.all.appControl.control.ControlEngine;
import com.all.client.model.LocalFolder;
import com.all.client.model.LocalModelDao;
import com.all.client.model.LocalModelFactory;
import com.all.client.model.LocalPlaylist;
import com.all.client.services.MusicEntityService;
import com.all.core.events.ContainerModifiedEvent;
import com.all.core.events.ErrorMessageEvent;
import com.all.core.events.Events;
import com.all.core.model.Model;
import com.all.event.ValueEvent;
import com.all.i18n.Messages;
import com.all.shared.model.Folder;
import com.all.shared.model.ModelCollection;
import com.all.shared.model.ModelTypes;
import com.all.shared.model.Playlist;
import com.all.shared.model.Root;
import com.all.shared.model.SmartPlaylist;
import com.all.shared.model.Track;
import com.all.shared.model.TrackContainer;

@Service
public class MoveDelegate {
	private static final String PLAYLIST_DEFAULT_NEW_NAME = "playlist.defaultNewName";

	@Autowired
	private LocalModelDao modelDao;
	@Autowired
	private LocalModelFactory modelFactory;
	@Autowired
	private ControlEngine controlEngine;
	@Autowired
	private MusicEntityService musicEntityService;
	@Autowired
	private Messages messages;

	public ModelCollection doMove(ModelCollection content, TrackContainer destination) {
		if (!(destination instanceof Root) && !(destination instanceof Playlist) && !(destination instanceof Folder)
				&& (destination instanceof SmartPlaylist && !((SmartPlaylist) destination).dropAllowed())) {
			throw new RuntimeException("Invalid destination " + destination.getClass().getName());
		}
		String playlistBasename = messages.getMessage(PLAYLIST_DEFAULT_NEW_NAME);
		Root destinationRoot = controlEngine.get(Model.USER_ROOT);
		if (content.isRemote()) {
			content = modelFactory.doRelocate(content);
		}
		if (destination instanceof Folder) {
			if (content.only(ModelTypes.playlists, ModelTypes.tracks)) {
				for (final Playlist playlist : content.getPlaylists()) {
					Folder parentFolder = (Folder) destination;
					if (parentFolder.getPlaylists().size() >= Folder.MAX_PLAYLIST_ALLOWED) {
						controlEngine.fireEvent(Events.Errors.ERROR_MESSAGE, new ErrorMessageEvent("playlist.maxAllowed", "a Folder", ""
								+ Folder.MAX_PLAYLIST_ALLOWED));
						controlEngine.fireEvent(Events.Library.TREE_STRUCTURE_CHANGED, new ValueEvent<Root>(destinationRoot));
						return content;
					}
					((LocalFolder) parentFolder).add(playlist);
				}
				if (content.has(ModelTypes.tracks)) {

					Playlist playlist = LocalPlaylist.createUntitledPlaylist(((LocalFolder) destination).getPlaylists(), playlistBasename);
					((LocalFolder) destination).add(playlist);
					for (Track track : content.getTracks()) {
						((LocalPlaylist) playlist).add(track);
					}
					modelDao.update(playlist);
				}
				modelDao.update(((Folder) destination));
				controlEngine.fireEvent(Events.Library.FOLDER_UPDATED, new ValueEvent<Folder>((Folder) destination));
			}
		} else if (destination instanceof Playlist) {
			if (content.only(ModelTypes.tracks)) {
				for (Track track : content.getTracks()) {
					((LocalPlaylist) destination).add(track);
				}
				modelDao.update(((Playlist) destination));
			}
		} else {
			if (content.only(ModelTypes.playlists)) {
				for (Playlist playlist : content.getPlaylists()) {
					musicEntityService.moveTo(playlist, null);
				}
			}
		}
		controlEngine.fireEvent(Events.Library.TREE_STRUCTURE_CHANGED, new ValueEvent<Root>(destinationRoot));
		// controlEngine.fireEvent(Events.Library.CONTAINER_MODIFIED, new ContainerModifiedEvent(null));
		controlEngine.fireEvent(Events.Library.CONTAINER_MODIFIED, new ContainerModifiedEvent(destination));
		return content;
	}

	public Track relocate(Track track) {
		return modelFactory.relocateTrack(track);
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Reading/Writing a noise covariance matrix — MNE 0.22.1 documentation</title>
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../../_static/graphviz.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/bootstrap_divs.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-binder.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-dataframe.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-rendered-html.css" />

    <link rel="shortcut icon" href="../../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />

    <link rel="canonical" href="https://mne.tools/stable/index.html" />

    <link rel="stylesheet" href="../../_static/style.css " type="text/css" />
    <link rel="stylesheet" href="../../_static/font-awesome.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/font-source-code-pro.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/font-source-sans-pro.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/flag-icon.css" type="text/css" />

<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.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

        0.22.1

Install

Overview

Tutorials

Examples

Glossary

API

              More

 GitHub

 Get help

 Contribute

 Cite MNE

              <button type="button" class="btn btn-primary btn-sm navbar-btn dropdown-toggle" id="dLabelMore" data-toggle="dropdown" style="margin-left: 10px">
              v0.22.1

            </button>

Development

v0.22 (stable)

v0.21

v0.20

v0.19

v0.18

v0.17

v0.16

v0.15

v0.14

v0.13

v0.12

v0.11

<form class="navbar-form navbar-right" action="../../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Note

Click here
to download the full example code

Reading/Writing a noise covariance matrix¶

Plot a noise covariance matrix.

# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)

from os import path as op
import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()
fname_cov = op.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif')
fname_evo = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')

cov = mne.read_cov(fname_cov)
print(cov)
evoked = mne.read_evokeds(fname_evo)[0]

Out:

    366 x 366 full covariance (kind = 1) found.
    Read a total of 4 projection items:
        PCA-v1 (1 x 102) active
        PCA-v2 (1 x 102) active
        PCA-v3 (1 x 102) active
        Average EEG reference (1 x 60) active
<Covariance | size : 366 x 366, n_samples : 15972, data : [[ 2.27235589e-23  4.79818505e-24  7.12852747e-25 ...  4.85348042e-18
   2.02846360e-18  8.26727393e-18]
 [ 4.79818505e-24  5.33468523e-24  1.80261790e-25 ...  2.33583009e-19
  -6.93161055e-19  2.35199238e-18]
 [ 7.12852747e-25  1.80261790e-25  5.79073915e-26 ...  1.09498615e-19
   6.16924072e-21  2.93873875e-19]
 ...
 [ 4.85348042e-18  2.33583009e-19  1.09498615e-19 ...  1.40677185e-11
   1.27444183e-11  1.08634620e-11]
 [ 2.02846360e-18 -6.93161055e-19  6.16924072e-21 ...  1.27444183e-11
   1.59818134e-11  8.51070563e-12]
 [ 8.26727393e-18  2.35199238e-18  2.93873875e-19 ...  1.08634620e-11
   8.51070563e-12  1.53708918e-11]]>
Reading /home/circleci/mne_data/MNE-sample-data/MEG/sample/sample_audvis-ave.fif ...
    Read a total of 4 projection items:
        PCA-v1 (1 x 102) active
        PCA-v2 (1 x 102) active
        PCA-v3 (1 x 102) active
        Average EEG reference (1 x 60) active
    Found the data of interest:
        t =    -199.80 ...     499.49 ms (Left Auditory)
        0 CTF compensation matrices available
        nave = 55 - aspect type = 100
Projections have already been applied. Setting proj attribute to True.
No baseline correction applied
    Read a total of 4 projection items:
        PCA-v1 (1 x 102) active
        PCA-v2 (1 x 102) active
        PCA-v3 (1 x 102) active
        Average EEG reference (1 x 60) active
    Found the data of interest:
        t =    -199.80 ...     499.49 ms (Right Auditory)
        0 CTF compensation matrices available
        nave = 61 - aspect type = 100
Projections have already been applied. Setting proj attribute to True.
No baseline correction applied
    Read a total of 4 projection items:
        PCA-v1 (1 x 102) active
        PCA-v2 (1 x 102) active
        PCA-v3 (1 x 102) active
        Average EEG reference (1 x 60) active
    Found the data of interest:
        t =    -199.80 ...     499.49 ms (Left visual)
        0 CTF compensation matrices available
        nave = 67 - aspect type = 100
Projections have already been applied. Setting proj attribute to True.
No baseline correction applied
    Read a total of 4 projection items:
        PCA-v1 (1 x 102) active
        PCA-v2 (1 x 102) active
        PCA-v3 (1 x 102) active
        Average EEG reference (1 x 60) active
    Found the data of interest:
        t =    -199.80 ...     499.49 ms (Right visual)
        0 CTF compensation matrices available
        nave = 58 - aspect type = 100
Projections have already been applied. Setting proj attribute to True.
No baseline correction applied

Show covariance

cov.plot(evoked.info, exclude='bads', show_svd=False)

Total running time of the script: ( 0 minutes  2.775 seconds)

Estimated memory usage:  8 MB

Download Python source code: plot_read_noise_covariance_matrix.py

Download Jupyter notebook: plot_read_noise_covariance_matrix.ipynb

Gallery generated by Sphinx-Gallery

© Copyright 2012-2021, MNE Developers. Last updated <time datetime="2021-04-02T17:37:54.428702+00:00" class="localized">2021-04-02 17:37 UTC</time>


text:
require 'spec_helper'

require 'puppet/resource/type_collection_helper'

class RTCHelperTester
  include Puppet::Resource::TypeCollectionHelper
end

describe Puppet::Resource::TypeCollectionHelper do
  before do
    @helper = RTCHelperTester.new
  end

  it "should use its current environment to retrieve the known resource type collection" do
    env = stub 'environment'
    @helper.expects(:environment).returns env

    rtc = stub 'known_resource_types'
    env.expects(:known_resource_types).returns  rtc

    @helper.known_resource_types.should equal(rtc)
  end
end


text:
#ifndef LINGVO_CORE_OPS_ROPE_H_
#define LINGVO_CORE_OPS_ROPE_H_

#include <string>

namespace tensorflow {
namespace lingvo {

class Rope : public std::string {
 public:
  Rope() = default;
  Rope(const std::string& s) : std::string(s) {}
  Rope(std::string&& s) : std::string(std::move(s)) {}

  void AppendTo(std::string* dst) const {
    dst->append(*this);
  }

  std::string ToString() const { return *this; }
};

}  // namespace lingvo
}  // namespace tensorflow

#endif  // LINGVO_CORE_OPS_ROPE_H_


text:
require File.expand_path('../../spec_helper', __FILE__)

describe 'XCRes::Analyzer' do

  def subject
    XCRes::Analyzer
  end

  before do
    @target = app_target
    @analyzer = subject.new(@target)
  end

  describe '#new_section' do
    describe 'without configured options' do
      describe 'without options given as argument' do
        it 'should return a new section' do
          @analyzer.new_section('Name', { a: 'a' })
            .should.be.eql? XCRes::Section.new('Name', { a: 'a' })
        end
      end

      describe 'with options given as argument' do
        it 'should return a new section' do
          @analyzer.new_section('Name', { a: 'a' }, the_answer: 42)
            .should.be.eql? XCRes::Section.new('Name', { a: 'a' }, the_answer: 42)
        end
      end
    end

    describe 'with configured options' do
      before do
        @analyzer.options = { the_answer: 42, the_question: '6x7=?' }
      end

      describe 'without options given as argument' do
        it 'should return a new section' do
          @analyzer.new_section('Name', { a: 'a' })
            .should.be.eql? XCRes::Section.new('Name', { a: 'a' }, the_answer: 42,  the_question: '6x7=?')
        end
      end

      describe 'with options given as argument' do
        it 'should return a new section' do
          @analyzer.new_section('Name', { a: 'a' }, the_answer: 21)
            .should.be.eql? XCRes::Section.new('Name', { a: 'a' }, the_answer: 21, the_question: '6x7=?')
        end
      end
    end
  end

  describe '#filter_exclusions' do
    describe 'single asterisk' do
      it 'rejects file paths on first hierarchy level' do
        @analyzer.exclude_file_patterns = ['*.gif']
        @analyzer.filter_exclusions(['cat.jpg', 'doge.gif']).should.be.eql?(['cat.jpg'])
      end

      it 'rejects file paths in nested directories by default' do
        @analyzer.exclude_file_patterns = ['*.gif']
        @analyzer.filter_exclusions(['top_doge.gif', 'sub/sub/doge.gif', 'sub/sub/doge.gif']).should.be.eql?([])
      end
    end

    describe 'double asterisk' do
      it 'rejects file paths in nested directories only' do
        @analyzer.exclude_file_patterns = ['**.gif']
        @analyzer.filter_exclusions(['top_doge.gif', 'sub/sub/doge.gif', 'sub/sub/doge.gif']).should.be.eql?([])
      end
    end

    it 'rejects hidden files' do
      @analyzer.exclude_file_patterns = ['.git']
      @analyzer.filter_exclusions(['.git']).should.be.eql?([])
    end
  end

  describe '#find_files_by_extname' do
    it 'should return an empty list for an empty project' do
      @analyzer.project.stubs(:files).returns([])
      @analyzer.find_file_refs_by_extname('.bundle').should.be.eql?([])
    end

    it 'should return matching files' do
      @bundle = stub('FileRef', path: 'the-whole.bundle')
      @img    = stub('FileRef', path: 'awesome.jpg')
      @target.project.stubs(:files).returns([@bundle, @img])

      @analyzer.stubs(:is_file_ref_included_in_application_target?)
        .returns(true)
      @analyzer.find_file_refs_by_extname('.bundle').should.be.eql?([@bundle])
    end

    it 'should not return files, which do not belong to an application target' do
      @dog_img = stub('FileRef', path: 'doge.jpg')
      @cat_img = stub('FileRef', path: 'nyancat.jpg')
      @target.project.stubs(:files).returns([@dog_img, @cat_img])

      @analyzer.stubs(:is_file_ref_included_in_application_target?)
        .with(@dog_img).returns(true)
      @analyzer.stubs(:is_file_ref_included_in_application_target?)
        .with(@cat_img).returns(false)
      @analyzer.find_file_refs_by_extname('.jpg').should.be.eql?([@dog_img])
    end
  end

  describe '#is_file_ref_included_in_application_target?' do
    it 'should return true for included files' do
      file = @target.project.files.find { |f| f.path.to_s == 'doge.jpeg' }
      file.should.be.an.instance_of?(Xcodeproj::Project::Object::PBXFileReference)
      @analyzer.is_file_ref_included_in_application_target?(file)
        .should.be.true?
    end

    it 'should return false for non-included files' do
      file = @target.project.files.find { |f| f.path.to_s == 'nyanCat.png' }
      file.should.be.an.instance_of?(Xcodeproj::Project::Object::PBXFileReference)
      @analyzer.is_file_ref_included_in_application_target?(file)
        .should.be.false?
    end
  end

end


text:
Sinatra/Bulma Barebones
=========================

To bootstrap a web app project.


text:
<?php

namespace LeDjassa\AdsBundle\Model;

use LeDjassa\AdsBundle\Model\om\BaseUserPeer;

class UserPeer extends BaseUserPeer
{
}


text:
@interface NIMImageContentConfig : NSObject<NIMSessionContentConfig>

@end


text:
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _

def signup_domain_validator(value):
    if '*' in settings.ALLOWED_SIGNUP_DOMAINS:
        return

    domain = value[value.index("@"):]

    if domain not in settings.ALLOWED_SIGNUP_DOMAINS:
        allowed_domain = ','.join(settings.ALLOWED_SIGNUP_DOMAINS)
        msg = _('Invalid domain. '
                'Allowed domains on this network: {0}').format(allowed_domain)
        raise ValidationError(msg)

def forbidden_username_validator(value):
    forbidden_usernames = {
        'admin', 'settings', 'news', 'about', 'help', 'signin', 'signup',
        'signout', 'terms', 'privacy', 'cookie', 'new', 'login', 'logout',
        'administrator', 'join', 'account', 'username', 'root', 'blog',
        'user', 'users', 'billing', 'subscribe', 'reviews', 'review', 'blog',
        'blogs', 'edit', 'mail', 'email', 'home', 'job', 'jobs', 'contribute',
        'newsletter', 'shop', 'profile', 'register', 'auth', 'authentication',
        'campaign', 'config', 'delete', 'remove', 'forum', 'forums',
        'download', 'downloads', 'contact', 'blogs', 'feed', 'feeds', 'faq',
        'intranet', 'log', 'registration', 'search', 'explore', 'rss',
        'support', 'status', 'static', 'media', 'setting', 'css', 'js',
        'follow', 'activity', 'questions', 'articles', 'network', }
    if value.lower() in forbidden_usernames:
        raise ValidationError(_('This is a reserved word.'))

def invalid_username_validator(value):
    if '@' in value or '+' in value or '-' in value:
        raise ValidationError(_('Enter a valid username.'))

def unique_email_validator(value):
    if User.objects.filter(email__iexact=value).exists():
        raise ValidationError(_('User with this Email already exists.'))

def unique_username_ignore_case_validator(value):
    if User.objects.filter(username__iexact=value).exists():
        raise ValidationError(_('User with this Username already exists.'))

class SignUpForm(forms.ModelForm):
    username = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=30,
        required=True,
        label=_('Username'),
        help_text=_('Usernames may contain alphanumeric, _ and . characters'))
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label=_('Password'))
    confirm_password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label=_('Confirm your password'),
        required=True)
    email = forms.CharField(
        widget=forms.EmailInput(attrs={'class': 'form-control'}),
        required=True,
        max_length=75,
        label=_('Email'))

    class Meta:
        model = User
        exclude = ['last_login', 'date_joined']
        fields = ['username', 'email', 'password', 'confirm_password', ]

    def __init__(self, *args, **kwargs):
        super(SignUpForm, self).__init__(*args, **kwargs)
        self.fields['username'].validators += [
            forbidden_username_validator, invalid_username_validator,
            unique_username_ignore_case_validator
        ]
        self.fields['email'].validators += [
            unique_email_validator, signup_domain_validator]

    def clean(self):
        super(SignUpForm, self).clean()
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if password and password != confirm_password:
            self._errors['password'] = self.error_class(
                [_('Passwords don\'t match')])
        return self.cleaned_data


text:
__author__ = 'ipetrash'

from PySide.QtGui import *

class UndoCommand(QUndoCommand):
    """
    Class which provides undo/redo actions
    """

    def __init__(self, canvas, parent=None):
        super().__init__(parent)

        self.mPrevImage = canvas.image.copy()
        self.mCurrImage = canvas.image.copy()
        self.canvas = canvas

    def undo(self):
        # TODO: проверить и реализовать clearSelection
        # self.canvas.clearSelection()
        self.mCurrImage = self.canvas.image.copy()
        self.canvas.image = self.mPrevImage
        self.canvas.update()
        # TODO: проверить и реализовать saveImageChanges
        # self.canvas.saveImageChanges()

    def redo(self):
        self.canvas.image = self.mCurrImage
        self.canvas.update()
        # TODO: проверить и реализовать saveImageChanges
        # self.canvas.saveImageChanges()


text:
package com.garrapeta.jumplings.game.scenario;

import android.graphics.Bitmap;

import com.garrapeta.gameengine.BitmapManager;
import com.garrapeta.jumplings.R;
import com.garrapeta.jumplings.game.JumplingsWorld;

/**
 *
 * Nature scenario
 *
 * @author GaRRaPeTa
 */
public class JungleScenario extends LayerScenario {

    private final static int LAYER1_ID = R.drawable.scenario_jungle_1;
    private final static int LAYER2_ID = R.drawable.scenario_jungle_2;
    private final static int LAYER3_ID = R.drawable.scenario_jungle_3;
    private final static int LAYER4_ID = R.drawable.scenario_jungle_4;

    // ----------------------------------------------- Constructor

    /**
     * @param dWorld
     */
    JungleScenario(JumplingsWorld world) {
        super(world);
    }

    @Override
    public void initLayers(BitmapManager bm) {
        int viewWidth = mWorld.mGameView.getWidth();
        int viewHeight = mWorld.mGameView.getHeight();

        // Initialisation of Layers
        {
            // TODO: avoid blocking game thread with this load
            Bitmap bmp = bm.loadBitmap(mWorld.mActivity.getResources(), LAYER1_ID);
            int maxHeight = (int) (viewHeight * 1.5);
            addLayer(new Layer(this, bmp, maxHeight, 0, 0, 2, 0, true, true, viewWidth, viewHeight));
        }
        {
            int maxHeight = (int) (viewHeight * 1.4);
            Bitmap bmp = bm.loadBitmap(mWorld.mActivity.getResources(), LAYER2_ID);
            float initYPos = maxHeight - bmp.getHeight();
            addLayer(new Layer(this, bmp, maxHeight, 0, initYPos, 0, 0, true, false, viewWidth, viewHeight));
        }
        {
            Bitmap bmp = bm.loadBitmap(mWorld.mActivity.getResources(), LAYER3_ID);
            int maxHeight = (int) (viewHeight * 2.7);
            addLayer(new Layer(this, bmp, maxHeight, 0, 0, 0, 0, false, false, viewWidth, viewHeight));
        }
        {
            int maxHeight = viewHeight * 2;
            Bitmap bmp = bm.loadBitmap(mWorld.mActivity.getResources(), LAYER4_ID);
            float initYPos = maxHeight - bmp.getHeight();
            addLayer(new Layer(this, bmp, maxHeight, 0, initYPos, 0, 0, true, false, viewWidth, viewHeight));
        }
    }

    @Override
    public void dispose() {
        // TODO: delegate this into the layer
        BitmapManager bm = mWorld.getBitmapManager();
        bm.releaseBitmap(LAYER1_ID);
        bm.releaseBitmap(LAYER2_ID);
        bm.releaseBitmap(LAYER3_ID);
        bm.releaseBitmap(LAYER4_ID);
    }

}


text:
using UnityEngine;
using System.Collections;

public class OTEaseCubicOut : OTEase
{

    public override float ease(float t, float b, float c, float d)
    {
        return c * ((t = t / d - 1) * t * t + 1) + b;
    }
}


text:
'''
Utils
=====

.. versionchanged:: 1.6.0
    The OrderedDict class has been removed. Use the collections.OrderedDict.

'''

__all__ = ('intersection', 'difference', 'strtotuple',
           'get_color_from_hex', 'get_hex_from_color', 'get_random_color',
           'is_color_transparent', 'boundary',
           'deprecated', 'SafeList',
           'interpolate', 'QueryDict',
           'platform', 'escape_markup', 'reify')

from os import environ
from sys import platform as _sys_platform
from re import match, split
try:
    from UserDict import UserDict
    from UserDict import DictMixin
except ImportError:
    from collections import UserDict
    from collections import MutableMapping as DictMixin

_platform_android = None
_platform_ios = None

def boundary(value, minvalue, maxvalue):
    '''Limit a value between a minvalue and maxvalue.'''
    return min(max(value, minvalue), maxvalue)

def intersection(set1, set2):
    '''Return the intersection of 2 lists.'''
    return [s for s in set1 if s in set2]

def difference(set1, set2):
    '''Return the difference between 2 lists.'''
    return [s for s in set1 if s not in set2]

def interpolate(value_from, value_to, step=10):
    '''Interpolate between two values. This can be useful for smoothing some
    transitions. For example::

        # instead of setting directly
        self.pos = pos

        # use interpolate, and you'll have a nicer transition
        self.pos = interpolate(self.pos, new_pos)

    .. warning::
        These interpolations work only on lists/tuples/doubles with the same
        dimensions. No test is done to check the dimensions are the same.
    '''
    if type(value_from) in (list, tuple):
        out = []
        for x, y in zip(value_from, value_to):
            out.append(interpolate(x, y, step))
        return out
    else:
        return value_from + (value_to - value_from) / float(step)

def strtotuple(s):
    '''Convert a tuple string into a tuple
    with some security checks. Designed to be used
    with the eval() function::

        a = (12, 54, 68)
        b = str(a)         # return '(12, 54, 68)'
        c = strtotuple(b)  # return (12, 54, 68)

    '''
    # security
    if not match('^[,.0-9 ()\[\]]*$', s):
        raise Exception('Invalid characters in string for tuple conversion')
    # fast syntax check
    if s.count('(') != s.count(')'):
        raise Exception('Invalid count of ( and )')
    if s.count('[') != s.count(']'):
        raise Exception('Invalid count of [ and ]')
    r = eval(s)
    if type(r) not in (list, tuple):
        raise Exception('Conversion failed')
    return r

def get_color_from_hex(s):
    '''Transform a hex string color to a kivy
    :class:`~kivy.graphics.Color`.
    '''
    if s.startswith('#'):
        return get_color_from_hex(s[1:])

    value = [int(x, 16) / 255.
             for x in split('([0-9a-f]{2})', s.lower()) if x != '']
    if len(value) == 3:
        value.append(1)
    return value

def get_hex_from_color(color):
    '''Transform a kivy :class:`~kivy.graphics.Color` to a hex value::

        >>> get_hex_from_color((0, 1, 0))
        '#00ff00'
        >>> get_hex_from_color((.25, .77, .90, .5))
        '#3fc4e57f'

    .. versionadded:: 1.5.0
    '''
    return '#' + ''.join(['{0:02x}'.format(int(x * 255)) for x in color])

def get_random_color(alpha=1.0):
    '''Returns a random color (4 tuple).

    :Parameters:
        `alpha` : float, defaults to 1.0
            If alpha == 'random', a random alpha value is generated.
    '''
    from random import random
    if alpha == 'random':
        return [random(), random(), random(), random()]
    else:
        return [random(), random(), random(), alpha]

def is_color_transparent(c):
    '''Return True if the alpha channel is 0.'''
    if len(c) < 4:
        return False
    if float(c[3]) == 0.:
        return True
    return False

DEPRECATED_CALLERS = []

def deprecated(func):
    '''This is a decorator which can be used to mark functions
    as deprecated. It will result in a warning being emitted the first time
    the function is used.'''

    import inspect
    import functools

    @functools.wraps(func)
    def new_func(*args, **kwargs):
        file, line, caller = inspect.stack()[1][1:4]
        caller_id = "%s:%s:%s" % (file, line, caller)
        # We want to print deprecated warnings only once:
        if caller_id not in DEPRECATED_CALLERS:
            DEPRECATED_CALLERS.append(caller_id)
            warning = (
                    'Call to deprecated function %s in %s line %d.'
                    'Called from %s line %d'
                    ' by %s().') % (
                            func.__name__,
                            func.__code__.co_filename,
                            func.__code__.co_firstlineno + 1,
                            file, line, caller)
            from kivy.logger import Logger
            Logger.warn(warning)
            if func.__doc__:
                Logger.warn(func.__doc__)
        return func(*args, **kwargs)
    return new_func

class SafeList(list):
    '''List with a clear() method.

    .. warning::
        Usage of the iterate() function will decrease your performance.
    '''

    def clear(self):
        del self[:]

    @deprecated
    def iterate(self, reverse=False):
        if reverse:
            return reversed(iter(self))
        return iter(self)

class QueryDict(dict):
    '''QueryDict is a dict() that can be queried with dot.

    .. versionadded:: 1.0.4

  ::

        d = QueryDict()
        # create a key named toto, with the value 1
        d.toto = 1
        # it's the same as
        d['toto'] = 1
    '''

    def __getattr__(self, attr):
        try:
            return self.__getitem__(attr)
        except KeyError:
            return super(QueryDict, self).__getattr__(attr)

    def __setattr__(self, attr, value):
        self.__setitem__(attr, value)

def format_bytes_to_human(size, precision=2):
    '''Format a bytes value to a human readable representation (B, KB, MB...).

    .. versionadded:: 1.0.8

    :Parameters:
        `size`: int
            Number that represents a bytes value
        `precision`: int, defaults to 2
            Precision after the comma

    Examples::

        >>> format_bytes_to_human(6463)
        '6.31 KB'
        >>> format_bytes_to_human(646368746541)
        '601.98 GB'

    '''
    size = int(size)
    fmt = '%%1.%df %%s' % precision
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if size < 1024.0:
            return fmt % (size, unit)
        size /= 1024.0

class Platform(object):
    # refactored to class to allow module function to be replaced
    # with module variable
    _platform = None

    @deprecated
    def __call__(self):
        return self._get_platform()

    def __eq__(self, other):
        return other == self._get_platform()

    def __ne__(self, other):
        return other != self._get_platform()

    def __str__(self):
        return self._get_platform()

    def __repr__(self):
        return 'platform name: \'{platform}\' from: \n{instance}'.format(
            platform=self._get_platform(),
            instance=super(Platform, self).__repr__()
        )

    def __hash__(self):
        return self._get_platform().__hash__()

    def _get_platform(self):
        if self._platform is not None:
            return self._platform
        global _platform_ios, _platform_android

        if _platform_android is None:
            # ANDROID_ARGUMENT and ANDROID_PRIVATE are 2 environment variables
            # from python-for-android project
            _platform_android = 'ANDROID_ARGUMENT' in environ

        if _platform_ios is None:
            _platform_ios = (environ.get('KIVY_BUILD', '') == 'ios')

        # On android, _sys_platform return 'linux2', so prefer to check the
        # import of Android module than trying to rely on _sys_platform.
        if _platform_android is True:
            return 'android'
        elif _platform_ios is True:
            return 'ios'
        elif _sys_platform in ('win32', 'cygwin'):
            return 'win'
        elif _sys_platform == 'darwin':
            return 'macosx'
        elif _sys_platform[:5] == 'linux':
            return 'linux'
        return 'unknown'

platform = Platform()
'''
.. versionadded:: 1.3.0

Deprecated since 1.8.0:  Use platform as variable instaed of a function.\n
Calling platform() will return one of: *win*, *linux*, *android*, *macosx*,
*ios* or *unknown*.

.. versionchanged:: 1.8.0

`platform` also behaves like a regular variable in comparisons like so::

    from kivy import platform
    if platform == 'linux':
        do_linux_things()
    if platform() == 'linux': # triggers deprecation warning
        do_more_linux_things()
    foo = {'linux' : do_linux_things}
    foo[platform]() # calls do_linux_things
    p = platform # assigns to a module object
    if p is 'android':
        do_android_things()
    p += 'some string' # error!

'''

def escape_markup(text):
    '''
    Escape markup characters found in the text. Intended to be used when markup
    text is activated on the Label::

        untrusted_text = escape_markup('Look at the example [1]')
        text = '[color=ff0000]' + untrusted_text + '[/color]'
        w = Label(text=text, markup=True)

    .. versionadded:: 1.3.0
    '''
    return text.replace('[', '&bl;').replace(']', '&br;').replace('&', '&')

class reify(object):
    '''
    Put the result of a method which uses this (non-data) descriptor decorator
    in the instance dict after the first call, effectively replacing the
    decorator with an instance variable.

    It acts like @property, except that the function is only ever called once;
    after that, the value is cached as a regular attribute. This gives you lazy
    attribute creation on objects that are meant to be immutable.

    Taken from the `Pyramid project <https://pypi.python.org/pypi/pyramid/>`_.
    '''

    def __init__(self, func):
        self.func = func
        self.__doc__ = func.__doc__

    def __get__(self, inst, cls):
        if inst is None:
            return self
        retval = self.func(inst)
        setattr(inst, self.func.__name__, retval)
        return retval


text:
package privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.logic.shoppingList.business.impl.converter;

import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.context.ContextSetter;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.logic.shoppingList.business.domain.ListItem;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.logic.shoppingList.persistence.entity.ShoppingListEntity;

/**
 * Description:
 * Author: Grebiel Jose Ifill Brito
 * Created: 11.06.16 creation date
 */
public interface ShoppingListConverter extends ContextSetter
{
    void convertItemToEntity(ListItem item, ShoppingListEntity entity);

    void convertEntityToItem(ShoppingListEntity entity, ListItem item);
}


text:
<?php

final class HeraldDifferentialDiffAdapter extends HeraldDifferentialAdapter {

  public function getAdapterApplicationClass() {
    return 'PhabricatorDifferentialApplication';
  }

  protected function initializeNewAdapter() {
    $this->setDiff(new DifferentialDiff());
  }

  public function isSingleEventAdapter() {
    return true;
  }

  protected function loadChangesets() {
    return $this->loadChangesetsWithHunks();
  }

  protected function loadChangesetsWithHunks() {
    return $this->getDiff()->getChangesets();
  }

  public function getObject() {
    return $this->getDiff();
  }

  public function getAdapterContentType() {
    return 'differential.diff';
  }

  public function getAdapterContentName() {
    return pht('Differential Diffs');
  }

  public function getAdapterContentDescription() {
    return pht(
      "React to new diffs being uploaded, before writes occur.\n".
      "These rules can reject diffs before they are written to permanent ".
      "storage, to prevent users from accidentally uploading private keys or ".
      "other sensitive information.");
  }

  public function supportsRuleType($rule_type) {
    switch ($rule_type) {
      case HeraldRuleTypeConfig::RULE_TYPE_GLOBAL:
        return true;
      case HeraldRuleTypeConfig::RULE_TYPE_OBJECT:
      case HeraldRuleTypeConfig::RULE_TYPE_PERSONAL:
      default:
        return false;
    }
  }

  public function getRepetitionOptions() {
    return array(
      HeraldRepetitionPolicyConfig::FIRST,
    );
  }

  public function getHeraldName() {
    return pht('New Diff');
  }

}


text:
[?php use_helper('I18N', 'Date') ?]
[?php include_partial('<?php echo $this->getModuleName() ?>/assets') ?]

            <a href="[?php echo url_for('<?php echo $this->getModuleName() ?>/index'); ?]">[?php echo <?php echo $this->getI18NString('list.title') ?> ?]

[?php echo <?php echo $this->getI18NString('edit.title') ?> ?]

[?php echo <?php echo $this->getI18NString('edit.title') ?> ?]

  [?php include_partial('<?php echo $this->getModuleName() ?>/flashes') ?]

  [?php include_partial('<?php echo $this->getModuleName() ?>/form_header', array('<?php echo $this->getSingularName() ?>' => $<?php echo $this->getSingularName() ?>, 'form' => $form, 'configuration' => $configuration)) ?]

  [?php include_partial('<?php echo $this->getModuleName() ?>/form', array('<?php echo $this->getSingularName() ?>' => $<?php echo $this->getSingularName() ?>, 'form' => $form, 'configuration' => $configuration, 'helper' => $helper)) ?]

  [?php include_partial('<?php echo $this->getModuleName() ?>/form_footer', array('<?php echo $this->getSingularName() ?>' => $<?php echo $this->getSingularName() ?>, 'form' => $form, 'configuration' => $configuration)) ?]


text:
using ElectronicObserver.Data.Battle.Phase;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ElectronicObserver.Data.Battle {

	/// <summary>
	/// 連合艦隊航空戦
	/// </summary>
	public class BattleCombinedAirBattle : BattleDay {

		public PhaseAirBattle AirBattle2 { get; protected set; }

		public override void LoadFromResponse( string apiname, dynamic data ) {
			base.LoadFromResponse( apiname, (object)data );

			JetBaseAirAttack = new PhaseJetBaseAirAttack( this, "噴式基地航空隊攻撃" );
			JetAirBattle = new PhaseJetAirBattle( this, "噴式航空戦" );
			BaseAirAttack = new PhaseBaseAirAttack( this, "基地航空隊攻撃" );
			AirBattle = new PhaseAirBattle( this, "第一次航空戦" );
			Support = new PhaseSupport( this, "支援攻撃" );
			AirBattle2 = new PhaseAirBattle( this, "第二次航空戦", "2" );

			foreach ( var phase in GetPhases() )
				phase.EmulateBattle( _resultHPs, _attackDamages );

		}

		public override string APIName {
			get { return "api_req_combined_battle/airbattle"; }
		}

		public override string BattleName {
			get { return "連合艦隊 航空戦"; }
		}

		public override BattleData.BattleTypeFlag BattleType {
			get { return BattleTypeFlag.Day | BattleTypeFlag.Combined; }
		}

		public override IEnumerable<PhaseBase> GetPhases() {
			yield return Initial;
			yield return Searching;
			yield return JetBaseAirAttack;
			yield return JetAirBattle;
			yield return BaseAirAttack;
			yield return AirBattle;
			yield return Support;
			yield return AirBattle2;
		}

	}

}


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

namespace Devdog.General
{
    [DisallowMultipleComponent]
    public abstract class TriggerBase : MonoBehaviour // , IMouseCallbacks
    {
        public bool useWhenPlayerComesInRange = false;
        public bool blockPlayerInput = false;

        public bool isInUse
        {
            get { return TriggerManager.currentActiveTrigger == this; }
        }

        [Obsolete("Use TriggerManager.currentActiveTrigger instead.")]
        protected static TriggerBase currentTrigger
        {
            get { return TriggerManager.currentActiveTrigger; }
            set { TriggerManager.currentActiveTrigger = value; }
        }

        private bool _inRange;
        public virtual bool inRange
        {
            get
            {
                if (rangeHandler == null || rangeHandler.Equals(null))
                {
                    return _inRange;
                }

                return rangeHandler.IsPlayerInRange(PlayerManager.instance.currentPlayer);
            }
            protected set { _inRange = value; }
        }

        private ITriggerRangeHandler _rangeHandler;
        public ITriggerRangeHandler rangeHandler
        {
            get
            {
                if (_rangeHandler == null || _rangeHandler.Equals(null))
                {
                    _rangeHandler = GetComponentInChildren<ITriggerRangeHandler>();
                }

                return _rangeHandler;
            }
        }

        private static List<ITriggerCallbacks> _callbacks = new List<ITriggerCallbacks>();

        protected virtual void Awake()
        {

        }

        protected virtual void OnDestroy()
        {
            if (isInUse)
            {
                if (PlayerManager.instance == null)
                {
                    return; // No need to reset, the player has already been destroyed..
                }

                UnUse();

                Destroy(GetComponent<ITriggerInputHandler>() as UnityEngine.Component);
                Destroy(GetComponent<ITriggerRangeHandler>() as UnityEngine.Component);
            }
        }

        public virtual bool Toggle()
        {
            return Toggle(PlayerManager.instance.currentPlayer);
        }

        public virtual bool Toggle(Player player)
        {
            if (isInUse)
            {
                return UnUse(player);
            }

            return Use(player);
        }

        protected bool CanUse()
        {
            return CanUse(PlayerManager.instance.currentPlayer);
        }

        public virtual bool CanUse(Player player)
        {
            if (enabled == false || inRange == false)
                return false;

            if (isInUse)
                return true;

            if (InputManager.CanReceiveUIInput(gameObject) == false)
                return false;

            return true;
        }

        protected bool CanUnUse()
        {
            return CanUnUse(PlayerManager.instance.currentPlayer);
        }

        public virtual bool CanUnUse(Player player)
        {
            if (enabled == false || inRange == false)
                return false;

            if (isInUse == false)
                return false;

            if (InputManager.CanReceiveUIInput(gameObject) == false)
                return false;

            return true;
        }

        public bool Use()
        {
            return Use(PlayerManager.instance.currentPlayer);
        }

        public abstract bool Use(Player player);

        public bool UnUse()
        {
            return UnUse(PlayerManager.instance.currentPlayer);
        }

        public abstract bool UnUse(Player player);

        public abstract void DoVisuals();
        public abstract void UndoVisuals();

        public virtual void NotifyCameInRange(Player player)
        {
            inRange = true;
            if (useWhenPlayerComesInRange)
            {
                Use(player);
            }
        }

        public virtual void NotifyWentOutOfRange(Player player)
        {
            if (isInUse)
            {
                UnUse(player);
            }
            inRange = false;
        }

        private void UpdateTriggerCallbacks()
        {
            GetComponents<ITriggerCallbacks>(_callbacks);
        }

        /// <summary>
        /// Only the first active and enabled component gets the callbacks. In order for the next component to receive the callbacks the first one has to be disabled or removed.
        /// </summary>
        protected virtual void NotifyTriggerUsed(Player player)
        {
            if (blockPlayerInput)
            {
                InputManager.LimitPlayerInputTo(gameObject);
            }

            UpdateTriggerCallbacks();
            for (int i = 0; i < _callbacks.Count; i++)
            {
                var callback = _callbacks[i];
                var callbackBehaviour = callback as Behaviour;
                if (callbackBehaviour != null)
                {
                    if (callbackBehaviour.isActiveAndEnabled == false)
                    {
                        continue;
                    }
                }

                bool eventIsConsumed = callback.OnTriggerUsed(player);
                if (eventIsConsumed)
                {
                    break;
                }
            }
        }

        /// <summary>
        /// Only the first active and enabled component gets the callbacks. In order for the next component to receive the callbacks the first one has to be disabled or removed.
        /// </summary>
        protected virtual void NotifyTriggerUnUsed(Player player)
        {
            if (blockPlayerInput)
            {
                InputManager.RemovePlayerLimitInput(gameObject);
            }

            UpdateTriggerCallbacks();
            for (int i = 0; i < _callbacks.Count; i++)
            {
                var callback = _callbacks[i];
                var callbackBehaviour = callback as Behaviour;
                if (callbackBehaviour != null)
                {
                    if (callbackBehaviour.isActiveAndEnabled == false)
                    {
                        continue;
                    }
                }

                bool eventIsConsumed = callback.OnTriggerUnUsed(player);
                if (eventIsConsumed)
                {
                    break;
                }
            }
        }
    }
}


text:
{% comment %}
	Creates a breadcrumb from the page's URL
{% endcomment %}

					{% assign parts = page.url | split: "/" %}

Home

							{% for part in parts offset: 1 %}
								{% if forloop.last %}

{{ page.title }}

								{% else %}
									{% assign text =  part | replace:'-', ' ' | capitalize %}
									{% assign limit = forloop.index | plus: 1 %}
									{% capture href %}{% for part in parts limit: limit %}{{ part | append: '/' }}{% endfor %}{% endcapture %}

										{{ text }}

								{% endif %}
							{% endfor %}


text:
package org.apache.commons.digester3.annotations.rules;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.apache.commons.digester3.PathCallParamRule;
import org.apache.commons.digester3.annotations.DigesterRule;
import org.apache.commons.digester3.annotations.DigesterRuleList;
import org.apache.commons.digester3.annotations.handlers.PathCallParamHandler;

/**
 * Methods arguments annotated with {@code PathCallParam} will be bound with {@code PathCallParamRule} digester rule.
 *
 * @see org.apache.commons.digester3.Digester#addCallParamPath(String,int)
 * @since 2.1
 */
@Documented
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.PARAMETER )
@DigesterRule( reflectsRule = PathCallParamRule.class, handledBy = PathCallParamHandler.class )
public @interface PathCallParam
{

    /**
     * The element matching pattern.
     */
    String pattern();

    /**
     * The namespace URI for which this Rule is relevant, if any.
     *
     * @since 3.0
     */
    String namespaceURI() default "";

    /**
     * Defines several {@code @PathCallParam} annotations on the same element.
     *
     * @see PathCallParam
     */
    @Documented
    @Retention( RetentionPolicy.RUNTIME )
    @Target( ElementType.PARAMETER )
    @DigesterRuleList
    @interface List
    {
        PathCallParam[] value();
    }

}


text:
This project is a boot camp project for [AngularJS](http://angularjs.org/) Framework.
You can use it to learn AngularJS basics.

[Project web page](http://nebrass.github.io/AngularJS-Boot-Camp)

Done : Thursday 30th, April 2015 - Asnières sur Seine 92600 - FRANCE


text:
import fn from 'fnjs';
import { mix } from 'lib/objects';
import { Mods, Resources } from 'services/modifiers';

const ResourceMappings = {
    'MP': Resources.MANA,
    'Mana': Resources.MANA,
    'Energy': Resources.ENERGY,
    'BloodWell': Resources.BLOODWELL,
    'Rage': Resources.RAGE
};

const ResourceStats = ['mp', 'mpperlevel', 'mpregen', 'mpregenperlevel'];

const ChampionStatMods = {
    'hp': Mods.FLAT_HP_POOL,
    'hpperlevel': Mods.SCALING_HP_POOL,
    'mp': {
        [Resources.MANA]: Mods.FLAT_MP_POOL,
        [Resources.ENERGY]: Mods.FLAT_ENERGY_POOL,
        [Resources.BLOODWELL]: Mods.FLAT_BLOODWELL
    },
    'mpperlevel': {
        [Resources.MANA]: Mods.SCALING_MP_POOL,
        [Resources.ENERGY]: Mods.SCALING_ENERGY_POOL,
        [Resources.BLOODWELL]: Mods.SCALING_BLOODWELL
    },
    'movespeed': Mods.FLAT_MOVE_SPEED,
    'armor': Mods.FLAT_ARMOR,
    'armorperlevel': Mods.SCALING_ARMOR,
    'spellblock': Mods.FLAT_MR,
    'spellblockperlevel': Mods.SCALING_MR,
    'attackrange': Mods.FLAT_ATTACK_RANGE,
    'hpregen': Mods.FLAT_HP_REGEN,
    'hpregenperlevel': Mods.SCALING_HP_REGEN,
    'mpregen': {
        [Resources.MANA]: Mods.FLAT_MP_REGEN,
        [Resources.ENERGY]: Mods.FLAT_ENERGY_REGEN
    },
    'mpregenperlevel': {
        [Resources.MANA]: Mods.SCALING_MP_REGEN,
        [Resources.ENERGY]: Mods.SCALING_ENERGY_REGEN
    },
    'crit': Mods.FLAT_CRIT_CHANCE,
    'critperlevel': Mods.SCALING_CRIT_CHANCE,
    'attackdamage': Mods.FLAT_ATTACK_DAMAGE,
    'attackdamageperlevel': Mods.SCALING_ATTACK_DAMAGE,
    'attackspeedoffset': Mods.FLAT_ATTACK_SPEED,
    'attackspeedperlevel': Mods.SCALING_ATTACK_SPEED
};

function transform(rawChampions) {
    let champions = fn.map(rawChampions.data, (champion, id) => {
        let resource = ResourceMappings[champion.partype];

        return {
            id,
            resource,
            name: champion.name,
            stats: fn.chain(champion.stats)
                .map((value, stat) => {
                    let mod = ChampionStatMods[stat];

                    if(ResourceStats.indexOf(stat) > -1) {
                        mod = mod[resource]
                    }

                    return mod ? mix(mod, { value }) : null;
                })
                .filter(mod => !!mod)
                .reduce((stats, mod) => {
                    let id = mod.stat.id;

                    if(!stats[id]) {
                        stats[id] = mix({ values: {} }, mod.stat);
                    }

                    let key = mod.scaling ? 'growth' : 'base';

                    stats[id].values[key] = mod.value;

                    return stats;
                }, {})
                .value(),
            image: {
                sprite: champion.image.sprite,
                x: champion.image.x,
                y: champion.image.y
            }
        }
    });

    return fn.sort(champions, (a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1);
}

export default transform;


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

namespace AdvancedAgilityPack
{

    public static class AdvancedHtmlNodeExtensions
    {

        public static AdvancedHtmlNode ElementById<T>(this T node, string id) where T : AdvancedHtmlNode
        {
            return node.Descendants.SingleById(id);
        }

        public static T SingleById<T>(this IEnumerable<T> nodes, string id) where T : AdvancedHtmlNode
        {
            return nodes.FirstOrDefault(x => x.Id == id);
        }

        public static AdvancedNodeCollection<T> ToAdvancedCollection<T>(this IEnumerable<T> nodes) where T : AdvancedHtmlNode
        {
            return new AdvancedNodeCollection<T>(nodes);
        }

        public static AdvancedNodeCollection<T> WithTag<T>(this IEnumerable<T> nodes, string tag) where T : AdvancedHtmlNode
        {
            return nodes.Where(x => x.Tag == tag).ToAdvancedCollection();
        }

        public static AdvancedNodeCollection<T> WithName<T>(this IEnumerable<T> nodes, string name) where T : AdvancedHtmlNode
        {
            return nodes.Where(x => x.Name == name).ToAdvancedCollection();
        }

        public static AdvancedNodeCollection<T> WithCssClass<T>(this IEnumerable<T> nodes, string cssClass) where T : AdvancedHtmlNode
        {
            return nodes.Where(x => x.HasClass(cssClass)).ToAdvancedCollection();
        }

        public static AdvancedNodeCollection<T> WithoutAnyCssClass<T>(this IEnumerable<T> nodes) where T : AdvancedHtmlNode
        {
            return nodes.Where(x => !x.HasAnyClass).ToAdvancedCollection();
        }

        public static AdvancedNodeCollection<T> WhereFirstChildIs<T>(this IEnumerable<T> nodes, string tagName) where T : AdvancedHtmlNode
        {
            return nodes.Where(x => x.HasChilds).Where(x => x.FirstChild.Tag == tagName).ToAdvancedCollection();
        }

        public static AdvancedNodeCollection<T> WhereInnerTextContains<T>(this IEnumerable<T> nodes, string text) where T : AdvancedHtmlNode
        {
            return nodes.Where(x => x.InnerText.Contains(text)).ToAdvancedCollection();
        }

        public static AdvancedNodeCollection<T> WhereParentIs<T>(this IEnumerable<T> nodes, string tagName) where T : AdvancedHtmlNode
        {
            return nodes.Where(x => x.Parent != null).Where(x => x.Parent.Tag == tagName).ToAdvancedCollection();
        }

        public static IEnumerable<T> DownCast<T>(this IEnumerable<AdvancedHtmlNode> nodes) where T : AdvancedHtmlNode, new()
        {
            foreach (var node in nodes)
                yield return node.DownCast<T>();
        }

        public static T DownCast<T>(this AdvancedHtmlNode node) where T : AdvancedHtmlNode, new()
        {
            var htmlNode = node.AsHtmlNode();
            var tt = new T();
            tt.htmlNode = htmlNode;
            return tt;
        }
    }
}


text:
class InvitesController < ApplicationController

  skip_before_filter :check_xhr
  skip_before_filter :redirect_to_login_if_required

  before_filter :ensure_logged_in, only: [:destroy, :create]

  def show
    invite = Invite.where(invite_key: params[:id]).first

    if invite.present?
      user = invite.redeem
      if user.present?
        log_on_user(user)

        # Send a welcome message if required
        user.enqueue_welcome_message('welcome_invite') if user.send_welcome_message

        topic = invite.topics.first
        if topic.present?
          redirect_to "#{Discourse.base_uri}#{topic.relative_url}"
          return
        end
      end
    end

    redirect_to "/"
  end

  def create
    params.require(:email)

    guardian.ensure_can_invite_to_forum!

    if Invite.invite_by_email(params[:email], current_user)
      render json: success_json
    else
      render json: failed_json, status: 422
    end
  end

  def destroy
    params.require(:email)

    invite = Invite.where(invited_by_id: current_user.id, email: params[:email]).first
    raise Discourse::InvalidParameters.new(:email) if invite.blank?
    invite.trash!(current_user)

    render nothing: true
  end

end


text:
"""Instance Messenger base classes for protocol support.

You will find these useful if you're adding a new protocol to IM.
"""

# Abstract representation of chat "model" classes

from twisted.words.im.locals import ONLINE, OFFLINE, OfflineError
from twisted.words.im import interfaces

from twisted.internet.protocol import Protocol

from twisted.python.reflect import prefixedMethods
from twisted.persisted import styles

from twisted.internet import error

class AbstractGroup:
    def __init__(self, name, account):
        self.name = name
        self.account = account

    def getGroupCommands(self):
        """finds group commands

        these commands are methods on me that start with imgroup_; they are
        called with no arguments
        """
        return prefixedMethods(self, "imgroup_")

    def getTargetCommands(self, target):
        """finds group commands

        these commands are methods on me that start with imgroup_; they are
        called with a user present within this room as an argument

        you may want to override this in your group in order to filter for
        appropriate commands on the given user
        """
        return prefixedMethods(self, "imtarget_")

    def join(self):
        if not self.account.client:
            raise OfflineError
        self.account.client.joinGroup(self.name)

    def leave(self):
        if not self.account.client:
            raise OfflineError
        self.account.client.leaveGroup(self.name)

    def __repr__(self):
        return '<%s %r>' % (self.__class__, self.name)

    def __str__(self):
        return '%s@%s' % (self.name, self.account.accountName)

class AbstractPerson:
    def __init__(self, name, baseAccount):
        self.name = name
        self.account = baseAccount
        self.status = OFFLINE

    def getPersonCommands(self):
        """finds person commands

        these commands are methods on me that start with imperson_; they are
        called with no arguments
        """
        return prefixedMethods(self, "imperson_")

    def getIdleTime(self):
        """
        Returns a string.
        """
        return '--'

    def __repr__(self):
        return '<%s %r/%s>' % (self.__class__, self.name, self.status)

    def __str__(self):
        return '%s@%s' % (self.name, self.account.accountName)

class AbstractClientMixin:
    """Designed to be mixed in to a Protocol implementing class.

    Inherit from me first.

    @ivar _logonDeferred: Fired when I am done logging in.
    """
    def __init__(self, account, chatui, logonDeferred):
        for base in self.__class__.__bases__:
            if issubclass(base, Protocol):
                self.__class__._protoBase = base
                break
        else:
            pass
        self.account = account
        self.chat = chatui
        self._logonDeferred = logonDeferred

    def connectionMade(self):
        self._protoBase.connectionMade(self)

    def connectionLost(self, reason):
        self.account._clientLost(self, reason)
        self.unregisterAsAccountClient()
        return self._protoBase.connectionLost(self, reason)

    def unregisterAsAccountClient(self):
        """Tell the chat UI that I have `signed off'.
        """
        self.chat.unregisterAccountClient(self)

class AbstractAccount(styles.Versioned):
    """Base class for Accounts.

    I am the start of an implementation of L{IAccount<interfaces.IAccount>}, I
    implement L{isOnline} and most of L{logOn}, though you'll need to implement
    L{_startLogOn} in a subclass.

    @cvar _groupFactory: A Callable that will return a L{IGroup} appropriate
        for this account type.
    @cvar _personFactory: A Callable that will return a L{IPerson} appropriate
        for this account type.

    @type _isConnecting: boolean
    @ivar _isConnecting: Whether I am in the process of establishing a
    connection to the server.
    @type _isOnline: boolean
    @ivar _isOnline: Whether I am currently on-line with the server.

    @ivar accountName:
    @ivar autoLogin:
    @ivar username:
    @ivar password:
    @ivar host:
    @ivar port:
    """

    _isOnline = 0
    _isConnecting = 0
    client = None

    _groupFactory = AbstractGroup
    _personFactory = AbstractPerson

    persistanceVersion = 2

    def __init__(self, accountName, autoLogin, username, password, host, port):
        self.accountName = accountName
        self.autoLogin = autoLogin
        self.username = username
        self.password = password
        self.host = host
        self.port = port

        self._groups = {}
        self._persons = {}

    def upgrateToVersion2(self):
        # Added in CVS revision 1.16.
        for k in ('_groups', '_persons'):
            if not hasattr(self, k):
                setattr(self, k, {})

    def __getstate__(self):
        state = styles.Versioned.__getstate__(self)
        for k in ('client', '_isOnline', '_isConnecting'):
            try:
                del state[k]
            except KeyError:
                pass
        return state

    def isOnline(self):
        return self._isOnline

    def logOn(self, chatui):
        """Log on to this account.

        Takes care to not start a connection if a connection is
        already in progress.  You will need to implement
        L{_startLogOn} for this to work, and it would be a good idea
        to override L{_loginFailed} too.

        @returntype: Deferred L{interfaces.IClient}
        """
        if (not self._isConnecting) and (not self._isOnline):
            self._isConnecting = 1
            d = self._startLogOn(chatui)
            d.addCallback(self._cb_logOn)
            # if chatui is not None:
            # (I don't particularly like having to pass chatUI to this function,
            # but we haven't factored it out yet.)
            d.addCallback(chatui.registerAccountClient)
            d.addErrback(self._loginFailed)
            return d
        else:
            raise error.ConnectError("Connection in progress")

    def getGroup(self, name):
        """Group factory.

        @param name: Name of the group on this account.
        @type name: string
        """
        group = self._groups.get(name)
        if group is None:
            group = self._groupFactory(name, self)
            self._groups[name] = group
        return group

    def getPerson(self, name):
        """Person factory.

        @param name: Name of the person on this account.
        @type name: string
        """
        person = self._persons.get(name)
        if person is None:
            person = self._personFactory(name, self)
            self._persons[name] = person
        return person

    def _startLogOn(self, chatui):
        """Start the sign on process.

        Factored out of L{logOn}.

        @returntype: Deferred L{interfaces.IClient}
        """
        raise NotImplementedError()

    def _cb_logOn(self, client):
        self._isConnecting = 0
        self._isOnline = 1
        self.client = client
        return client

    def _loginFailed(self, reason):
        """Errorback for L{logOn}.

        @type reason: Failure

        @returns: I{reason}, for further processing in the callback chain.
        @returntype: Failure
        """
        self._isConnecting = 0
        self._isOnline = 0 # just in case
        return reason

    def _clientLost(self, client, reason):
        self.client = None
        self._isConnecting = 0
        self._isOnline = 0
        return reason

    def __repr__(self):
        return "<%s: %s (%s@%s:%s)>" % (self.__class__,
                                        self.accountName,
                                        self.username,
                                        self.host,
                                        self.port)


text:
const raceController = module.exports = {};

const raceService = require('./raceService');
const expressService = require('../expressService');

expressService.addStandardMethods(raceController, raceService);

raceController.searchFields = ['name=name', 'name~like', 'date>=startDate', 'date<=endDate'];

raceController.find = function (req, res) {
    expressService.standardSearch(req, res, raceService, raceController.searchFields);
};

raceController.getDistinctForDistance = function (req, res) {
    return expressService.promToRes(raceService.distinctField('distanceMeters'), res);
};

raceController.create = function (req, res) {
    expressService.promToRes(raceService.createRaceFromJson(req.body), res);
};

raceController.update = function (req, res) {
    expressService.promToRes(raceService.updateRaceFromJson(req.model, req.body), res);
};

raceController.destroy = function (req, res) {
    expressService.promToRes(raceService.remove(req.model), res);
};

raceController.exportCSV = function (req, res) {
    const findOptions = expressService.parseSearchParams(req);
    findOptions.query = expressService.buildQueryFromRequest(req, raceController.searchFields);
    findOptions.limit = null;
    expressService.streamCollectionToCSVResponse(res, findOptions, raceService, 'race_export', raceService.toExportFormat);
};


text:
package org.kuali.kra.irb.actions.notifyirb;

import org.apache.commons.lang.StringUtils;
import org.kuali.kra.irb.actions.IrbActionsKeyValuesBase;
import org.kuali.kra.irb.actions.submit.ProtocolSubmissionQualifierType;
import org.kuali.kra.irb.actions.submit.ProtocolSubmissionType;
import org.kuali.kra.irb.actions.submit.ValidProtoSubTypeQual;
import org.kuali.rice.core.api.util.ConcreteKeyValue;
import org.kuali.rice.core.api.util.KeyValue;

import java.util.*;

/**
 * Finds the available set of Submission Qualifier Types for a Notify IRB request.
 *
 * @author Kuali Research Administration Team (kualidev@oncourse.iu.edu)
 */
public class SubmissionQualifierTypeValuesFinder extends IrbActionsKeyValuesBase {

    /**
     * @see org.kuali.rice.krad.keyvalues.KeyValuesFinder#getKeyValues()
     */
    @SuppressWarnings("unchecked")
    public List<KeyValue> getKeyValues() {

        List<KeyValue> keyValues = new ArrayList<KeyValue>();
        Map<String, String> fieldValues = new HashMap<String, String>();
        fieldValues.put("submissionTypeCode", ProtocolSubmissionType.NOTIFY_IRB);
        List<ValidProtoSubTypeQual> validProtoSubTypeQuals = (List<ValidProtoSubTypeQual>) getBusinessObjectService().findMatching(
                ValidProtoSubTypeQual.class, fieldValues);
        if (validProtoSubTypeQuals.isEmpty()) {
            keyValues.add(new ConcreteKeyValue("", "select"));
            Collection<ProtocolSubmissionQualifierType> submissionQualifierTypes = this.getKeyValuesService().findAll(
                    ProtocolSubmissionQualifierType.class);
            for (ProtocolSubmissionQualifierType submissionQualifierType : submissionQualifierTypes) {
                if (isAllowed(submissionQualifierType)) {
                    keyValues.add(new ConcreteKeyValue(submissionQualifierType.getSubmissionQualifierTypeCode(),
                        submissionQualifierType.getDescription()));
                }
            }
        } else {
            for (ValidProtoSubTypeQual typeQual : validProtoSubTypeQuals) {
                keyValues.add(new ConcreteKeyValue(typeQual.getSubmissionTypeQualCode(), typeQual.getSubmissionTypeQualifier()
                        .getDescription()));
            }
        }

        return keyValues;
    }

    /**
     * There are many submission qualifier types but only a few are available for a Notify IRB request.
     *
     * @param submissionQualifierType the submission qualifier type
     * @return true if applicable; otherwise false
     */
    private boolean isAllowed(ProtocolSubmissionQualifierType submissionQualifierType) {
        String typeCodes[] = { ProtocolSubmissionQualifierType.AE_UADE, ProtocolSubmissionQualifierType.DSMB_REPORT,
                ProtocolSubmissionQualifierType.ANNUAL_REPORT, ProtocolSubmissionQualifierType.COMPLAINT,
                ProtocolSubmissionQualifierType.DEVIATION, ProtocolSubmissionQualifierType.COI_REPORT,
                ProtocolSubmissionQualifierType.REQUEST_FOR_ELIGIBILITY_EX,
                ProtocolSubmissionQualifierType.SELF_REPORT_NON_COMPLIANCE };

        for (String typeCode : typeCodes) {
            if (StringUtils.equals(typeCode, submissionQualifierType.getSubmissionQualifierTypeCode())) {
                return true;
            }
        }
        return false;
    }
}


text:
import ast
import importlib.abc
import sys
from . import Importer

class AssertionRewritingImporter(Importer):
    def setup_parser(self, parser):
        parser.add_argument('--no-assert',
                            action='store_false',
                            dest='rewriting',
                            default=True,
                            help='Disable assertion rewriting.')

    @classmethod
    def locate(cls):
        return (None, Importer)

    def initialise(self, args, env):
        return args.rewriting

    def get_loader(self, module_name, filename):
        return AssertionRewritingLoader(module_name, filename)

class AssertionRewritingLoader(importlib.machinery.SourceFileLoader):
    # in Python 3.4, implementing get_code won't be necessary -
    # I could just override source_to_code.
    # When 3.4 gets officially released, maybe wrap this def in an if
    def get_code(self, fullname):
        source = self.get_source(fullname)
        path = self.get_filename(fullname)
        return self.source_to_code(source, path)

    def source_to_code(self, source, path='<string>'):
        parsed = ast.parse(source)

        transformer = AssertionRewriter()
        transformer.visit(parsed)

        return compile(parsed, path, 'exec', dont_inherit=True, optimize=0)

    def module_repr(self, module):
        return '<module {!r} from {!r}>'.format(module.__name__, module.__file__)

class AssertionRewriter(ast.NodeTransformer):
    def visit_Assert(self, assert_node):
        if assert_node.msg is not None:
            return assert_node

        statements = AssertionChildVisitor().visit(assert_node.test)

        for s in statements:
            ast.copy_location(s, assert_node)
            ast.fix_missing_locations(s)
        return statements

class AssertionChildVisitor(ast.NodeVisitor):
    def visit(self, node):
        ret = super().visit(node)
        return ret if ret is not None else self.visit_unknown_node(node)

    def visit_BoolOp(self, boolop_node):
        statements = []
        format_params = []
        new_comparators = []
        for i, comparator in enumerate(boolop_node.values):
            name = '@contexts_assertion_var' + str(i)
            statements.append(self.assign(name, comparator))
            new_comparators.append(self.load(name))
            format_params.append(self.repr(self.load(name)))
        if isinstance(boolop_node.op, ast.And):
            format_string = "Asserted " + (" and ".join("{}" for _ in format_params)) + " but found one to be falsy"
            msg = self.format(format_string, format_params)
        elif isinstance(boolop_node.op, ast.Or):
            format_string = "Asserted " + (" or ".join("{}" for _ in format_params)) + " but found them all to be falsy"
            msg = self.format(format_string, format_params)

        statements.append(ast.Assert(ast.BoolOp(boolop_node.op, new_comparators), msg))
        return statements

    def visit_Compare(self, compare_node):
        if len(compare_node.comparators) > 1:
            return

        format_string = self.formatstring_for_comparison(compare_node)
        if format_string is None:
            return

        statements = []
        format_params = []
        new_comparators = []
        for i, comparator in enumerate([compare_node.left] + compare_node.comparators):
            name = '@contexts_assertion_var' + str(i)
            statements.append(self.assign(name, comparator))
            new_comparators.append(self.load(name))
            format_params.append(self.repr(self.load(name)))

        name = '@contexts_formatparam'
        if isinstance(compare_node.ops[0], ast.Lt):
            ternary_expression = ast.IfExp(
                ast.Compare(new_comparators[0], [ast.Gt()], [new_comparators[1]]),
                ast.Str('it to be greater'),
                ast.Str('them to be equal')
            )
        elif isinstance(compare_node.ops[0], ast.Gt):
            ternary_expression = ast.IfExp(
                ast.Compare(new_comparators[0], [ast.Lt()], [new_comparators[1]]),
                ast.Str('it to be less'),
                ast.Str('them to be equal')
            )

        if isinstance(compare_node.ops[0], (ast.Lt, ast.Gt)):
            statements.append(self.assign(name, ternary_expression))
            format_params.append(self.load(name))

        compare_node.left, *compare_node.comparators = new_comparators
        msg = self.format(format_string, format_params)

        statements.append(ast.Assert(compare_node, msg))
        return statements

    def visit_Call(self, call_node):
        func_node = call_node.func
        if isinstance(func_node, ast.Name) and func_node.id == "isinstance":
            # original code was:
            # assert isinstance(obj, cls_or_tuple)
            #
            # generated code is:
            #
            # @contexts_assertion_var1 = obj
            # @contexts_assertion_var2 = cls_or_tuple
            # @contexts_assertion_var3 = obj.__class__
            # @contexts_assertion_var4 = (tuple(@x.__name__ for @x in @contexts_assertion_var2)
            #                             if isinstance(@contexts_assertion_var2, tuple)
            #                             else @contexts_assertion_var2.__name__)
            # assert isinstance(@contexts_assertion_var1, @contexts_assertion_var2), 'Asserted isinstance({0}, {1}) but found it to be a {2}'.format(@contexts_assertion_var1, repr(@contexts_assertion_var4).replace("'", ""), @contexts_assertion_var3)
            if sys.version_info < (3, 6):
                tupleAstArgs = ast.comprehension(ast.Name('@x', ast.Store()), self.load('@contexts_assertion_var2'), [])
            else:
                tupleAstArgs = ast.comprehension(ast.Name('@x', ast.Store()), self.load('@contexts_assertion_var2'), [], False)

            return [
                self.assign('@contexts_assertion_var1', call_node.args[0]),
                self.assign('@contexts_assertion_var2', call_node.args[1]),
                self.assign('@contexts_assertion_var3', self.clsname(self.getattr(self.load('@contexts_assertion_var1'), '__class__'))),
                self.assign('@contexts_assertion_var4', ast.IfExp(
                    ast.Call(func=self.load('isinstance'), args=[
                        self.load('@contexts_assertion_var2'),
                        self.load('tuple'),
                    ], keywords=[]),

                    ast.Call(func=self.load('tuple'), args=[
                        ast.GeneratorExp(self.clsname(self.load('@x')), [
                            tupleAstArgs,
                        ]),
                    ], keywords=[]),
                    self.clsname(self.load('@contexts_assertion_var2'))
                )),
                ast.Assert(
                    ast.Call(func=ast.Name(id='isinstance', ctx=ast.Load()), args=[
                        self.load('@contexts_assertion_var1'),
                        self.load('@contexts_assertion_var2'),
                    ], keywords=[]),
                    self.format('Asserted isinstance({0}, {1}) but found it to be a {2}', [
                        self.repr(self.load('@contexts_assertion_var1')),
                        ast.Call(func=self.getattr(self.repr(self.load('@contexts_assertion_var4')), 'replace'), args=[ast.Str("'"), ast.Str("")], keywords=[]),
                        self.load('@contexts_assertion_var3'),
                    ]))
            ]
        if isinstance(func_node, ast.Name) and func_node.id == "all":
            # original code was:
            #
            # assert all(iterable)
            #
            # generated code is:
            #
            # @contexts_assertion_var1 = iterable
            # for @contexts_assertion_var_ix, @contexts_assertion_var_elem in enumerate(@contexts_assertion_var1):
            #     assert x, "Not all elements of {} were truthy. First falsy element: {} at position {}".format(@contexts_assertion_var1, @contexts_assertion_var_ix, @contexts_assertion_var_elem)
            return [
                self.assign('@contexts_assertion_var1', call_node.args[0]),
                ast.For(ast.Tuple([ast.Name("@contexts_assertion_var_ix", ast.Store()),
                                   ast.Name("@contexts_assertion_var_elem", ast.Store())], ast.Store()), ast.Call(func=self.load("enumerate"), args=[self.load('@contexts_assertion_var1')], keywords=[]), [
                    ast.Assert(
                        self.load('@contexts_assertion_var_elem'),
                        self.format("Not all elements of {0} were truthy. First falsy element: {1} at position {2}", [
                            self.repr(self.load('@contexts_assertion_var1')),
                            self.repr(self.load('@contexts_assertion_var_elem')),
                            self.load('@contexts_assertion_var_ix'),
                        ]))
                ], [])
            ]

    def visit_Name(self, name_node):
        if name_node.id == 'False':
            return self.asserted_false_result(name_node)

    def visit_NameConstant(self, nameconst_node):
        if nameconst_node.value == False:  # noqa
            return self.asserted_false_result(nameconst_node)

    def visit_UnaryOp(self, unaryop_node):
        if isinstance(unaryop_node.op, ast.Not):
            format_string = "Asserted not {} but found it to be truthy"
            name = '@contexts_assertion_var'
            statements = [self.assign(name, unaryop_node.operand)]
            msg = self.format(format_string, [self.repr(self.load(name))])
            statements.append(ast.Assert(ast.UnaryOp(ast.Not(), self.load(name)), msg))
            return statements

    def visit_unknown_node(self, node):
        format_string = "Asserted {} but found it to be falsy"
        name = '@contexts_assertion_var'
        statements = [self.assign(name, node)]
        msg = self.format(format_string, [self.repr(self.load(name))])
        statements.append(ast.Assert(self.load(name), msg))
        return statements

    def formatstring_for_comparison(self, compare_node):
        if isinstance(compare_node.ops[0], ast.NotEq):
            return 'Asserted {0} != {1} but found them to be equal'
        if isinstance(compare_node.ops[0], ast.Eq):
            return 'Asserted {0} == {1} but found them not to be equal'
        if isinstance(compare_node.ops[0], ast.Lt):
            return "Asserted {0} < {1} but found {2}"
        if isinstance(compare_node.ops[0], ast.LtE):
            return "Asserted {0} <= {1} but found it to be greater"
        if isinstance(compare_node.ops[0], ast.Gt):
            return "Asserted {0} > {1} but found {2}"
        if isinstance(compare_node.ops[0], ast.GtE):
            return "Asserted {0} >= {1} but found it to be less"
        if isinstance(compare_node.ops[0], ast.In):
            return "Asserted {0} in {1} but found it not to be present"
        if isinstance(compare_node.ops[0], ast.NotIn):
            return "Asserted {0} not in {1} but found it to be present"
        if isinstance(compare_node.ops[0], ast.Is):
            return "Asserted {0} is {1} but found them not to be the same"
        if isinstance(compare_node.ops[0], ast.IsNot):
            return "Asserted {0} is not {1} but found them to be the same"

    def assign(self, name, expr_node):
        return ast.Assign([ast.Name(name, ast.Store())], expr_node)

    def repr(self, load_name_node):
        return ast.Call(func=ast.Name('repr', ast.Load()), args=[load_name_node], keywords=[])

    def format(self, string, format_params):
        return ast.Call(func=self.getattr(ast.Str(string), 'format'), args=format_params, keywords=[])

    def clsname(self, node):
        return self.getattr(node, "__name__")

    def load(self, name):
        return ast.Name(name, ast.Load())

    def getattr(self, node, name):
        return ast.Attribute(node, name, ast.Load())

    def asserted_false_result(self, node):
        msg = ast.Str("Explicitly asserted False")
        return [ast.Assert(node, msg)]


text:
import { makeIconComponent } from './utils/icon-wrapper'
import { DataMap } from '@clair/icons'
export const IconDataMap = /*@__PURE__*/ makeIconComponent({
  name: 'CIconDataMap',
  template: DataMap
})


text:
package org.apache.isis.core.runtime.system;

import java.util.List;

import com.google.common.collect.Lists;

import org.apache.isis.core.commons.debug.DebugBuilder;
import org.apache.isis.core.commons.debug.DebuggableWithTitle;
import org.apache.isis.core.metamodel.deployment.DeploymentCategory;
import org.apache.isis.core.metamodel.deployment.DeploymentCategoryProviderAbstract;
import org.apache.isis.core.runtime.system.session.IsisSessionFactory;

/**
 * Whether running on client or server side etc.
 *
 *

 * Previously this was an <tt>enum</tt>, but it is now a regular class. The
 * change has been made to provide more flexibility in setting up the
 * <tt>IsisContext</tt> lookup.
 *
 *

 * To use this capability:
 *

 *
Write your new implementation of <tt>IsisContext</tt>, along with a
 * static factory method (cf
 * <tt>IsisContextStatic#createInstance(IsisSessionFactory)</tt>)
 *
Create a new subclass of {@link ContextCategory} (also now a regular
 * class rather than an <tt>enum</tt>); this is where your code goes to
 * instantiate your <tt>IsisContext</tt> implementation

 *
Create a new subclass of {@link DeploymentType}, passing in the custom
 * {@link ContextCategory} in its constructor

 *
In your bootstrap code, instantiate your new {@link DeploymentType}
 * subclass

 *
When you run your app, don't forget to specify your custom
 * {@link DeploymentType}, eg using the <tt>--type</tt> command line arg

 *

 */
public class DeploymentType extends DeploymentCategoryProviderAbstract {

    private static List<DeploymentType> deploymentTypes = Lists.newArrayList();

    public static DeploymentType SERVER = new DeploymentType("SERVER", DeploymentCategory.PRODUCTION, ContextCategory.THREADLOCAL);
    public static DeploymentType SERVER_EXPLORATION = new DeploymentType("SERVER_EXPLORATION", DeploymentCategory.EXPLORING, ContextCategory.THREADLOCAL);
    public static DeploymentType SERVER_PROTOTYPE = new DeploymentType("SERVER_PROTOTYPE", DeploymentCategory.PROTOTYPING, ContextCategory.THREADLOCAL);
    public static DeploymentType UNIT_TESTING = new DeploymentType("UNIT_TESTING", DeploymentCategory.PRODUCTION, ContextCategory.STATIC_RELAXED);

    /**
     * Look up {@link DeploymentType} by their {@link #name()}.
     *
     *

     * Can substitute <tt>'-'</tt> instead of <tt>'_'</tt>; for example
     * <tt>server_exploration</tt> will lookup the same as
     * <tt>server-exploration</tt>.
     */
    public static DeploymentType lookup(final String str) {
        final String underscoredStr = str.replace('-', '_').toUpperCase();
        for (final DeploymentType deploymentType : deploymentTypes) {
            if (underscoredStr.equals(deploymentType.name())) {
                return deploymentType;
            }
        }
        throw new IllegalArgumentException(String.format("Unknown deployment type '%s'", str));
    }

    private final String name;
    private final DeploymentCategory deploymentCategory;
    private final ContextCategory contextCategory;

    public DeploymentType(
            final String name, final DeploymentCategory category, final ContextCategory contextCategory) {
        this.deploymentCategory = category;
        this.contextCategory = contextCategory;
        this.name = name;
        deploymentTypes.add(this);
    }

    public DebuggableWithTitle getDebug() {
        return new DebuggableWithTitle() {

            @Override
            public void debugData(final DebugBuilder debug) {
                debug.appendln("Category", deploymentCategory);
                debug.appendln("Context", contextCategory);
                debug.appendln();
                debug.appendln("Name", friendlyName());
                debug.appendln("Should monitor", shouldMonitor());
            }

            @Override
            public String debugTitle() {
                return "Deployment type";
            }
        };
    }

    public void initContext(final IsisSessionFactory sessionFactory) {
        contextCategory.initContext(sessionFactory);
    }

    public boolean shouldMonitor() {
        return (this == SERVER) && isProduction();
    }

    @Override
    public DeploymentCategory getDeploymentCategory() {
        return deploymentCategory;
    }

    public boolean isExploring() {
        return deploymentCategory.isExploring();
    }

    public boolean isPrototyping() {
        return deploymentCategory.isPrototyping();
    }

    public boolean isProduction() {
        return deploymentCategory.isProduction();
    }

    public String friendlyName() {
        return nameLowerCase().replace('_', '-');
    }

    public String nameLowerCase() {
        return name().toLowerCase();
    }

    public String name() {
        return name;
    }

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

}


text:
id: bad87fee1348bd9aefe08806
title: Stilizzare elementi multipli con una classe CSS
challengeType: 0
videoUrl: 'https://scrimba.com/c/cRkVbsQ'
forumTopicId: 18311
dashedName: style-multiple-elements-with-a-css-class
---

# --description--

Le classi consentono di utilizzare gli stessi stili CSS su più elementi HTML. Puoi vederlo applicando la tua classe `red-text` al primo elemento `p`.

# --hints--

Il tuo elemento `h2` dovrebbe essere rosso.

```js
assert($('h2').css('color') === 'rgb(255, 0, 0)');
```

Il tuo elemento `h2` dovrebbe avere la classe `red-text`.

```js
assert($('h2').hasClass('red-text'));
```

Il tuo elemento `p` dovrebbe essere rosso.

```js
assert($('p:eq(0)').css('color') === 'rgb(255, 0, 0)');
```

Il secondo e il terzo elemento `p` non dovrebbero essere rossi.

```js
assert(
  !($('p:eq(1)').css('color') === 'rgb(255, 0, 0)') &&
    !($('p:eq(2)').css('color') === 'rgb(255, 0, 0)')
);
```

Il tuo primo elemento `p` dovrebbe avere la classe `red-text`.

```js
assert($('p:eq(0)').hasClass('red-text'));
```

# --seed--

## --seed-contents--

```html
<style>
  .red-text {
    color: red;
  }
</style>

<h2 class="red-text">CatPhotoApp</h2>
<main>
  <p>Click here to view more <a href="#">cat photos</a>.</p>

  <a href="#"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a>

  <div>
    <p>Things cats love:</p>
    <ul>
      <li>cat nip</li>
      <li>laser pointers</li>
      <li>lasagna</li>
    </ul>
    <p>Top 3 things cats hate:</p>
    <ol>
      <li>flea treatment</li>
      <li>thunder</li>
      <li>other cats</li>
    </ol>
  </div>

  <form action="https://freecatphotoapp.com/submit-cat-photo">
    <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
    <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
    <label><input type="checkbox" name="personality" checked> Loving</label>
    <label><input type="checkbox" name="personality"> Lazy</label>
    <label><input type="checkbox" name="personality"> Energetic</label><br>
    <input type="text" placeholder="cat photo URL" required>
    <button type="submit">Submit</button>
  </form>
</main>
```

# --solutions--

```html
<style>
  .red-text {
    color: red;
  }
</style>

<h2 class="red-text">CatPhotoApp</h2>
<main>
  <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>

  <a href="#"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a>

  <div>
    <p>Things cats love:</p>
    <ul>
      <li>cat nip</li>
      <li>laser pointers</li>
      <li>lasagna</li>
    </ul>
    <p>Top 3 things cats hate:</p>
    <ol>
      <li>flea treatment</li>
      <li>thunder</li>
      <li>other cats</li>
    </ol>
  </div>

  <form action="https://freecatphotoapp.com/submit-cat-photo">
    <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
    <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
    <label><input type="checkbox" name="personality" checked> Loving</label>
    <label><input type="checkbox" name="personality"> Lazy</label>
    <label><input type="checkbox" name="personality"> Energetic</label><br>
    <input type="text" placeholder="cat photo URL" required>
    <button type="submit">Submit</button>
  </form>
</main>
```