text:
/*
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.flaminem.flamy.exec

import com.flaminem.flamy.conf.{FlamyConfVars, FlamyContext}
import com.flaminem.flamy.exec.files.FileRunner
import com.flaminem.flamy.exec.hive.{HiveRunner, ModelHiveRunner, RemoteHiveRunner}
import com.flaminem.flamy.exec.utils.io.FlamyOutput
import com.flaminem.flamy.graph.TableGraph
import com.flaminem.flamy.model.core.Model
import com.flaminem.flamy.model.exceptions.FlamyException
import com.flaminem.flamy.model.files.{FileIndex, SchemaFile, TableFile}
import com.flaminem.flamy.model.{Inputs, PopulateInfo, Variables}
import com.flaminem.flamy.utils.sql.hive.StreamedResultSet

/**
 * The FlamyRunner is used to execute the queries on local or remote.
 * It is more general than the HiveRunner as it is planned to be able to run on other backends than Hive.
 */
class FlamyRunner private(private val hiveRunner: HiveRunner) extends AutoCloseable{

  /**
    * Check that all the schemas, tables and views are correct.
    * In model mode, since the database is empty at the start of each flamy command, this method will create the schema, table and views.
    * @param graph
    */
  @throws(classOf[FlamyException])
  def checkAll(graph: TableGraph): Unit = {
    hiveRunner.checkAll(graph)
    val stats = getStats
    FlamyOutput.out.info(stats.format())
    if (stats.getFailCount > 0) {
      throw new FlamyException("Interrupting command, some queries failed.")
    }
  }

  def populateAll(model: Model, context: FlamyContext): Unit = {
    val stats = getStats
    stats.clear()
    hiveRunner.populateAll(model, context)
    FlamyOutput.out.info(stats.format())
  }

  def getInputsFromText(text: String): Seq[Inputs] = {
    hiveRunner.getInputsFromText(text, variables = new Variables(), closeAfter = false)
  }

  def runText(text: String, title: Option[String]): Unit = {
    hiveRunner.runText(text, title, variables = new Variables(), explainIfDryRun = true, closeAfter = false)
  }

  def testAll(fileIndex: FileIndex, context: FlamyContext): Unit = {
    hiveRunner.testAll(fileIndex, context)
  }

  def runPopulate(populateInfo: PopulateInfo): Unit = {
    hiveRunner.runPopulate(populateInfo)
  }

  def getInputsFromPopulate(populateInfo: PopulateInfo): Seq[Inputs] = {
    hiveRunner.getInputsFromPopulate(populateInfo)
  }

  def runCreateTable(create: TableFile): Unit = {
    hiveRunner.runCreateTable(create)
  }

  def runCreateSchema(schemaFile: SchemaFile): Unit = {
    hiveRunner.runCreateSchema(schemaFile)
  }

  def runCheckTable(create: TableFile): Unit = {
    hiveRunner.runCheckTable(create)
  }

  def runCheckSchema(schemaFile: SchemaFile): Unit = {
    hiveRunner.runCheckSchema(schemaFile)
  }

  /**
    * Should only be used to execute small queries.
    * @param text
    */
  def runText(text: String): Unit = {
    hiveRunner.runText(text, None, new Variables, explainIfDryRun = true)
  }

  /**
    * Should only be used to execute small queries, for experimental features
    * @param query
    */
  def executeQuery(query: String): StreamedResultSet = hiveRunner.executeQuery(query)

  def getConfiguration(key: String): Option[String] = hiveRunner.getConfiguration(key)

  def getStats: FileRunner#Stats = hiveRunner.getStats

  override def close(): Unit = hiveRunner.close()

  def interrupt(): Unit = hiveRunner.interrupt()

}

object FlamyRunner {

  @throws(classOf[FlamyException])
  def apply(context: FlamyContext): FlamyRunner = {
    try {
      new FlamyRunner(HiveRunner(context))
    }
    catch {
      case e: InterruptedException =>
        throw new FlamyException(e)
      case e: Throwable =>
        if(!Thread.currentThread().isInterrupted){
          e.printStackTrace()
        }
        throw new FlamyException(e)
    }
  }

}


text:
<?php
	/**
	 * Created by PhpStorm.
	 * User: marksimonds
	 * Date: 2/3/16
	 * Time: 2:31 PM
	 */

	require_once('../config.php');

	try
	{
		/* initialize whatcounts */
		$whatcounts = new ZayconWhatCounts\WhatCounts( WC_REALM, WC_PASSWORD );

		$article = new ZayconWhatCounts\Article();
		$article
			->setId(5)
			->setName('article-1')
			->setTitle('Test Article Title')
			->setDescription('Test Article Description')
			->setDeck('This is the actual article deck.')
			->setCallout('Test Article Callout')
			->setBody('Test Article Body')
			->setAuthorName('Mark Simonds')
			->setAuthorBio('This is the bio for Mark Simonds')
			->setAuthorEmail('mark@zayconfresh.com')
			->setFolderId(0);

		$is_updated = $whatcounts->updateArticle($article);
		if (class_exists('Kint')) {
			Kint::dump($is_updated);
		} else {
			var_dump($is_updated);
		}
	}
	catch ( ZayconWhatCounts\Exception $e )
	{
		if (class_exists('Kint')) {
			Kint::dump($e);
		} else {
			var_dump($e);
		}
	}

redpajama_set_name: RedPajamaGithub


text:
@startDocuBlock get_cluster_health
@brief Returns the health of the cluster as assessed by the supervision (Agency)

@RESTHEADER{GET /_admin/cluster/health, Queries the health of cluster for monitoring}

@RESTDESCRIPTION
Queries the health of the cluster for monitoring purposes. The response is a JSON object, containing the standard `code`, `error`, `errorNum`, and `errorMessage` fields as appropriate. The endpoint-specific fields are as follows:

- `ClusterId`: A UUID string identifying the cluster
- `Health`: An object containing a descriptive sub-object for each node in the cluster.
  - `<nodeID>`: Each entry in `Health` will be keyed by the node ID and contain the following attributes:
    - `Endpoint`: A string representing the network endpoint of the server.
    - `Role`: The role the server plays. Possible values are `"AGENT"`, `"COORDINATOR"`, and `"DBSERVER"`.
    - `CanBeDeleted`: Boolean representing whether the node can safely be removed from the cluster.
    - `Version`: Version String of ArangoDB used by that node.
    - `Engine`: Storage Engine used by that node.
    - `Status`: A string indicating the health of the node as assessed by the supervision (Agency). This should be considered primary source of truth for Coordinator and DB-Servers node health. If the node is responding normally to requests, it is `"GOOD"`. If it has missed one heartbeat, it is `"BAD"`. If it has been declared failed by the supervision, which occurs after missing heartbeats for about 15 seconds, it will be marked `"FAILED"`.

    Additionally it will also have the following attributes for:

    **Coordinators** and **DB-Servers**
    - `SyncStatus`: The last sync status reported by the node. This value is primarily used to determine the value of `Status`. Possible values include `"UNKNOWN"`, `"UNDEFINED"`, `"STARTUP"`, `"STOPPING"`, `"STOPPED"`, `"SERVING"`, `"SHUTDOWN"`.
    - `LastAckedTime`: ISO 8601 timestamp specifying the last heartbeat received.
    - `ShortName`: A string representing the shortname of the server, e.g. `"Coordinator0001"`.
    - `Timestamp`: ISO 8601 timestamp specifying the last heartbeat received. (deprecated)
    - `Host`: An optional string, specifying the host machine if known.

    **Coordinators** only
    - `AdvertisedEndpoint`: A string representing the advertised endpoint, if set. (e.g. external IP address or load balancer, optional)

    **Agents**
    - `Leader`: ID of the Agent this node regards as leader.
    - `Leading`: Whether this Agent is the leader (true) or not (false).
    - `LastAckedTime`: Time since last `acked` in seconds.

@RESTRETURNCODES

@RESTRETURNCODE{200}
is returned when everything went well.

@endDocuBlock


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SearchServiceIntegrationTest</title>
<meta name="date" content="2016-01-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

de.thi.mymusic.service

Class SearchServiceIntegrationTest

java.lang.Object

de.thi.mymusic.service.SearchServiceIntegrationTest

public class SearchServiceIntegrationTest
extends java.lang.Object

Created by Michael on 20.11.2015.

Constructor Summary

Constructors

Constructor and Description

SearchServiceIntegrationTest()

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

static org.jboss.shrinkwrap.api.spec.WebArchive
createDeployment()

void
thatFindAlbumByNameReturnCorrectEntries()

method under test: findAlbumByName

void
thatFindEntitiesByNameReturnCorrectElements()

method under test: findEntitiesByName

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SearchServiceIntegrationTest

public SearchServiceIntegrationTest()

Method Detail

createDeployment

@Deployment(testable=true)
public static org.jboss.shrinkwrap.api.spec.WebArchive createDeployment()

thatFindAlbumByNameReturnCorrectEntries

public void thatFindAlbumByNameReturnCorrectEntries()
                                             throws java.lang.Exception

method under test: findAlbumByName

Throws:

java.lang.Exception

thatFindEntitiesByNameReturnCorrectElements

public void thatFindEntitiesByNameReturnCorrectElements()
                                                 throws java.lang.Exception

method under test: findEntitiesByName

Throws:

java.lang.Exception

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
namespace editor {
namespace sys {

	class EditorLogger : public engine::sys::Logger
	{
	private:
		void *gameEditor; //Void, because the game should not know about gameeditor...

	public:
		EditorLogger(void *gameEditor);

		void error(const String &msg);
		void warning(const String &msg);
		void info(const String &msg);
	};

}
}

#endif


text:
package cn.aezo.springboot.oauth2.youku.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.oauth2.client.CommonOAuth2Provider;
import org.springframework.security.oauth2.client.endpoint.NimbusAuthorizationCodeTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/oauth_login", "/loginFailure", "/")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2Login()
                .loginPage("/oauth_login") // 自定义oauth登录页面
                .authorizationEndpoint()
                .baseUri("/oauth2/authorize-client") // 自定义认证端点,默认是/oauth2/authorization
                .authorizationRequestRepository(authorizationRequestRepository())
                .and()
                .tokenEndpoint()
                .accessTokenResponseClient(accessTokenResponseClient()) // 自定义token处理
                .and()
                .defaultSuccessUrl("/loginSuccess")
                .failureUrl("/loginFailure");
    }

    @Bean
    public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
        return new HttpSessionOAuth2AuthorizationRequestRepository();
    }

    @Bean
    public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
        // DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient(); // spring-security-5.1.1
        NimbusAuthorizationCodeTokenResponseClient accessTokenResponseClient = new NimbusAuthorizationCodeTokenResponseClient();
        return accessTokenResponseClient;
    }

    // 自定义客户端
    // additional configuration for non-Spring Boot projects
    private static List<String> clients = Arrays.asList("google", "facebook");

    //@Bean
    public ClientRegistrationRepository clientRegistrationRepository() {
        List<ClientRegistration> registrations = clients.stream()
                .map(c -> getRegistration(c))
                .filter(registration -> registration != null)
                .collect(Collectors.toList());

        return new InMemoryClientRegistrationRepository(registrations);
    }

    private static String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration.";

    @Autowired
    private Environment env;

    private ClientRegistration getRegistration(String client) {
        String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");

        if (clientId == null) {
            return null;
        }

        String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret");
        if (client.equals("google")) {
            return CommonOAuth2Provider.GOOGLE.getBuilder(client)
                    .clientId(clientId)
                    .clientSecret(clientSecret)
                    .build();
        }
        if (client.equals("facebook")) {
            return CommonOAuth2Provider.FACEBOOK.getBuilder(client)
                    .clientId(clientId)
                    .clientSecret(clientSecret)
                    .build();
        }
        return null;
    }

}


text:
.class Lcom/android/server/am/ActivityManagerService$PermissionController;
.super Landroid/os/IPermissionController$Stub;
.source "ActivityManagerService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/am/ActivityManagerService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "PermissionController"
.end annotation

# instance fields
.field mActivityManagerService:Lcom/android/server/am/ActivityManagerService;

# direct methods
.method constructor <init>(Lcom/android/server/am/ActivityManagerService;)V
    .locals 0
    .parameter "activityManagerService"

    .prologue
    .line 5139
    invoke-direct {p0}, Landroid/os/IPermissionController$Stub;-><init>()V

    .line 5140
    iput-object p1, p0, Lcom/android/server/am/ActivityManagerService$PermissionController;->mActivityManagerService:Lcom/android/server/am/ActivityManagerService;

    .line 5141
    return-void
.end method

# virtual methods
.method public checkPermission(Ljava/lang/String;II)Z
    .locals 1
    .parameter "permission"
    .parameter "pid"
    .parameter "uid"

    .prologue
    .line 5144
    iget-object v0, p0, Lcom/android/server/am/ActivityManagerService$PermissionController;->mActivityManagerService:Lcom/android/server/am/ActivityManagerService;

    invoke-virtual {v0, p1, p2, p3}, Lcom/android/server/am/ActivityManagerService;->checkPermission(Ljava/lang/String;II)I

    move-result v0

    if-nez v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
<?php

namespace Pfe\Bundle\SessionBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Pfe\Bundle\SessionBundle\Entity\Presence;
use Pfe\Bundle\SessionBundle\Form\PresenceType;

/**
 * Presence controller.
 *
 * @Route("/presence")
 */
class PresenceController extends Controller
{

    /**
     * Lists all Presence entities.
     *
     * @Route("/", name="presence")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('PfeSessionBundle:Presence')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new Presence entity.
     *
     * @Route("/", name="presence_create")
     * @Method("POST")
     * @Template("PfeSessionBundle:Presence:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Presence();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('presence_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
    * Creates a form to create a Presence entity.
    *
    * @param Presence $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(Presence $entity)
    {
        $form = $this->createForm(new PresenceType(), $entity, array(
            'action' => $this->generateUrl('presence_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Presence entity.
     *
     * @Route("/new", name="presence_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Presence();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Presence entity.
     *
     * @Route("/{id}", name="presence_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('PfeSessionBundle:Presence')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Presence entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Presence entity.
     *
     * @Route("/{id}/edit", name="presence_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('PfeSessionBundle:Presence')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Presence entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Presence entity.
    *
    * @param Presence $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Presence $entity)
    {
        $form = $this->createForm(new PresenceType(), $entity, array(
            'action' => $this->generateUrl('presence_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Presence entity.
     *
     * @Route("/{id}", name="presence_update")
     * @Method("PUT")
     * @Template("PfeSessionBundle:Presence:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('PfeSessionBundle:Presence')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Presence entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('presence_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Presence entity.
     *
     * @Route("/{id}", name="presence_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('PfeSessionBundle:Presence')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Presence entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('presence'));
    }

    /**
     * Creates a form to delete a Presence entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('presence_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
function hello(name) {
	console.log("Hello, " + name);
}
hello("user");


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="script.tv.show.next.aired" name="TV Show - Next Aired" version="7.0.1" provider-name="WayneD,marcelveldt">
	<requires>
		<import addon="xbmc.python" version="2.1.0"/>
        <import addon="script.module.thetvdb" version="1.0.20" />
	</requires>
	<extension point="xbmc.python.script" library="default.py">
		<provides>executable</provides>
	</extension>
	<extension point="xbmc.service" library="service.py" start="login"/>
	<extension point="xbmc.addon.metadata">
		Информация за предстоящите ТВ сериали.
		Agafar informació de les sèries de TV que es retransmetran pròximament.
		Erhalten Sie Infos über die nächsten Ausstrahlungstermine der Serien in Ihrer Bibliothek.
		Λήψη πληροφοριών για την Επόμενη Προβολή των Τηλ. Σειρών
		Get info for TV Shows Next Aired.
		Get info for TV Shows Next Aired.
		Get info for TV Shows Next Aired.
		Obtener información de las siguientes emisiones de series.
		Obtener información de las siguientes emisiones de series.
		Obtenir les prochaines dates de diffusion de vos séries TV.
		Obtenir les infos de prochaine diffusion des séries télé.
		Obter a info. das Seguintes Emisións das Series de TV.
		קבל פרטי השידור הבא של תכניות הטלוויזיה.
		Nabavite informacije za sljedeću emitiranu TV seriju.
		Információ a sorozatok következő vetítési idejéről.
		Ottieni info per le Serie TV trasmesse prossimamente.
		TV 쇼 방송 일정을 가져옵니다.
		Gauti TV laidos kitos transliacijos informaciją.
		Ophalen info voor komende TV afleveringen.
		Hent informasjon om kommende TV-programmer.
		Pobieraj informacje o odcinkach seriali wkrótce na antenie.
		Obter info para Próximas Exibições de Séries TV.
		Saiba sobre próximas exibições de séries de TV.
		Află despre emisiuni care urmează să fie difuzate
		Информация о следующих ТВ передачах.
		Pridobi informacije TV oddaj ki se bodo predvajale.
		Hämta info för nästa sändning av TV-serier.
		获取即将播出的剧集的信息。
		<description lang="bg">Сваля информация за предстоящите ТВ сериали. Вече никога няма да пропускате епизод от ТВ сериали, които следите.</description>
		<description lang="ca">Agafar informació de les sèries de TV que es retransmetran pròximament. No te'n perdràs cap mai més.</description>
		<description lang="de">TV Show Next Aired liefert Termin-Informationen über die anstehenden Episoden der Serien aus der Datenbank. Dazu gibt es eine Wochenansicht mit allen in der nächsten Woche laufenden Episoden sowie (bei vorhandenem Skin Support) die direkte Integration der Informationen in die Ansichten des jeweiligen Skins. Sie werden nie wieder eine Folge verpassen.</description>
		<description lang="el">Λήψη πληροφοριών για την Επόμενη Προβολή των Τηλ. Σειρών. Δε θα ξαναχάσετε επεισόδιο ποτέ.</description>
		<description lang="en">Get info for TV Shows Next Aired. You'll never miss one again.</description>
		<description lang="en_NZ">Get info for TV Shows Next Aired. You'll never miss one again.</description>
		<description lang="en_US">Get info for TV Shows Next Aired. You'll never miss one again.</description>
		<description lang="es">Obtener información de las siguientes emisiones de series. Nunca te perderás una de nuevo.</description>
		<description lang="es_MX">Obtener información de las siguientes emisiones de series. Nunca te perderás una de nuevo.</description>
		<description lang="fr">Ce script interroge votre médiathèque puis vas récupérer les infos sur les prochaines diffusions de vos séries. vous n'en manquerez plus aucune.</description>
		<description lang="fr_CA">Obtenir les infos de prochaine diffusion des séries télé. Vous n'en manquerez plus jamais une.</description>
		<description lang="gl">Obter a info. das Seguintes Emisións das Series de TV. Non esquecerá ningunha.</description>
		<description lang="he">קבל פרטי השידור הבא של תכניות הטלוויזיה. לעולם לא תחמיץ שוב פרק.</description>
		<description lang="hr">Nabavite informacije za sljedeću emitiranu TV seriju. Nikada nećete propustiti nijednu.</description>
		<description lang="hu">Információ a sorozatok következő vetítési idejéről. Soha nem marad le mégegyszer semmiről.</description>
		<description lang="it">Ottieni info per le Serie TV trasmesse prossimamente. Non ne perderai più una.</description>
		<description lang="ko">TV 쇼 방송 일정을 가져옵니다. 놓치는 일은 절대 없을 것입니다.</description>
		<description lang="lt">Gauti TV laidos kitos transliacijos informaciją. Jūs niekada daugiau jos nepraleisite.</description>
		<description lang="nl">Ophalen info voor komende TV shows. Je zult ze nooit meer missen.</description>
		<description lang="no">Få informasjon om neste TV-sending. Du vil aldri gå glipp av en episode igjen.</description>
		<description lang="pl">Pobieraj informacje o odcinkach seriali wkrótce na antenie. Nigdy już żadnego nie przegapisz.</description>
		<description lang="pt">Obter info para Próximas Exibições de Séries TV. Nunca mais vai perder uma.</description>
		<description lang="pt_BR">Saiba sobre próximas exibições de séries de TV. Você nunca perderá um episódio.</description>
		<description lang="ro">Află despre emisiuni care urmează să fie difuzate. Nu vei mai rata nici una.</description>
		<description lang="ru">Получает информацию о следующих ТВ передачах. Теперь Вы никогда не пропустите ни одну ТВ передачу.</description>
		<description lang="sl">Pridobi informacije TV oddaj ki se bodo predvajale. Nikoli več ne boste zamudili nobene epizode.</description>
		<description lang="sv">Hämta info för nästa sändning av TV-Serie. Du kommer inte att missa en igen.</description>
		<description lang="zh">获取即将播出的剧集的信息。你不会再错过好节目了。</description>
		<language></language>
		<platform>all</platform>
		<license>GPL v2.0</license>
		<forum>http://forum.xbmc.org/showthread.php?tid=186090</forum>
		<website>http://github.com/marcelveldt/script.tv.show.next.aired</website>
		<source>https://github.com/marcelveldt/script.tv.show.next.aired.git</source>
	</extension>
</addon>


text:
package aws

import (
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/arn"
	"github.com/aws/aws-sdk-go/service/directconnect"
	"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/helper/validation"
)

func resourceAwsDxPrivateVirtualInterface() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsDxPrivateVirtualInterfaceCreate,
		Read:   resourceAwsDxPrivateVirtualInterfaceRead,
		Update: resourceAwsDxPrivateVirtualInterfaceUpdate,
		Delete: resourceAwsDxPrivateVirtualInterfaceDelete,
		Importer: &schema.ResourceImporter{
			State: resourceAwsDxPrivateVirtualInterfaceImport,
		},

		Schema: map[string]*schema.Schema{
			"arn": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"connection_id": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"name": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"vpn_gateway_id": {
				Type:          schema.TypeString,
				Optional:      true,
				ForceNew:      true,
				ConflictsWith: []string{"dx_gateway_id"},
			},
			"dx_gateway_id": {
				Type:          schema.TypeString,
				Optional:      true,
				ForceNew:      true,
				ConflictsWith: []string{"vpn_gateway_id"},
			},
			"vlan": {
				Type:         schema.TypeInt,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validation.IntBetween(1, 4094),
			},
			"bgp_asn": {
				Type:     schema.TypeInt,
				Required: true,
				ForceNew: true,
			},
			"bgp_auth_key": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},
			"address_family": {
				Type:         schema.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validation.StringInSlice([]string{directconnect.AddressFamilyIpv4, directconnect.AddressFamilyIpv6}, false),
			},
			"customer_address": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},
			"amazon_address": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},
			"mtu": {
				Type:         schema.TypeInt,
				Default:      1500,
				Optional:     true,
				ValidateFunc: validateIntegerInSlice([]int{1500, 9001}),
			},
			"jumbo_frame_capable": {
				Type:     schema.TypeBool,
				Computed: true,
			},
			"tags": tagsSchema(),
		},

		Timeouts: &schema.ResourceTimeout{
			Create: schema.DefaultTimeout(10 * time.Minute),
			Update: schema.DefaultTimeout(10 * time.Minute),
			Delete: schema.DefaultTimeout(10 * time.Minute),
		},
	}
}

func resourceAwsDxPrivateVirtualInterfaceCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dxconn

	vgwIdRaw, vgwOk := d.GetOk("vpn_gateway_id")
	dxgwIdRaw, dxgwOk := d.GetOk("dx_gateway_id")
	if vgwOk == dxgwOk {
		return fmt.Errorf(
			"One of ['vpn_gateway_id', 'dx_gateway_id'] must be set to create a Direct Connect private virtual interface")
	}

	req := &directconnect.CreatePrivateVirtualInterfaceInput{
		ConnectionId: aws.String(d.Get("connection_id").(string)),
		NewPrivateVirtualInterface: &directconnect.NewPrivateVirtualInterface{
			VirtualInterfaceName: aws.String(d.Get("name").(string)),
			Vlan:                 aws.Int64(int64(d.Get("vlan").(int))),
			Asn:                  aws.Int64(int64(d.Get("bgp_asn").(int))),
			AddressFamily:        aws.String(d.Get("address_family").(string)),
			Mtu:                  aws.Int64(int64(d.Get("mtu").(int))),
		},
	}
	if vgwOk && vgwIdRaw.(string) != "" {
		req.NewPrivateVirtualInterface.VirtualGatewayId = aws.String(vgwIdRaw.(string))
	}
	if dxgwOk && dxgwIdRaw.(string) != "" {
		req.NewPrivateVirtualInterface.DirectConnectGatewayId = aws.String(dxgwIdRaw.(string))
	}
	if v, ok := d.GetOk("bgp_auth_key"); ok {
		req.NewPrivateVirtualInterface.AuthKey = aws.String(v.(string))
	}
	if v, ok := d.GetOk("customer_address"); ok && v.(string) != "" {
		req.NewPrivateVirtualInterface.CustomerAddress = aws.String(v.(string))
	}
	if v, ok := d.GetOk("amazon_address"); ok && v.(string) != "" {
		req.NewPrivateVirtualInterface.AmazonAddress = aws.String(v.(string))
	}

	log.Printf("[DEBUG] Creating Direct Connect private virtual interface: %#v", req)
	resp, err := conn.CreatePrivateVirtualInterface(req)
	if err != nil {
		return fmt.Errorf("Error creating Direct Connect private virtual interface: %s", err.Error())
	}

	d.SetId(aws.StringValue(resp.VirtualInterfaceId))
	arn := arn.ARN{
		Partition: meta.(*AWSClient).partition,
		Region:    meta.(*AWSClient).region,
		Service:   "directconnect",
		AccountID: meta.(*AWSClient).accountid,
		Resource:  fmt.Sprintf("dxvif/%s", d.Id()),
	}.String()
	d.Set("arn", arn)

	if err := dxPrivateVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil {
		return err
	}

	return resourceAwsDxPrivateVirtualInterfaceUpdate(d, meta)
}

func resourceAwsDxPrivateVirtualInterfaceRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dxconn

	vif, err := dxVirtualInterfaceRead(d.Id(), conn)
	if err != nil {
		return err
	}
	if vif == nil {
		log.Printf("[WARN] Direct Connect virtual interface (%s) not found, removing from state", d.Id())
		d.SetId("")
		return nil
	}

	d.Set("connection_id", vif.ConnectionId)
	d.Set("name", vif.VirtualInterfaceName)
	d.Set("vlan", vif.Vlan)
	d.Set("bgp_asn", vif.Asn)
	d.Set("bgp_auth_key", vif.AuthKey)
	d.Set("address_family", vif.AddressFamily)
	d.Set("customer_address", vif.CustomerAddress)
	d.Set("amazon_address", vif.AmazonAddress)
	d.Set("vpn_gateway_id", vif.VirtualGatewayId)
	d.Set("dx_gateway_id", vif.DirectConnectGatewayId)
	d.Set("mtu", vif.Mtu)
	d.Set("jumbo_frame_capable", vif.JumboFrameCapable)
	if err := getTagsDX(conn, d, d.Get("arn").(string)); err != nil {
		return err
	}

	return nil
}

func resourceAwsDxPrivateVirtualInterfaceUpdate(d *schema.ResourceData, meta interface{}) error {
	if err := dxVirtualInterfaceUpdate(d, meta); err != nil {
		return err
	}

	if err := dxPrivateVirtualInterfaceWaitUntilAvailable(meta.(*AWSClient).dxconn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil {
		return err
	}

	return resourceAwsDxPrivateVirtualInterfaceRead(d, meta)
}

func resourceAwsDxPrivateVirtualInterfaceDelete(d *schema.ResourceData, meta interface{}) error {
	return dxVirtualInterfaceDelete(d, meta)
}

func resourceAwsDxPrivateVirtualInterfaceImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
	arn := arn.ARN{
		Partition: meta.(*AWSClient).partition,
		Region:    meta.(*AWSClient).region,
		Service:   "directconnect",
		AccountID: meta.(*AWSClient).accountid,
		Resource:  fmt.Sprintf("dxvif/%s", d.Id()),
	}.String()
	d.Set("arn", arn)

	return []*schema.ResourceData{d}, nil
}

func dxPrivateVirtualInterfaceWaitUntilAvailable(conn *directconnect.DirectConnect, vifId string, timeout time.Duration) error {
	return dxVirtualInterfaceWaitUntilAvailable(
		conn,
		vifId,
		timeout,
		[]string{
			directconnect.VirtualInterfaceStatePending,
		},
		[]string{
			directconnect.VirtualInterfaceStateAvailable,
			directconnect.VirtualInterfaceStateDown,
		})
}


text:
require "spec_helper"

describe Chef::Provisioning::AWSDriver::Credentials do
  context "loading config INI files" do
    let(:personal_credentials) do
      { region: "us-west-2",
        aws_access_key_id: "AKIAPERSONALKEY",
        aws_secret_access_key: "personalsecretaccesskey",
        name: "personal" }
    end

    let(:work_iam_credentials) do
      { region: "us-east-1",
        aws_access_key_id: "AKIAWORKIAMKEY",
        aws_secret_access_key: "workiamsecretaccesskey",
        name: "work_iam" }
    end

    let(:config_ini_file) do
      @config ||= begin
        ini = Tempfile.new("config_ini")
        ini.write(
          ["[profile personal]",
           "region = us-west-2",
           "[profile work_iam]",
           "region = us-east-1"].join("\n")
        )
        ini.rewind
        ini
      end
      @config
    end

    let(:credential_ini_file) do
      @creds ||= begin
        ini = Tempfile.new("credential_ini")
        ini.write(
          ["[personal]",
           "aws_access_key_id = AKIAPERSONALKEY",
           "aws_secret_access_key = personalsecretaccesskey",
           "[work_iam]",
           "aws_access_key_id = AKIAWORKIAMKEY",
           "aws_secret_access_key = workiamsecretaccesskey"].join("\n")
        )
        ini.rewind
        ini
      end
      @creds
    end

    let(:unified_config_ini_file) do
      @ini ||= begin
        ini = Tempfile.new("unified_config_ini")
        ini.write(
          ["[profile personal]",
           "region = us-west-2",
           "aws_access_key_id = AKIAPERSONALKEY",
           "aws_secret_access_key = personalsecretaccesskey",
           "[profile work_iam]",
           "region = us-east-1",
           "aws_access_key_id = AKIAWORKIAMKEY",
           "aws_secret_access_key = workiamsecretaccesskey"].join("\n")
        )
        ini.rewind
        ini
      end
      @ini
    end

    let(:enterprise_config_ini_file) do
      @ini ||= begin
        ini = Tempfile.new("enterprise_config_ini")
        ini.write(
          ["[profile enterprise]",
           "region = us-west-2",
           "aws_access_key_id = AKIAENTERPRISEKEY",
           "aws_secret_access_key = enterprisesecretaccesskey",
           "aws_session_token = MIIEpAIBAAKCAQEAth95Ci0sdvK222gG2wZEeBXZXeTIynOqJT1fcRnZ/dqVsoUm",
           "proxy_uri = https://user:password@my.proxy:443/path?query",
           "[profile work_iam]",
           "region = us-east-1",
           "aws_access_key_id = AKIAWORKIAMKEY",
           "aws_secret_access_key = workiamsecretaccesskey"].join("\n")
        )
        ini.rewind
        ini
      end
      @ini
    end

    context "unified config ini file" do
      %w{work_iam personal}.each do |profile|
        it "loads the '#{profile}' profile from a unified config file" do
          ENV["AWS_DEFAULT_PROFILE"] = profile
          ENV["AWS_CREDENTIAL_FILE"] = nil
          ENV["AWS_CONFIG_FILE"] = unified_config_ini_file.path
          allow(File)
            .to receive(:file?)
            .with(File.expand_path("~/.aws/credentials"))
            .and_return(false)
          allow(File)
            .to receive(:file?)
            .with(File.expand_path(unified_config_ini_file.path))
            .and_return(true)

          expect(described_class.new.default)
            .to eq(send("#{profile}_credentials"))
        end
      end
    end

    context "enterprise config ini file" do
      let(:credentials) { described_class.new }
      %w{work_iam enterprise}.each do |profile|
        it "loads the '#{profile}' profile from a enterprise config file" do
          ENV["AWS_DEFAULT_PROFILE"] = profile
          ENV["AWS_CREDENTIAL_FILE"] = nil
          ENV["AWS_CONFIG_FILE"] = enterprise_config_ini_file.path
          allow(File)
            .to receive(:file?)
            .with(File.expand_path("~/.aws/credentials"))
            .and_return(false)
          allow(File)
            .to receive(:file?)
            .with(File.expand_path(enterprise_config_ini_file.path))
            .and_return(true)

          if profile.eql?("enterprise")
            expect(credentials[profile][:proxy_uri])
              .to eq("https://user:password@my.proxy:443/path?query")
            expect(credentials[profile][:aws_session_token])
              .to eq("MIIEpAIBAAKCAQEAth95Ci0sdvK222gG2wZEeBXZXeTIynOqJT1fcRnZ/dqVsoUm")
          else
            expect(credentials[profile][:proxy_uri])
              .to eq(nil)
            expect(credentials[profile][:aws_session_token])
              .to eq(nil)
          end
        end
      end
    end

    context "separate config and credential ini files" do
      %w{work_iam personal}.each do |profile|
        it "loads the '#{profile}' profile from a separate config files" do
          ENV["AWS_DEFAULT_PROFILE"] = profile
          ENV["AWS_SHARED_CREDENTIALS_FILE"] = credential_ini_file.path
          ENV["AWS_CONFIG_FILE"] = config_ini_file.path

          expect(described_class.new.default)
            .to eq(send("#{profile}_credentials"))
        end
      end
    end

    context "backwards compatibility for AWS_CREDENTIAL_FILE env var" do
      %w{work_iam personal}.each do |profile|
        it "loads the '#{profile}' profile from a separate config files" do
          ENV["AWS_DEFAULT_PROFILE"] = profile
          ENV["AWS_CREDENTIAL_FILE"] = credential_ini_file.path
          ENV["AWS_CONFIG_FILE"] = config_ini_file.path

          expect(described_class.new.default)
            .to eq(send("#{profile}_credentials"))
        end
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using MiningRigRentalsApi.ObjectModel;
using MiningRigRentalsApi.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using RestSharp;
using RestSharp.Authenticators;

namespace MiningRigRentalsApi
{
	public class Api
	{
		internal readonly string apiKey;
		internal readonly string apiSecret;
		internal readonly WebProxy proxy;

		public JsonSerializerSettings JsonSettings = new JsonSerializerSettings
			{
				DefaultValueHandling = DefaultValueHandling.Ignore,
				ContractResolver = new CamelCasePropertyNamesContractResolver(),

			};
		public Api(
			string apiKey,
			string apiSecret)
			: this(apiKey, apiSecret, null)
		{
		}
		/// <summary>
		///
		/// </summary>
		/// <param name="apiKey">Your API Key</param>
		/// <param name="apiSecret">Your API Secret </param>
		/// <param name="proxy">Proxy for connections.</param>
		public Api(
			string apiKey,
			string apiSecret,
			WebProxy proxy)
		{
			this.apiKey = !string.IsNullOrEmpty(apiKey) ? apiKey : ConfigurationManager.AppSettings["ApiKey"];
			this.apiSecret = !string.IsNullOrEmpty(apiSecret) ? apiSecret : ConfigurationManager.AppSettings["ApiSecret"];
			if (string.IsNullOrEmpty(this.apiKey) || string.IsNullOrEmpty(this.apiSecret))
			{
				throw new ArgumentException("The API key / secret must not be empty. A valid API key and API secret should be used in the Api constructor or an appSettings configuration element with <add key='ApiKey' value='my_api_key' /> and <add key='ApiSecret' value='my_api_secret' /> should exist.", "apiKey");
			}

			this.proxy = proxy;
		}

		protected virtual RestClient CreateClient()
		{
			var client = new RestClient("https://www.miningrigrentals.com/api/v1/")
				{
					Proxy = this.proxy,
					Authenticator = GetAuthenticator()
				};

			client.AddHandler("*", new JsonNetDeseralizer(JsonSettings));
			return client;
		}

		protected virtual IAuthenticator GetAuthenticator()
		{
			return new ApiAuthenticator(apiKey, apiSecret);
		}

		protected virtual IRestRequest CreateRequest(string action, string methodparameter)
		{
			return CreateRequest(action, methodparameter, Method.POST);
		}

		protected virtual IRestRequest CreateRequest(string action, string methodparameter, Method method)
		{
			var post = new RestRequest(action, method)
				{
					RequestFormat = DataFormat.Json,
					JsonSerializer = new JsonNetSerializer(JsonSettings),
				};

			return post.AddParameter("method", methodparameter);
		}

		/// <summary>
		/// fooo.
		/// See: https://www.miningrigrentals.com/apidoc
		///
		/// </summary>
		/// <param name="type">.</param>
		/// <returns></returns>
		public RigList ListRigs(string type)
		{
			var client = CreateClient();

			var req = CreateRequest("rigs", "list")
						.AddParameter("type", type);
			var resp = client.Execute<MiningRigRentalsResponse<RigList>>(req);

			if (resp.ErrorException != null)
				throw resp.ErrorException;

			if (!resp.Data.Success)
				throw new Exception(resp.Data.Errors[0]);

			return resp.Data.Data;
		}

		public MyRigs ListMyRigs()
		{
			var client = CreateClient();

			var req = CreateRequest("account", "myrigs");
			var resp = client.Execute<MiningRigRentalsResponse<MyRigs>>(req);

			if (resp.ErrorException != null)
				throw resp.ErrorException;

			if (!resp.Data.Success)
				throw new Exception(resp.Data.Errors[0]);

			return resp.Data.Data;
		}

		public MyRentals ListMyRentals()
		{
			var client = CreateClient();

			var req = CreateRequest("account", "myrentals");
			var resp = client.Execute<MiningRigRentalsResponse<MyRentals>>(req);

			if (resp.ErrorException != null)
				throw resp.ErrorException;

			if (!resp.Data.Success)
				throw new Exception(resp.Data.Errors[0]);

			return resp.Data.Data;
		}

		public RigDetails GetRigDetails(uint id)
		{
			var client = CreateClient();

			var req = CreateRequest("rigs", "detail")
						.AddParameter("id", id);
			var resp = client.Execute<MiningRigRentalsResponse<RigDetails>>(req);

			if (resp.ErrorException != null)
				throw resp.ErrorException;

			if (!resp.Data.Success)
				throw new Exception(resp.Data.Errors[0]);

			return resp.Data.Data;
		}

		public RentalDetails GetRentalDetails(uint id)
		{
			var client = CreateClient();

			var req = CreateRequest("rental", "detail")
						.AddParameter("id", id);
			var resp = client.Execute<MiningRigRentalsResponse<RentalDetails>>(req);

			if (resp.ErrorException != null)
				throw resp.ErrorException;

			if (!resp.Data.Success)
				throw new Exception(resp.Data.Errors[0]);

			return resp.Data.Data;
		}

		public string UpdateRig(RigData data)
		{
			var client = CreateClient();

			var req = CreateRequest("rigs", "update")
						.AddObject(data);

			var resp = client.Execute<MiningRigRentalsResponse<string>>(req);

			if (resp.ErrorException != null)
				throw resp.ErrorException;

			if (!resp.Data.Success)
				throw new Exception(resp.Data.Errors[0]);

			return resp.Data.Data;
		}

		public Balance GetBalance()
		{
			var client = CreateClient();

			var req = CreateRequest("account", "balance");
			var resp = client.Execute<MiningRigRentalsResponse<Balance>>(req);

			if (resp.ErrorException != null)
				throw resp.ErrorException;

			if (!resp.Data.Success)
				throw new Exception(resp.Data.Errors[0]);

			return resp.Data.Data;
		}

		public List<Pool> ListFavoritePools()
		{
			var client = CreateClient();

			var req = CreateRequest("account", "pools");
			var resp = client.Execute<MiningRigRentalsResponse<List<Pool>>>(req);

			if (resp.ErrorException != null)
				throw resp.ErrorException;

			return resp.Data.Data;
		}

		public List<Profile> ListProfiles()
		{
			var client = CreateClient();

			var req = CreateRequest("account", "profiles");
			var resp = client.Execute<MiningRigRentalsResponse<List<Profile>>>(req);

			if (resp.ErrorException != null)
				throw resp.ErrorException;

			if (!resp.Data.Success)
				throw new Exception(resp.Data.Errors[0]);

			return resp.Data.Data;
		}

	}
}


text:
<!DOCTYPE html>

  <title>About | Kristie Chow</title>
  <link rel="icon" type="image/png" sizes="96x96" href="assets/favicon-96.png">
  <link rel="stylesheet" href="stylesheets/about.css">
  <link href="https://fonts.googleapis.com/css?family=Lora" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="robots" content="noindex" />

    SAY HELLO

            Hi! I'm Kristie Chow
             and I'm a Computer Science major at Dartmouth College. Prior to college, I completed a Web Development crash-course at Dev Bootcamp in New York City,
              where my excitement for engineering came to life and I learned how to make websites just like this one you are enjoying now. I have so far worked professionally as a developer on four continents and have lived in ten cities, meeting inspiring people all along the way. I am thus intrigued by the potential to reduce both physical and digital space with virtual and augmented reality.

              When afk, I enjoy long-distance running, hiking, and eating tropical fruit. I am also eternally searching for the world's best chocolate chip cookie, and have curated a list of my personal favorites here.

            SPECIAL MENTIONS

            The Mahjouba Project with Eric Van Hove

            Tarsier Goggles at the DALI Lab

            Special Project Fellowship from the Dickey Center for International Understanding


text:
package util

/**
  * @author K.Sakamoto
  *         Created on 2016/08/08
  */
object FloatUtils {
  implicit def floatToFloatUtils(repr: Float): FloatUtils = {
    new FloatUtils(repr)
  }
}

/**
  * @author K.Sakamoto
  * @param repr float
  */
class FloatUtils(repr: Float) {
  def toHexString: String = {
    java.lang.Float.toHexString(repr)
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Orchard.Alias.Records;
using Orchard.Data;
using Orchard.Alias.Implementation.Holder;

namespace Orchard.Alias.Implementation.Storage {
    public interface IAliasStorage : IDependency {
        void Set(string path, IDictionary<string, string> routeValues, string source);
        IDictionary<string, string> Get(string aliasPath);
        void Remove(string path);
        void Remove(string path, string aliasSource);
        void RemoveBySource(string aliasSource);
        IEnumerable<Tuple<string, string, IDictionary<string, string>, string>> List();
        IEnumerable<Tuple<string, string, IDictionary<string, string>, string>> List(string sourceStartsWith);
    }

    public class AliasStorage : IAliasStorage {
        private readonly IRepository<AliasRecord> _aliasRepository;
        private readonly IRepository<ActionRecord> _actionRepository;
        private readonly IAliasHolder _aliasHolder;
        public AliasStorage(IRepository<AliasRecord> aliasRepository, IRepository<ActionRecord> actionRepository, IAliasHolder aliasHolder) {
            _aliasRepository = aliasRepository;
            _actionRepository = actionRepository;
            _aliasHolder = aliasHolder;
        }

        public void Set(string path, IDictionary<string, string> routeValues, string source) {
            if (path == null) {
                throw new ArgumentNullException("path");
            }

            var aliasRecord = _aliasRepository.Fetch(r => r.Path == path, o => o.Asc(r => r.Id), 0, 1).FirstOrDefault();
            aliasRecord = aliasRecord ?? new AliasRecord { Path = path };

            string areaName = null;
            string controllerName = null;
            string actionName = null;
            var values = new XElement("v");
            foreach (var routeValue in routeValues.OrderBy(kv => kv.Key, StringComparer.InvariantCultureIgnoreCase)) {
                if (string.Equals(routeValue.Key, "area", StringComparison.InvariantCultureIgnoreCase)
                    || string.Equals(routeValue.Key, "area-", StringComparison.InvariantCultureIgnoreCase)) {
                    areaName = routeValue.Value;
                }
                else if (string.Equals(routeValue.Key, "controller", StringComparison.InvariantCultureIgnoreCase)) {
                    controllerName = routeValue.Value;
                }
                else if (string.Equals(routeValue.Key, "action", StringComparison.InvariantCultureIgnoreCase)) {
                    actionName = routeValue.Value;
                }
                else {
                    values.SetAttributeValue(routeValue.Key, routeValue.Value);
                }
            }

            aliasRecord.Action = _actionRepository.Fetch(
                r => r.Area == areaName && r.Controller == controllerName && r.Action == actionName,
                o => o.Asc(r => r.Id), 0, 1).FirstOrDefault();
            aliasRecord.Action = aliasRecord.Action ?? new ActionRecord { Area = areaName, Controller = controllerName, Action = actionName };

            aliasRecord.RouteValues = values.ToString();
            aliasRecord.Source = source;
            if (aliasRecord.Action.Id == 0 || aliasRecord.Id == 0) {
                if (aliasRecord.Action.Id == 0) {
                    _actionRepository.Create(aliasRecord.Action);
                }
                if (aliasRecord.Id == 0) {
                    _aliasRepository.Create(aliasRecord);
                }
                // Bulk updates might go wrong if we don't flush
                _aliasRepository.Flush();
            }
            // Transform and push into AliasHolder
            var dict = ToDictionary(aliasRecord);
            _aliasHolder.SetAlias(new AliasInfo { Path = dict.Item1, Area = dict.Item2, RouteValues = dict.Item3 });
        }

        public IDictionary<string, string> Get(string path) {
            return _aliasRepository
                .Fetch(r => r.Path == path, o => o.Asc(r => r.Id), 0, 1)
                .Select(ToDictionary)
                .Select(item => item.Item3)
                .SingleOrDefault();
        }

        public void Remove(string path) {

            if (path == null) {
                throw new ArgumentNullException("path");
            }

            foreach (var aliasRecord in _aliasRepository.Fetch(r => r.Path == path)) {
                _aliasRepository.Delete(aliasRecord);
                // Bulk updates might go wrong if we don't flush
                _aliasRepository.Flush();
                var dict = ToDictionary(aliasRecord);
                _aliasHolder.RemoveAlias(new AliasInfo() { Path = dict.Item1, Area = dict.Item2, RouteValues = dict.Item3 });
            }
        }
        public void Remove(string path, string aliasSource) {

            if (path == null) {
                throw new ArgumentNullException("path");
            }

            foreach (var aliasRecord in _aliasRepository.Fetch(r => r.Path == path && r.Source == aliasSource)) {
                _aliasRepository.Delete(aliasRecord);
                // Bulk updates might go wrong if we don't flush
                _aliasRepository.Flush();
                var dict = ToDictionary(aliasRecord);
                _aliasHolder.RemoveAlias(new AliasInfo() { Path = dict.Item1, Area = dict.Item2, RouteValues = dict.Item3 });
            }
        }

        public void RemoveBySource(string aliasSource) {
            foreach (var aliasRecord in _aliasRepository.Fetch(r => r.Source == aliasSource)) {
                _aliasRepository.Delete(aliasRecord);
                // Bulk updates might go wrong if we don't flush
                _aliasRepository.Flush();
                var dict = ToDictionary(aliasRecord);
                _aliasHolder.RemoveAlias(new AliasInfo() { Path = dict.Item1, Area = dict.Item2, RouteValues = dict.Item3 });
            }
        }

        public IEnumerable<Tuple<string, string, IDictionary<string, string>, string>> List() {
            return _aliasRepository.Table.OrderBy(a => a.Id).Select(ToDictionary).ToList();
        }

        public IEnumerable<Tuple<string, string, IDictionary<string, string>, string>> List(string sourceStartsWith) {
            return _aliasRepository.Table.Where(a => a.Source.StartsWith(sourceStartsWith)).OrderBy(a => a.Id).Select(ToDictionary).ToList();
        }

        private static Tuple<string, string, IDictionary<string, string>, string> ToDictionary(AliasRecord aliasRecord) {
            IDictionary<string, string> routeValues = new Dictionary<string, string>();
            if (aliasRecord.Action.Area != null) {
                routeValues.Add("area", aliasRecord.Action.Area);
            }
            if (aliasRecord.Action.Controller != null) {
                routeValues.Add("controller", aliasRecord.Action.Controller);
            }
            if (aliasRecord.Action.Action != null) {
                routeValues.Add("action", aliasRecord.Action.Action);
            }
            if (!string.IsNullOrEmpty(aliasRecord.RouteValues)) {
                foreach (var attr in XElement.Parse(aliasRecord.RouteValues).Attributes()) {
                    routeValues.Add(attr.Name.LocalName, attr.Value);
                }
            }
            return Tuple.Create(aliasRecord.Path, aliasRecord.Action.Area, routeValues, aliasRecord.Source);
        }
    }
}


text:
namespace blink {

class XRViewport final : public ScriptWrappable {
  DEFINE_WRAPPERTYPEINFO();

 public:
  XRViewport(int x, int y, int width, int height)
      : x_(x), y_(y), width_(width), height_(height) {}

  int x() const { return x_; }
  int y() const { return y_; }
  int width() const { return width_; }
  int height() const { return height_; }

 private:
  int x_;
  int y_;
  int width_;
  int height_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_XR_XR_VIEWPORT_H_


text:
package version

var (
	// Package is filled at linking time
	Package = "github.com/containerd/containerd"

	// Version holds the complete version number. Filled in at linking time.
	Version = "1.0.0-beta.3+unknown"

	// Revision is filled with the VCS (e.g. git) revision being used to build
	// the program at linking time.
	Revision = ""
)


text:
package org.xmlactions.db.actions;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import junit.framework.TestCase;

import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import org.xmlactions.action.Action;
import org.xmlactions.action.NestedActionException;
import org.xmlactions.action.actions.BaseAction;
import org.xmlactions.common.xml.BadXMLException;
import org.xmlactions.common.xml.XMLObject;
import org.xmlactions.db.DBConfigException;
import org.xmlactions.db.actions.CommonStorageField;
import org.xmlactions.db.actions.Database;
import org.xmlactions.db.actions.Storage;
import org.xmlactions.db.actions.Xml;

public class XmlTest extends TestCase
{

	private final static Logger log = LoggerFactory.getLogger(XmlTest.class);

	public void testLoadDatabase()
			throws IOException, NestedActionException, ClassNotFoundException, InstantiationException,
			IllegalAccessException, InvocationTargetException, NoSuchMethodException, BadXMLException
	{

		Action action = new Action();
		String page = action.loadPage("src/test/resources", "db/storage.xml");
		BaseAction[] actions = action.processXML(UtilsTestHelper.getExecContext(), page);
		assertEquals("Invalid number of actions returned from processXML", 1, actions.length);

		assertTrue("Action [" + action.getClass().getName() + "] should be a Storage class",
				actions[0] instanceof Storage);

		Storage storage = (Storage) actions[0];
		List<Xml> xmls = storage.getXmls();
		assertEquals("Missing Xml from Storage:" + storage.getName(), 1, xmls.size());

		Xml xml = xmls.get(0);
		XMLObject xo = xml.getXml();
		assertNotNull("XMLObject not loaded for [" + xml.getResource() + "]", xo);
		// assertEquals("tracker", database.getName());
		// assertEquals("Invalid number of tables in database [" + database.getName() + "]", 11, database.getTables()
		// .size());
	}

	public void testGetStorageField()
			throws IOException, NestedActionException, ClassNotFoundException, InstantiationException,
			IllegalAccessException, InvocationTargetException, NoSuchMethodException, BadXMLException
	{

		Action action = new Action();
		String page = action.loadPage("src/test/resources", "db/storage.xml");
		BaseAction[] actions = action.processXML(UtilsTestHelper.getExecContext(), page);
		Storage storage = (Storage) actions[0];
		List<Database> databases = storage.getDatabases();
		CommonStorageField sf = databases.get(0).getStorageField("tb_tracker.id");
	}

	public void testBuildQuery()
			throws DBConfigException, IOException, NestedActionException, ClassNotFoundException,
			InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException,
			BadXMLException
	{

		Action action = new Action();
		String page = action.loadPage("src/test/resources", "db/storage.xml");
		BaseAction[] actions = action.processXML(UtilsTestHelper.getExecContext(), page);
		assertEquals("Invalid number of actions returned from processXML", 1, actions.length);

		assertTrue("Action [" + action.getClass().getName() + "] should be a Storage class",
				actions[0] instanceof Storage);

		Storage storage = (Storage) actions[0];
		Database database = storage.getDatabase("oneloginforall");
		String databaseName = "oneloginforall";
		String tableName = "tb_user_rights";
		String[] fields = new String[] { "tb_user_rights.id", "tb_user.name", "tb_projects.name",
				"tb_rights.permission" };
		String[] query = database.buildQuery(databaseName, tableName, fields, null, null, null, -1, -1);
		log.debug("query[0]:" + query[0]);
		log.debug("query[1]:" + query[1]);

	}
}


text:
"""Multi tab memory test.

This test is a multi tab test, but we're interested in measurements for
the entire test rather than each single page.
"""

import logging

from metrics import histogram_util
from telemetry.page import page_measurement

class MemoryPressure(page_measurement.PageMeasurement):
  def __init__(self, *args, **kwargs):
    super(MemoryPressure, self).__init__(*args, **kwargs)
    # _first_tab is used to access histograms
    self._is_first_page = True
    self._tab_count = 0

  # Allow histogram collection
  def CustomizeBrowserOptions(self, options):
    histogram_util.CustomizeBrowserOptions(options)

  # Open a new tab at each page
  def TabForPage(self, page, browser):
    return browser.tabs.New()

  def GetTabsHistogramCounts(self, tab):
    histogram_type = histogram_util.BROWSER_HISTOGRAM
    discard_count = histogram_util.GetHistogramCount(
      histogram_type, "Tabs.Discard.DiscardCount", tab)
    kill_count = histogram_util.GetHistogramCount(
      histogram_type, "Tabs.SadTab.KillCreated", tab)
    return (discard_count, kill_count)

  def MeasurePage(self, page, tab, results):
    # After navigating to each page, check if it triggered tab discards or
    # kills.
    (discard_count, kill_count) = self.GetTabsHistogramCounts(tab)
    # Done with this tab.  Disconnect cleanly from it to avoid a possible
    # TabCrashException if the tab is discarded or killed.
    tab.Disconnect()
    # Sanity check for first page
    if self._is_first_page:
      self._is_first_page = False
      assert discard_count == 0 and kill_count == 0

    self._tab_count += 1
    # End the test at the first kill or discard.
    if kill_count > 0 or discard_count > 0:
      logging.info("test ending at tab %d, discards = %d, kills = %d" %
        (self._tab_count, discard_count, kill_count))
      self.RequestExit()


text:
<?xml version="1.0" encoding="utf-8"?>
<extension version="1.7" type="plugin" group="geocode">
	<name>Geocode - ArcGISOnline</name>
	<author>HUBzero</author>
	<authorUrl>hubzero.org</authorUrl>
	<authorEmail>support@hubzero.org</authorEmail>
	<copyright>Copyright 2005-2019 HUBzero Foundation, LLC.</copyright>
	<license>http://opensource.org/licenses/MIT MIT</license>
	<description>ArcGISOnline provider for geocode</description>
	<files>
		<filename plugin="arcgisonline">arcgisonline.php</filename>
	</files>
	<languages>
		<language tag="en-GB">en-GB.plg_geocode_arcgisonline.ini</language>
	</languages>
	<config>
		<fields name="params">
			<fieldset name="basic">
				<field name="sourceCountry" type="text" menu="hide" label="Source Country" default="" description="Source Country" />
				<field name="useSsl" type="list" default="0" label="Use SSL" description="Use SSL?">
					<option value="0">No</option>
					<option value="1">Yes</option>
				</field>
			</fieldset>
		</fields>
	</config>
</extension>


text:
//===--- ArgumentList.cpp - Function and subscript argument lists -*- C++ -*==//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the logic for the Argument and ArgumentList classes.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/ArgumentList.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Expr.h"
#include "swift/AST/ParameterList.h"

using namespace swift;

Type swift::__Expr_getType(Expr *E) { return E->getType(); }

SourceRange Argument::getSourceRange() const {
  auto labelLoc = getLabelLoc();
  if (labelLoc.isInvalid())
    return getExpr()->getSourceRange();

  auto exprEndLoc = getExpr()->getEndLoc();
  if (exprEndLoc.isInvalid())
    return labelLoc;

  return SourceRange(labelLoc, exprEndLoc);
}

bool Argument::isInOut() const {
  return ArgExpr->isSemanticallyInOutExpr();
}

ArgumentList *ArgumentList::create(ASTContext &ctx, SourceLoc lParenLoc,
                                   ArrayRef<Argument> args, SourceLoc rParenLoc,
                                   Optional<unsigned> firstTrailingClosureIndex,
                                   bool isImplicit, ArgumentList *originalArgs,
                                   AllocationArena arena) {
  SmallVector<Expr *, 4> exprs;
  SmallVector<Identifier, 4> labels;
  SmallVector<SourceLoc, 4> labelLocs;

  bool hasLabels = false;
  bool hasLabelLocs = false;
  for (auto &arg : args) {
    exprs.push_back(arg.getExpr());

    hasLabels |= !arg.getLabel().empty();
    labels.push_back(arg.getLabel());

    hasLabelLocs |= arg.getLabelLoc().isValid();
    labelLocs.push_back(arg.getLabelLoc());
  }
  if (!hasLabels)
    labels.clear();
  if (!hasLabelLocs)
    labelLocs.clear();

  auto numBytes =
      totalSizeToAlloc<Expr *, Identifier, SourceLoc, ArgumentList *>(
          exprs.size(), labels.size(), labelLocs.size(), originalArgs ? 1 : 0);
  auto *mem = ctx.Allocate(numBytes, alignof(ArgumentList), arena);
  auto *argList = new (mem)
      ArgumentList(lParenLoc, rParenLoc, args.size(), firstTrailingClosureIndex,
                   originalArgs, isImplicit, hasLabels, hasLabelLocs);

  std::uninitialized_copy(exprs.begin(), exprs.end(),
                          argList->getExprsBuffer().begin());
  if (hasLabels) {
    std::uninitialized_copy(labels.begin(), labels.end(),
                            argList->getLabelsBuffer().begin());
  }
  if (hasLabelLocs) {
    std::uninitialized_copy(labelLocs.begin(), labelLocs.end(),
                            argList->getLabelLocsBuffer().begin());
  }
  if (originalArgs) {
    *argList->getTrailingObjects<ArgumentList *>() = originalArgs;
  }
  return argList;
}

ArgumentList *
ArgumentList::createParsed(ASTContext &ctx, SourceLoc lParenLoc,
                           ArrayRef<Argument> args, SourceLoc rParenLoc,
                           Optional<unsigned> firstTrailingClosureIndex) {
  return create(ctx, lParenLoc, args, rParenLoc, firstTrailingClosureIndex,
                /*implicit*/ false);
}

ArgumentList *ArgumentList::createTypeChecked(ASTContext &ctx,
                                              ArgumentList *originalArgs,
                                              ArrayRef<Argument> newArgs) {
  return create(ctx, originalArgs->getLParenLoc(), newArgs,
                originalArgs->getRParenLoc(), /*trailingClosureIdx*/ None,
                originalArgs->isImplicit(), originalArgs);
}

ArgumentList *ArgumentList::createImplicit(ASTContext &ctx, SourceLoc lParenLoc,
                                           ArrayRef<Argument> args,
                                           SourceLoc rParenLoc,
                                           AllocationArena arena) {
  return create(ctx, lParenLoc, args, rParenLoc,
                /*firstTrailingClosureIdx*/ None, /*implicit*/ true,
                /*originalArgs*/ nullptr, arena);
}

ArgumentList *ArgumentList::createImplicit(ASTContext &ctx,
                                           ArrayRef<Argument> args,
                                           AllocationArena arena) {
  return createImplicit(ctx, SourceLoc(), args, SourceLoc(), arena);
}

ArgumentList *ArgumentList::forImplicitSingle(ASTContext &ctx, Identifier label,
                                              Expr *arg) {
  return createImplicit(ctx, {Argument(SourceLoc(), label, arg)});
}

ArgumentList *ArgumentList::forImplicitUnlabeled(ASTContext &ctx,
                                                 ArrayRef<Expr *> argExprs) {
  SmallVector<Argument, 4> args;
  for (auto *argExpr : argExprs)
    args.push_back(Argument::unlabeled(argExpr));
  return createImplicit(ctx, args);
}

ArgumentList *ArgumentList::forImplicitCallTo(DeclNameRef fnNameRef,
                                              ArrayRef<Expr *> argExprs,
                                              ASTContext &ctx) {
  auto labels = fnNameRef.getArgumentNames();
  assert(labels.size() == argExprs.size());

  SmallVector<Argument, 8> args;
  for (auto idx : indices(argExprs))
    args.emplace_back(SourceLoc(), labels[idx], argExprs[idx]);

  return createImplicit(ctx, args);
}

ArgumentList *ArgumentList::forImplicitCallTo(ParameterList *params,
                                              ArrayRef<Expr *> argExprs,
                                              ASTContext &ctx) {
  assert(params->size() == argExprs.size());
  SmallVector<Argument, 8> args;
  for (auto idx : indices(argExprs)) {
    auto *param = params->get(idx);
    assert(param->isInOut() == argExprs[idx]->isSemanticallyInOutExpr());
    args.emplace_back(SourceLoc(), param->getArgumentName(), argExprs[idx]);
  }
  return createImplicit(ctx, args);
}

SourceLoc ArgumentList::getLoc() const {
  // If we have an unlabeled unary arg, return the start loc of the expr. This
  // preserves the behavior of when such argument lists were represented by
  // ParenExprs.
  if (auto *unary = getUnlabeledUnaryExpr())
    return unary->getStartLoc();
  return getStartLoc();
}

SourceRange ArgumentList::getSourceRange() const {
  auto start = LParenLoc;
  if (start.isInvalid()) {
    // Scan forward for the first valid source loc.
    for (auto arg : *this) {
      start = arg.getStartLoc();
      if (start.isValid())
        break;
    }
  }
  auto end = RParenLoc;
  if (hasAnyTrailingClosures() || RParenLoc.isInvalid()) {
    // Scan backward for the first valid source loc. We use getOriginalArgs to
    // filter out default arguments and get accurate trailing closure info.
    for (auto arg : llvm::reverse(*getOriginalArgs())) {
      end = arg.getEndLoc();
      if (end.isValid())
        break;
    }
  }
  if (start.isInvalid() || end.isInvalid())
    return SourceRange();

  return SourceRange(start, end);
}

ArrayRef<Identifier>
ArgumentList::getArgumentLabels(SmallVectorImpl<Identifier> &scratch) const {
  assert(scratch.empty());
  if (HasLabels)
    return getLabelsBuffer();
  scratch.append(size(), Identifier());
  return scratch;
}

Optional<unsigned> ArgumentList::findArgumentExpr(Expr *expr,
                                                  bool allowSemantic) const {
  if (allowSemantic)
    expr = expr->getSemanticsProvidingExpr();
  for (auto idx : indices(*this)) {
    auto *argExpr = getExpr(idx);
    if (allowSemantic)
      argExpr = argExpr->getSemanticsProvidingExpr();

    if (expr == argExpr)
      return idx;
  }
  return None;
}

Expr *ArgumentList::packIntoImplicitTupleOrParen(
    ASTContext &ctx, llvm::function_ref<Type(Expr *)> getType) const {
  assert(!hasAnyInOutArgs() && "Cannot construct bare tuple/paren with inout");

  // Make sure to preserve the source location info here and below as it may be
  // needed for e.g serialization of its textual representation.
  if (auto *unary = getUnlabeledUnaryExpr()) {
    auto *paren = new (ctx) ParenExpr(getLParenLoc(), unary, getRParenLoc());
    if (auto ty = getType(unary))
      paren->setType(ParenType::get(ctx, ty));
    paren->setImplicit();
    return paren;
  }

  SmallVector<Expr *, 2> argExprs;
  SmallVector<Identifier, 2> argLabels;
  SmallVector<SourceLoc, 2> argLabelLocs;
  SmallVector<TupleTypeElt, 2> tupleEltTypes;

  for (auto arg : *this) {
    auto *argExpr = arg.getExpr();
    argExprs.push_back(argExpr);
    argLabels.push_back(arg.getLabel());
    argLabelLocs.push_back(arg.getLabelLoc());
    if (auto ty = getType(argExpr))
      tupleEltTypes.emplace_back(ty, arg.getLabel());
  }
  assert(tupleEltTypes.empty() || tupleEltTypes.size() == argExprs.size());

  auto *tuple =
      TupleExpr::create(ctx, getLParenLoc(), argExprs, argLabels, argLabelLocs,
                        getRParenLoc(), /*implicit*/ true);
  if (empty() || !tupleEltTypes.empty())
    tuple->setType(TupleType::get(tupleEltTypes, ctx));

  return tuple;
}

Type ArgumentList::composeTupleOrParenType(
    ASTContext &ctx, llvm::function_ref<Type(Expr *)> getType) const {
  if (auto *unary = getUnlabeledUnaryExpr()) {
    auto ty = getType(unary);
    assert(ty);
    ParameterTypeFlags flags;
    if (get(0).isInOut()) {
      ty = ty->getInOutObjectType();
      flags = flags.withInOut(true);
    }
    return ParenType::get(ctx, ty, flags);
  }
  SmallVector<TupleTypeElt, 4> elts;
  for (auto arg : *this) {
    auto ty = getType(arg.getExpr());
    assert(ty);
    ParameterTypeFlags flags;
    if (arg.isInOut()) {
      ty = ty->getInOutObjectType();
      flags = flags.withInOut(true);
    }
    elts.emplace_back(ty, arg.getLabel(), flags);
  }
  return TupleType::get(elts, ctx);
}

bool ArgumentList::matches(ArrayRef<AnyFunctionType::Param> params,
                           llvm::function_ref<Type(Expr *)> getType) const {
  if (size() != params.size())
    return false;

  for (auto i : indices(*this)) {
    auto arg = get(i);
    auto &param = params[i];

    if (arg.getLabel() != param.getLabel())
      return false;

    if (arg.isInOut() != param.isInOut())
      return false;

    auto argTy = getType(arg.getExpr());
    assert(argTy && "Expected type for argument");
    auto paramTy = param.getParameterType();
    assert(paramTy && "Expected a type for param");

    if (arg.isInOut())
      argTy = argTy->getInOutObjectType();

    if (!argTy->isEqual(paramTy))
      return false;
  }
  return true;
}


text:
title: Greatest Common Factor Calculator
localeTitle: Calculadora de factor común más grande
---
## Calculadora de factor común más grande

Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/tools/calculators/greatest-common-factor-calculator/index.md) .

[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Más información:


text:
"use strict";
/**
 * The view model for the list of runs.
 *
 * @module runs/viewModel
 */
define(["knockout", "runs/filters/queryFilters", "runs/filters/queryFilter", "runs/filters", "runs/runTable"],
    function (ko, QueryFilters, QueryFilter, filters, runTable) {
        //Additionaly requires runTable
        ko.options.deferUpdates = true;
        filters.initialize();

        /**
         * Define the main view Model for the run list view.
         *
         * Currently manages the run filters only.
         * @exports runs/viewModel
         */
        var viewModel = {
            /**
             * The list of filters applied.
             * The concept currently used allows defining users their custom queries
             * using the <query-filter> HTML component (defined in {@link runs/filters})
             * that are joined together by "AND" (all filters entered must apply at once.
             * Additionally, there is a row of experiment statues (RUNNING, COMPLETED, ...)
             * joined by the "OR" connective that is stored
             * in the {@link viewModel.statusFilters} property.
             * the statusFilters clause and the user-defined filters are joined by AND.
             */
            queryFilters: ko.observable(new QueryFilters()),
            /**
             * Aliases for commonly used filters.
             */
            predefinedFilters: {
                "run-alive": new QueryFilter("status", "==", "\"RUNNING\""),
                "run-completed": new QueryFilter("status", "==", "\"COMPLETED\""),
                "run-queued": new QueryFilter("status", "==", "\"QUEUED\""),
                "run-failed": new QueryFilter("status", "==", "\"FAILED\""),
                "run-interrupted": new QueryFilter("status", "==", "\"INTERRUPTED\""),
                "run-dead": new QueryFilter("status", "==", "\"DEAD\""),
                "run-timeout": new QueryFilter("status", "==", "\"TIMEOUT\"")
            },
            /**
             * Currently applied status filters.
             */
            statusFilters: new QueryFilters("or"),

            /**
             * Transform the curent filters to their Data Transfer Object.
             *
             * @returns {QueryFilterDto} The object to be passed to the Sacredboard Web API.
             */
            getQueryFilterDto: function () {
                return this.queryFilters().toDto();
            },
            /**
             * @callback listenerCallback
             */
            /**
             * Subscribe to changes in the list of applied filters.
             *
             * @param {listenerCallback} listener - The listener function.
             */
            subscribe: function (listener) {
                this.queryFilters().filters.subscribe(listener);
            },

            /**
             * Reload the whole table from the backend.
             */
            reloadTable: function () {
                runTable.reload();
            },

            /**
             * Bind the view model to the view.
             * Should be called after {@link module:runs/viewModel.initialize}.
             */
            bind: function () {
                ko.applyBindings(this);
            },

            /**
             * Initialize the view model and the table of runs.
             *
             * Do not forget to call {@link bind} after that.
             *
             * @param {DOMNode|string} runTableSelector - The HTML <table> element or its selector (e.g. '#run-table')
             * for the list of runs.
             */
            initialize: function (runTableSelector) {
                /* By default, runs any state are displayed.
                 Add them to the statusFilters.q
                 */
                for (var key in this.predefinedFilters) {
                    this.statusFilters.addFilter(this.predefinedFilters[key]);
                }
                // Apply the statusFilters to the view filter.
                this.queryFilters().addFilter(this.statusFilters);

                runTable.initTable(runTableSelector);

                /*
                 * Attach a listener to the viewModel to update the query of
                 * runTable and reload.
                 */
                this.subscribe(function () {
                    runTable.queryFilter = viewModel.getQueryFilterDto();
                    runTable.reload();
                });
            }
        };
        return viewModel;
    });


text:
import os,sys
import numpy as np
import fitsio
from bokpipe.bokutil import BokMefImage,array_stats,stats_region
from bokpipe import bokproc

import argparse

class CCDMedianBackgroundFit(bokproc.BackgroundFit):
	def __init__(self,fits,**kwargs):
		self.statsReg = kwargs.pop('stats_reg','ccd_central_quadrant')
		self.method = kwargs.pop('method','median')
		super(CCDMedianBackgroundFit,self).__init__(fits,**kwargs)
		self.statsPix = stats_region(self.statsReg)
		self.medBack = {}
		for extn,data,hdr in fits:
			self.medBack[extn] = array_stats(data[self.statsPix],
			                                 method=self.method,clip=True)
			self.imShape = data.shape
	def get(self,extn):
		return self.medBack[extn] + np.zeros(self.imShape,dtype=np.float32)

parser = argparse.ArgumentParser()
parser.add_argument("input",type=str,
                    help="input FITS image")
parser.add_argument("-f","--fit",type=str,default='spline',
                    help="fit method (poly|[spline]|ccdmedian|ccdmean|ccdmode)")
parser.add_argument("--order",type=int,default=1,
                    help="fit order [default=1]")
parser.add_argument("--knots",type=int,default=2,
                    help="number of spline knots [default=2]")
parser.add_argument("--nbin",type=int,default=64,
                    help="amount of binning to apply before fit[default=64]")
parser.add_argument("-o","--output",type=str,
                    help="output FITS image")
parser.add_argument("-m","--mask",type=str,
                    help="mask FITS image")
parser.add_argument("-s","--statsreg",type=str,default='ccd_central_quadrant',
                    help="region to use for statistics (mean/median/mode)")
parser.add_argument('-v','--verbose',action='count',
                    help='increase output verbosity')
args = parser.parse_args()

fileName = args.input

fits = BokMefImage(fileName,mask_file=args.mask,read_only=True)

if args.fit == 'spline':
	backfit = bokproc.SplineBackgroundFit(fits,nKnots=args.knots,
	                                      order=args.order,nbin=args.nbin)
elif args.fit == 'poly':
	backfit = bokproc.PolynomialBackgroundFit(fits,
	                                          order=args.order,nbin=args.nbin)
elif args.fit == 'ccdmedian':
	backfit = CCDMedianBackgroundFit(fits,stats_reg=args.statsreg,
	                                 method=args.fit[3:])
else:
	raise ValueError

if not args.output:
	outfn = fileName.replace('.fits','_back.fits')
else:
	outfn = args.output

backfit.write(outfn,clobber=True)


text:
namespace guicpp {
Injector::Injector(internal::BindTable* bind_table)
    : bind_table_(bind_table) {}

Injector::~Injector() {}

// This is used to create Injector having all the bindings specified
// in module. This will call module->Configure().
// static
Injector* Injector::Create(const Module* module) {
  // injector owns the bind_table.
  Injector* injector = new Injector(new internal::BindTable());

  // Binder does not own the bind_table.
  Binder binder(injector->bind_table_.get());

  module->Configure(&binder);  // This will populate the bind_table.

  if (binder.num_errors() != 0) {
    GUICPP_LOG_(FATAL) << "Creation of Injector failed: "
                       << "Module had " << binder.num_errors() << " errors. ";
  }

  return injector;
}

}  // namespace guicpp


text:
import {NgModuleRef} from '@angular/core';
import {ComponentFixture} from '@angular/core/testing';
import {platformServerTesting} from '@angular/platform-server/testing';

import {MainModuleNgFactory} from '../alt/src/module.ngfactory';
import {MainModule} from '../src/module';

let mainModuleRef: NgModuleRef<MainModule> = null !;
beforeEach((done) => {
  platformServerTesting().bootstrapModuleFactory(MainModuleNgFactory).then((moduleRef: any) => {
    mainModuleRef = moduleRef;
    done();
  });
});

export function createModule(): NgModuleRef<MainModule> {
  return mainModuleRef;
}

export function createComponentAlt<C>(comp: {new (...args: any[]): C}): ComponentFixture<C> {
  const moduleRef = createModule();
  const compRef =
      moduleRef.componentFactoryResolver.resolveComponentFactory(comp).create(moduleRef.injector);
  return new ComponentFixture(compRef, null, false);
}


text:
using Serenity.Data;
using System;

namespace Serenity.ComponentModel
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = true)]
    public class RegisterPermissionKeyAttribute : PermissionAttributeBase
    {
        public RegisterPermissionKeyAttribute(object permission)
            : base(permission)
        {
        }

        public RegisterPermissionKeyAttribute(object module, object permission)
            : base(module, permission)
        {
        }

        public RegisterPermissionKeyAttribute(object module, object submodule, object permission)
            : base(module, submodule, permission)
        {
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Assets;
using HexTbs.Battle.Effects;
using HexTbs.Battle.Player;
using HexTbs.Battle.Unit.Weapons;
using HexTbs.Battle.Map;

namespace HexTbs.Battle.Unit.Actions
{
   public class VehicleAttackAction : BSquadAction
   {
      protected BPlayer Player { get; set; }
      protected BVehicleSquad Squad { get; set; }
      protected BSquad Enemy { get; set; }
      protected BVehicleWeapon Weapon {get; set; }

      protected bool hit = false;
      protected bool penetrated = false;
      protected bool over = false;
      protected int damageGiven = 0;

      protected List<BProjectileAnimation> projectiles = new List<BProjectileAnimation>();
      protected List<BExplosionEffect> explosions = new List<BExplosionEffect>();

      protected int shots;
      protected int shotsFired;

      public VehicleAttackAction(BPlayer player, BVehicleSquad squad, BSquad enemy, BVehicleWeapon weapon)
      {
         Cost = 2;

         Player = player;
         Squad = squad;
         Enemy = enemy;
         Weapon = weapon;

         // Projektiilit
         //projectiles = new List<BProjectileAnimation>();
         //explosions = new List<BExplosionEffect>();
         for (int i = 0; i < Weapon.ShotsAmount; i++)
         {
            int xplus = DieRoll.RollNormalDice(5, 1, 40, 0) - DieRoll.RollNormalDice(5, 1, 40, 0);
            int yplus = DieRoll.RollNormalDice(5, 1, 40, 0) - DieRoll.RollNormalDice(5, 1, 40, 0);
            BProjectileAnimation proj = new  BProjectileAnimation(Squad.Position, new Vector2(enemy.Position.X + xplus, enemy.Position.Y + yplus));
            proj.SetDelay(i * 100);
            projectiles.Add(proj);

         }
         Player.Effects.AddRange(projectiles);

         // Heitetään nopat
         int attackRoll = DieRoll.RollDice(1, 20, 0);
         int armorRoll = DieRoll.RollDice(1, 10, 0);
         int damageRoll = DieRoll.RollDice(1, 10, 0);

         int attack = GetAttack();
         int defend = GetDefend();

         int penetration = GetPenetration();
         int armor = GetArmour();

         int damage = GetDamage();
         int toughness = GetToughness();

         PrintHitChances(attack, defend);
         PrintPenetrationChances(penetration, armor);
         PrintDamageChances(damage, toughness);

         int attackGiven = attack - defend + attackRoll;
         if (attackGiven >= (20/2) && attackRoll != 1)
            hit = true;

         int penGiven = penetration - armor + armorRoll;
         if (penGiven >= (10/2))
            penetrated = true;

         if (enemy is BVehicleSquad)
         {
            if (hit)
            {
               if (penetrated)
               {
                  damageGiven = damage - toughness + damageRoll - 5;
               }
            }
         }
         else
         {

            damageGiven = damage - toughness + damageRoll - 5;
         }

         if (damageGiven < 0)
            damageGiven = 0;

         Console.WriteLine("Tulta " + attackGiven + " " + penGiven+ " " + damageGiven);

         // Turn the turrets
         squad.MainTurret.TurnTurret(enemy.Position);
      }

      protected void PrintHitChances(float a, float d)
      {
         float prob = (10f + (a - d)) / 20f;
         prob *= 100;

         if (prob >= 100)
            prob = 95;
         else if (prob < 0)
            prob = 0;

         Console.WriteLine("HitChange: " + prob + "%");
      }

      protected void PrintPenetrationChances(float p, float a)
      {
         float prob = (5f + (p - a)) / 10f;
         prob *= 100;

         if (prob >= 100)
            prob = 100;
         if (prob < 0)
            prob = 0;

         Console.WriteLine("Penetration: " + prob + "%");
      }

      protected void PrintDamageChances(float d, float t)
      {
         float prob = (5f + (d - t)) / 10f;
         prob *= 100;

         if (prob >= 100)
            prob = 100;

         Console.WriteLine("DamageChange: " + prob + "%");
      }

      protected int GetAttack()
      {
         int attack = Weapon.Accuracy;

         if (Squad.MoveCompleted)
            attack -= 2;

         if (attack < 0)
            attack = 0;

         return attack;
      }

      protected int GetDefend()
      {
         int defend = Enemy.Defence;
         return defend;
      }

      protected int GetDamage()
      {
         int damage = Weapon.FirePower;
         return damage;
      }

      protected int GetToughness()
      {
         int toughness = Enemy.Toughness;
         return toughness;
      }

      protected int GetArmour()
      {
         if (Enemy is BVehicleSquad)
         {
            BVehicleSquad e = Enemy as BVehicleSquad;
            HexDirection pAngle = BHex.AngleToDirection(MathRoutines.RadianToDegree(projectiles[0].Angle));
            HexDirection eAngle = e.Direction;

            int diff = BHex.DirectionDifference(pAngle, eAngle);
            if (diff == 0)
            {
               Console.WriteLine("REAR!");
               return e.RearArmor;
            }
            else if (diff == 1 || diff == 2)
            {
               Console.WriteLine("SIDE!");
               return e.SideArmor;
            }

            Console.WriteLine("FRONT!");
            return e.FrontArmor;
         }

         return 0;
      }

      protected int GetPenetration()
      {
         int penetration = Weapon.Penetration;
         return penetration;
      }

      public override bool IsDone()
      {
         return over;
      }

      public override void Update(GameTime gt)
      {
         bool projOver = true;
         foreach (BProjectileAnimation pj in projectiles)
         {
            if (!pj.IsOver())
               projOver = false;
         }

         bool expOver = true;
         foreach (BExplosionEffect ex in explosions)
         {
            if (!ex.IsOver())
               expOver = false;
         }

         // Matka päättyi, losauta
         List<BProjectileAnimation> remoProj = new List<BProjectileAnimation>();
         foreach (BProjectileAnimation proj in projectiles)
         {
            if (proj.IsOver())
            {
               BExplosionEffect exp = new BExplosionEffect(Enemy.Position);
               explosions.Add(exp);
               Player.Effects.Add(exp);
               remoProj.Add(proj);
            }
         }

         foreach (BProjectileAnimation proj in remoProj)
            projectiles.Remove(proj);

         List<BExplosionEffect> remoExp = new List<BExplosionEffect>();
         foreach (BExplosionEffect exp in explosions)
         {
            if (exp.IsOver())
            {
               remoExp.Add(exp);
            }
         }

         foreach (BExplosionEffect exp in remoExp)
            explosions.Remove(exp);

         // Räjähdys päättyi, lopeta
         if (expOver && projOver)
         {
            over = true;
         }

         // Lopuksi otetaan damaget
         if (over && penetrated && hit)
         {
            Enemy.TakeDamage(damageGiven);
         }
      }
   }
}


text:
etcd-php-client
===============

A simple PHP ETCD Client

Build Status
------------
[![Build Status](https://travis-ci.org/proudlygeek/etcd-php-client.svg?branch=master)](https://travis-ci.org/proudlygeek/etcd-php-client)

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

*TODO*


text:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;

namespace AntivirusForm
{
    class dumps
    {
        ///

        /// The main entry point for the application.
        ///

        public static class MINIDUMP_TYPE
        {
            public const int MiniDumpNormal = 0x00000000;
            public const int MiniDumpWithDataSegs = 0x00000001;
            public const int MiniDumpWithFullMemory = 0x00000002;
            public const int MiniDumpWithHandleData = 0x00000004;
            public const int MiniDumpFilterMemory = 0x00000008;
            public const int MiniDumpScanMemory = 0x00000010;
            public const int MiniDumpWithUnloadedModules = 0x00000020;
            public const int MiniDumpWithIndirectlyReferencedMemory = 0x00000040;
            public const int MiniDumpFilterModulePaths = 0x00000080;
            public const int MiniDumpWithProcessThreadData = 0x00000100;
            public const int MiniDumpWithPrivateReadWriteMemory = 0x00000200;
            public const int MiniDumpWithoutOptionalData = 0x00000400;
            public const int MiniDumpWithFullMemoryInfo = 0x00000800;
            public const int MiniDumpWithThreadInfo = 0x00001000;
            public const int MiniDumpWithCodeSegs = 0x00002000;
        }

        [DllImport("dbghelp.dll")]
        public static extern bool MiniDumpWriteDump(IntPtr hProcess,
                                                    Int32 ProcessId,
                                                    IntPtr hFile,
                                                    int DumpType,
                                                    IntPtr ExceptionParam,
                                                    IntPtr UserStreamParam,
                                                    IntPtr CallackParam);

        public void CurrentDomain_UnhandledException(string nombre)
        {
            CreateMiniDump(nombre);
        }

        private static void CreateMiniDump(string nombre)
        {
            using (FileStream fs = new FileStream(nombre+"Dump.dmp", FileMode.Create))
            {
                using (System.Diagnostics.Process process = System.Diagnostics.Process.GetProcessesByName(nombre)[0])
                {
                    MiniDumpWriteDump(process.Handle,
                                                     process.Id,
                                                     fs.SafeFileHandle.DangerousGetHandle(),
                                                     MINIDUMP_TYPE.MiniDumpNormal,
                                                     IntPtr.Zero,
                                                     IntPtr.Zero,
                                                     IntPtr.Zero);
                }
            }
        }
    }
}