text:
'use strict'
const fs = require('fs')
const path = require('path')

// add bash completions to your
//  yargs-powered applications.
module.exports = function completion (yargs, usage, command) {
  const self = {
    completionKey: 'get-yargs-completions'
  }

  // get a list of completion commands.
  // 'args' is the array of strings from the line to be completed
  self.getCompletion = function getCompletion (args, done) {
    const completions = []
    const current = args.length ? args[args.length - 1] : ''
    const argv = yargs.parse(args, true)
    const aliases = yargs.parsed.aliases

    // a custom completion function can be provided
    // to completion().
    if (completionFunction) {
      if (completionFunction.length < 3) {
        const result = completionFunction(current, argv)

        // promise based completion function.
        if (typeof result.then === 'function') {
          return result.then((list) => {
            process.nextTick(() => { done(list) })
          }).catch((err) => {
            process.nextTick(() => { throw err })
          })
        }

        // synchronous completion function.
        return done(result)
      } else {
        // asynchronous completion function
        return completionFunction(current, argv, (completions) => {
          done(completions)
        })
      }
    }

    const handlers = command.getCommandHandlers()
    for (let i = 0, ii = args.length; i < ii; ++i) {
      if (handlers[args[i]] && handlers[args[i]].builder) {
        const builder = handlers[args[i]].builder
        if (typeof builder === 'function') {
          const y = yargs.reset()
          builder(y)
          return y.argv
        }
      }
    }

    if (!current.match(/^-/)) {
      usage.getCommands().forEach((usageCommand) => {
        const commandName = command.parseCommand(usageCommand[0]).cmd
        if (args.indexOf(commandName) === -1) {
          completions.push(commandName)
        }
      })
    }

    if (current.match(/^-/)) {
      Object.keys(yargs.getOptions().key).forEach((key) => {
        // If the key and its aliases aren't in 'args', add the key to 'completions'
        const keyAndAliases = [key].concat(aliases[key] || [])
        const notInArgs = keyAndAliases.every(val => args.indexOf(`--${val}`) === -1)
        if (notInArgs) {
          completions.push(`--${key}`)
        }
      })
    }

    done(completions)
  }

  // generate the completion script to add to your .bashrc.
  self.generateCompletionScript = function generateCompletionScript ($0, cmd) {
    let script = fs.readFileSync(
      path.resolve(__dirname, '../completion.sh.hbs'),
      'utf-8'
    )
    const name = path.basename($0)

    // add ./to applications not yet installed as bin.
    if ($0.match(/\.js$/)) $0 = `./${$0}`

    script = script.replace(/{{app_name}}/g, name)
    script = script.replace(/{{completion_command}}/g, cmd)
    return script.replace(/{{app_path}}/g, $0)
  }

  // register a function to perform your own custom
  // completions., this function can be either
  // synchrnous or asynchronous.
  let completionFunction = null
  self.registerFunction = (fn) => {
    completionFunction = fn
  }

  return self
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="icon" href="/assets/images/favicon.png">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Rubik:400,400i,500,500i,700,700i" rel="stylesheet">
<link href="/assets/css/theme.css" rel="stylesheet">
<link href="/assets/css/custom.css" rel="stylesheet">

<meta name="description" content="Eu me recordo muito bem da noite do dia 31 de dezembro do ano passado. Eu e a Jo caminhávamos tranquilos de volta pra casa, felizes com o jantar que tínhamos...">

  <meta property="og:site_name" content="Fellipe Brito">

  <meta property="og:title" content="Tchau 2015">
  <meta property="og:type" content="article">
  <meta property="og:description" content="Eu me recordo muito bem da noite do dia 31 de dezembro do ano passado. Eu e a Jo caminhávamos tranquilos de volta pra casa, felizes com o jantar que tínhamos desfrutado e eu, todo ingênuo, falei pra ela -  Eu espero que 2015 seja igual 2014, se for assim está ótimo..."/>

  <meta property="og:image" content="http://fellipebrito.com/assets/images/img/bg/sunset.jpg" />
  <meta property="article:published_time" content="2015-12-31T00:00:00-06:00">
  <meta property="article:author" content="http://fellipebrito.com/about/">

  <meta property="og:url" content="http://fellipebrito.com/tchau-2015/" />

  <meta itemprop="keywords" content="fim de ano" />

  <meta property="article:tag" content="fim de ano">

    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsWow" aria-controls="navbarsWow" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Fellipe Brito | Crer também é pensar

                Home

                    Sobre

Fellipe Brito

             Fellipe Brito | Crer também é pensar

Conecte-se!

Newsletter

<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">

<form action="https://fellipebrito.us19.list-manage.com/subscribe/post?u=0794ba995c37a5e8a28edf28d&id=8bb58341f2" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

      <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="seuemail@gmail.com" required>

<input type="text" name="b_0794ba995c37a5e8a28edf28d_8bb58341f2" tabindex="-1" value="">

<input type="submit" value="Confirmar!" name="subscribe" id="mc-embedded-subscribe" class="button">

</form>

                         fim de ano

Tchau 2015

Eu me recordo muito bem da noite do dia 31 de dezembro do ano passado. Eu e a Jo caminhávamos tranquilos de volta pra casa, felizes com o jantar que tínhamos desfrutado e eu, todo ingênuo, falei pra ela: "Eu espero que 2015 seja igual 2014, se for assim está ótimo".

Não foi preciso esperar mais que 3 semanas para termos nossa vida sacudida de cabeça pra baixo. Ainda em janeiro nós tivemos péssimas notícias na empresa. Foram dias muito dificeis, de muito stress e muita, muita incerteza. Durante os primeiros 3 meses do ano, os mais dificeis, tivémos várias visitas do Brasil aqui. Foi uma mega lição de praticar o auto controle, superar as dificuldades e tentar ser um bom amigo e recebê-los bem.

Enfim, 2015 foi um ano como tantos outros, onde nós planejamos um monte de coisa e a maioria delas saíram diferente do que havíamos planejado. A arte da improvisação foi mais uma vez utilizada frequentemente.

Muita coisa boa aconteceu em 2015 também. E eu quero guardar alguns minutos para me inspirar nos conselhos do israelita profeta Jeremias e "Eu nunca vou me esquecer dos problemas, do sentimento de estar perdido, do gosto da cinza e do veneno que eu provei. Eu me lembro muito bem disso tudo - ah, como eu me lembro do sentimento de atingir o fundo do poço. Mas há outra coisa que eu me lembro muito bem, e lembrando disso eu me encho de esperança".

Eu me lembro dos dias com a minha melhor amiga. Dos incontáveis dias que fomos a praia, seja na Califórnia ou no Hawaii. Dos dias que fizemos exercício juntos, subimos montanhas em Hollywood e Malibu, Fizemos trilhas em Palos Verdes e no Waimea Canyon, andamos de carro, passeamos, fomos ao cinema em Hollywood ver Star Wars, comemoramos 10 anos de casamento no restaurante de Uma Linda Mulher em Beverly Hills e dividimos nossos sonhos e nossas dificuldades. Eu tenho certeza que quando eu fechar meus olhos pela última vez, você será a maior memória que levarei comigo.

Eu recebi amigos em casa, amigos queridos, que nos enchem de combustível para seguir com a aventura que é morar tão longe. Vilson e Dai, Fábio e Débora, Thiago, Carol e Noah! Foi ótimo ter vocês aqui, ao fechar este ano, vocês fazem parte das melhores lembranças dele. Obrigado pelo carinho!

Meus pais vieram me visitar. Não há palavras suficientes para explicar o que este tempo entre julho e agosto deste ano significaram para mim. Quanto tempo longe, quantas lágrimas, quantas incertezas e depois de tudo isso, quantas horas de diversão, carinho e novas lembranças criadas. Amo vocês, foi ótimo tê-los aqui e estou contando os dias para a próxima vez.

Em 2015 eu viajei, como sempre, Portland, costa da Califórnia e Hawaii. Eu fui a shows, U2 e TobyMac (de novo!), fui a corrida de Formula Indy, jogos da NBA, UFC, Museus, Jardins, Campeonatos de Surf, enfim, a vida foi de novo uma diversão.

Eu reli o que escrevi em 2012, 2013 e 2014 e cada vez mais eu chego a conclusão de que a vida é o que acontece enquanto nós planejamos o que fazer da vida.

Meu coração e minha oração é para que Deus me dê sabedoria para aproveitar cada dia aqui, fazer cada momento valer e ser sábio em cada decisão. E que eu possa abraçar a esperança em tempos ruins, porque se eu parar pra olhar o quanto eu tenho a agradecer, vou acabar não tendo tempo para sentir medo ou provar o gosto da incerteza.

2016, lá vamos nós!

                <time class="post-date" datetime="2015-12-31">31 Dec 2015</time>

                    « Tchau 2015

                    I think, therefore I believe »

    Please enable JavaScript to view the comments powered by Disqus.
    comments powered by Disqus

                Copyright © 2018 Fellipe Brito.

                "Affiliates Theme" - Design & Code by WowThemes.net

redpajama_set_name: RedPajamaGithub


text:
<?php

use app\components\db\Migration;
use yii\db\Query;

class m170810_040928_ua_attr_groups extends Migration
{
    public function safeUp()
    {
        $this->insert('agent_group', ['name' => 'SquidTracks']);

        $ikaRec = $this->getGroupId('IkaRec');
        $squidTracks = $this->getGroupId('SquidTracks');

        $this->batchInsert('agent_group_map', ['group_id', 'agent_name'], [
            [$ikaRec, 'IkaRec2'],
            [$squidTracks, 'SquidTracks'],
            [$squidTracks, 'SplatTrack'],
        ]);
    }

    public function safeDown()
    {
        $this->delete('agent_group_map', ['name' => [
            'IkaRec2',
            'SquidTracks',
            'SplatTrack',
        ]]);
        $this->delete('agent_group', ['name' => 'SquidTracks']);
    }

    private function getGroupId(string $name): int
    {
        $ret = (new Query())
            ->select('id')
            ->from('agent_group')
            ->where(['name' => $name])
            ->scalar();
        if (!$ret) {
            throw new \Exception('Invalid UA group name: ' . $name);
        }
        return (int)$ret;
    }
}


text:
package org.ovirt.engine.api.resource;

import javax.ws.rs.Path;

public interface MeasurableResource {

    @Path("statistics")
    public StatisticsResource getStatisticsResource();

}


text:
package com.pushtorefresh.storio3.test_without_rxjava.contentresolver;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;

import com.pushtorefresh.storio3.contentresolver.impl.DefaultStorIOContentResolver;
import com.pushtorefresh.storio3.contentresolver.operations.delete.DeleteResolver;
import com.pushtorefresh.storio3.contentresolver.operations.get.GetResolver;
import com.pushtorefresh.storio3.contentresolver.operations.put.PutResolver;
import com.pushtorefresh.storio3.contentresolver.queries.DeleteQuery;
import com.pushtorefresh.storio3.contentresolver.queries.Query;

import org.junit.Test;

import java.util.Collection;

import static org.mockito.Mockito.mock;

public class DefaultStorIOContentResolverTest {

    @Test
    public void instantiateWithoutRxJava() {
        // Should not fail
        DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .build();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void instantiateGetCursor() {
        DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .build()
                .get()
                .cursor()
                .withQuery(Query.builder()
                        .uri(mock(Uri.class))
                        .build())
                .withGetResolver(mock(GetResolver.class))
                .prepare();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void instantiateGetListOfObjects() {
        DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .build()
                .get()
                .listOfObjects(Object.class)
                .withQuery(Query.builder()
                        .uri(mock(Uri.class))
                        .build())
                .withGetResolver(mock(GetResolver.class))
                .prepare();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void instantiateGetObject() {
        DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .build()
                .get()
                .object(Object.class)
                .withQuery(Query.builder()
                        .uri(mock(Uri.class))
                        .build())
                .withGetResolver(mock(GetResolver.class))
                .prepare();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void instantiatePutObject() {
        DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .build()
                .put()
                .object(new Object())
                .withPutResolver(mock(PutResolver.class))
                .prepare();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void instantiatePutCollectionOfObjects() {
        DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .build()
                .put()
                .objects(mock(Collection.class))
                .withPutResolver(mock(PutResolver.class))
                .prepare();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void instantiatePutContentValues() {
        DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .build()
                .put()
                .contentValues(mock(ContentValues.class))
                .withPutResolver(mock(PutResolver.class))
                .prepare();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void instantiatePutContentValuesIterable() {
        DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .build()
                .put()
                .contentValues(mock(Iterable.class))
                .withPutResolver(mock(PutResolver.class))
                .prepare();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void instantiateDeleteByQuery() {
        DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .build()
                .delete()
                .byQuery(DeleteQuery.builder()
                        .uri(mock(Uri.class))
                        .build())
                .withDeleteResolver(mock(DeleteResolver.class))
                .prepare();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void instantiateDeleteObject() {
        DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .build()
                .delete()
                .object(new Object())
                .withDeleteResolver(mock(DeleteResolver.class))
                .prepare();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void instantiateDeleteCollectionOfObjects() {
        DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .build()
                .delete()
                .objects(mock(Collection.class))
                .withDeleteResolver(mock(DeleteResolver.class))
                .prepare();
    }
}


text:
package validator

import (
	"encoding/json"
	"testing"

	"github.com/cilium/cilium/pkg/checker"

	. "gopkg.in/check.v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"sigs.k8s.io/yaml"
)

func Test(t *testing.T) {
	TestingT(t)
}

// Hook up gocheck into the "go test" runner.
type CNPValidationSuite struct {
}

var _ = Suite(&CNPValidationSuite{})

func (s *CNPValidationSuite) Test_GH10643(c *C) {
	cnp := []byte(`apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: exampleapp
  namespace: examplens
spec:
  egress:
  - toFQDNs:
    - matchPattern: prefix*.tier.location.example.com
    toPorts:
    - ports:
      - port "8050"
      - protocol TCP
      - port "8051"
      - protocol TCP
      - port "8052"
      - protocol TCP
      - port "8053"
      - protocol TCP
      - port "8054"
      - protocol TCP
      - port "8055"
      - protocol TCP
      - port "8056"
      - protocol TCP
      - port "8057"
      - protocol TCP
      - port "8058"
      - protocol TCP
      - port "8059"
      - protocol TCP
  endpointSelector:
    matchExpressions:
    - key: app
      operator: In
      values:
      - example-app-0-spark-worker
      - example-app-0-spark-driver
      - example-app-0-spark-worker-qe3
      - example-app-0-spark-driver-qe3
      - example-app-1-spark-worker
      - example-app-1-spark-driver
      - example-app-1-spark-worker-qe3
      - example-app-1-spark-driver-qe3
`)
	jsnByte, err := yaml.YAMLToJSON(cnp)
	c.Assert(err, IsNil)

	us := unstructured.Unstructured{}
	err = json.Unmarshal(jsnByte, &us)
	c.Assert(err, IsNil)

	validator, err := NewNPValidator()
	c.Assert(err, IsNil)
	err = validator.ValidateCNP(&us)
	// Err can't be nil since validation should detect the policy is not correct.
	c.Assert(err, Not(IsNil))
}

func (s *CNPValidationSuite) Test_BadMatchLabels(c *C) {
	cnp := []byte(`apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: cnp-test-1
  namespace: ns-2
spec:
  egress:
  - toServices:
    - k8sService:
        namespace: default
        serviceName: kubernetes
  endpointSelector:
    matchLabels:
      key: app
      operator: In
      values:
      - prometheus
      - kube-state-metrics
`)
	jsnByte, err := yaml.YAMLToJSON(cnp)
	c.Assert(err, IsNil)

	us := unstructured.Unstructured{}
	err = json.Unmarshal(jsnByte, &us)
	c.Assert(err, IsNil)

	validator, err := NewNPValidator()
	c.Assert(err, IsNil)
	err = validator.ValidateCNP(&us)
	// Err can't be nil since validation should detect the policy is not correct.
	c.Assert(err, Not(IsNil))
}

func (s *CNPValidationSuite) Test_GoodCNP(c *C) {
	cnp := []byte(`apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: cnp-test-1
  namespace: ns-2
spec:
  egress:
  - toServices:
    - k8sService:
        namespace: default
        serviceName: kubernetes
  endpointSelector:
    matchLabels:
      key: app
      operator: In
`)
	jsnByte, err := yaml.YAMLToJSON(cnp)
	c.Assert(err, IsNil)

	us := unstructured.Unstructured{}
	err = json.Unmarshal(jsnByte, &us)
	c.Assert(err, IsNil)

	validator, err := NewNPValidator()
	c.Assert(err, IsNil)
	err = validator.ValidateCNP(&us)
	c.Assert(err, IsNil)
}

func (s *CNPValidationSuite) Test_GoodCCNP(c *C) {
	ccnp := []byte(`apiVersion: cilium.io/v2
kind: CiliumClusterwideNetworkPolicy
metadata:
  name: cnp-test-1
spec:
  egress:
  - toServices:
    - k8sService:
        namespace: default
        serviceName: kubernetes
  endpointSelector:
    matchLabels:
      key: app
      operator: In
`)
	jsnByte, err := yaml.YAMLToJSON(ccnp)
	c.Assert(err, IsNil)

	us := unstructured.Unstructured{}
	err = json.Unmarshal(jsnByte, &us)
	c.Assert(err, IsNil)

	validator, err := NewNPValidator()
	c.Assert(err, IsNil)
	err = validator.ValidateCCNP(&us)
	c.Assert(err, IsNil)
}

func (s *CNPValidationSuite) Test_BadCCNP(c *C) {
	// Bad CCNP with endpointSelector and nodeSelector
	ccnp := []byte(`apiVersion: cilium.io/v2
kind: CiliumClusterwideNetworkPolicy
metadata:
  name: cnp-test-1
spec:
  egress:
  - toServices:
    - k8sService:
        namespace: default
        serviceName: kubernetes
  endpointSelector:
    matchLabels:
      key: app
      operator: In
  nodeSelector:
    matchLabels:
      key: app
      operator: In
`)
	jsnByte, err := yaml.YAMLToJSON(ccnp)
	c.Assert(err, IsNil)

	us := unstructured.Unstructured{}
	err = json.Unmarshal(jsnByte, &us)
	c.Assert(err, IsNil)

	validator, err := NewNPValidator()
	c.Assert(err, IsNil)
	err = validator.ValidateCCNP(&us)
	// Err can't be nil since validation should detect the policy is not correct.
	c.Assert(err, Not(IsNil))
}

func (s *CNPValidationSuite) Test_UnknownFieldDetection(c *C) {
	tests := []struct {
		name        string
		policy      []byte
		clusterwide bool
		err         error
	}{
		{
			name: "neither a cnp or ccnp",
			policy: []byte(`
kind: ServiceAccount
apiVersion: v1
metadata:
  name: app1-account
`),
			clusterwide: false,
			err: ErrUnknownKind{
				kind: "ServiceAccount",
			},
		},

		{
			name: "cnp top-level description exists",
			policy: []byte(`
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
description: "default deny policy"
metadata:
  name: cnp-test-1
spec:
  endpointSelector: {}
`),
			clusterwide: false,
			err:         ErrTopLevelDescriptionFound,
		},
		{
			name: "cnp top-level description does not exist",
			policy: []byte(`
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: cnp-test-1
spec:
  endpointSelector: {}
`),
			clusterwide: false,
			err:         nil,
		},
		{
			name: "ccnp top-level description exists",
			policy: []byte(`
apiVersion: cilium.io/v2
kind: CiliumClusterwideNetworkPolicy
description: "default deny policy"
metadata:
  name: ccnp-test-1
spec:
  nodeSelector: {}
`),
			clusterwide: true,
			err:         ErrTopLevelDescriptionFound,
		},
		{
			name: "ccnp top-level description does not exist",
			policy: []byte(`
apiVersion: cilium.io/v2
kind: CiliumClusterwideNetworkPolicy
metadata:
  name: ccnp-test-1
spec:
  nodeSelector: {}
`),
			clusterwide: true,
			err:         nil,
		},

		{
			name: "cnp extra unknown fields",
			policy: []byte(`
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
foo: bar
metadata:
  name: ccnp-test-1
spec:
  endpointSelector: {}
  bar: baz
`),
			clusterwide: false,
			err: ErrUnknownFields{
				extras: []string{"foo", "spec.bar"},
			},
		},
		{
			name: "ccnp extra unknown fields",
			policy: []byte(`
apiVersion: cilium.io/v2
kind: CiliumClusterwideNetworkPolicy
foo: bar
metadata:
  name: ccnp-test-1
spec:
  nodeSelector: {}
  bar: baz
`),
			clusterwide: true,
			err: ErrUnknownFields{
				extras: []string{"foo", "spec.bar"},
			},
		},
		{
			name: "cnp specs",
			policy: []byte(`
apiVersion: "cilium.io/v2"
kind: CiliumNetworkPolicy
metadata:
  name: "cnp-specs"
specs:
  - description: "Policy to test multiple rules in a single file"
    endpointSelector:
      matchLabels:
        app: ratings
        version: v1
    ingress:
    - fromEndpoints:
      - matchLabels:
          app: reviews
          track: stable
          version: v1
      toPorts:
      - ports:
        - port: "9080"
          protocol: TCP
        rules:
          http:
          - method: "GET"
            path: "/health"
  - endpointSelector:
      matchLabels:
        app: details
        track: stable
        version: v1
    ingress:
    - fromEndpoints:
      - matchLabels:
          app: productpage
          track: stable
          version: v1
      toPorts:
      - ports:
        - port: "9080"
          protocol: TCP
        rules:
          http:
          - method: "GET"
            path: "/.*"
`),
			clusterwide: false,
			err:         nil,
		},
	}
	for _, tt := range tests {
		c.Log(tt.name)

		jsnByte, err := yaml.YAMLToJSON(tt.policy)
		c.Assert(err, IsNil)

		us := unstructured.Unstructured{}
		err = json.Unmarshal(jsnByte, &us)
		c.Assert(err, IsNil)

		validator, err := NewNPValidator()
		c.Assert(err, IsNil)

		if tt.clusterwide {
			c.Assert(validator.ValidateCCNP(&us), checker.DeepEquals, tt.err)
		} else {
			c.Assert(validator.ValidateCNP(&us), checker.DeepEquals, tt.err)
		}
	}
}


text:
class Music{
	shared_ptr<Mix_Music> music;
public:
	Music();
	Music(string file);

	void Play(int times);
	void Stop();
	void Open(string file);
	bool IsOpen();
};

#endif//MUSICHPP


text:
class AddPassowrdDigestToUsers < ActiveRecord::Migration
  def change
    add_column :users, :password_digest, :string
  end
end


text:
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "ifcpp/model/GlobalDefines.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingObject.h"
#include "IfcSweptAreaSolid.h"
class IFCQUERY_EXPORT IfcCurve;
class IFCQUERY_EXPORT IfcParameterValue;
class IFCQUERY_EXPORT IfcDirection;
//ENTITY
class IFCQUERY_EXPORT IfcFixedReferenceSweptAreaSolid : public IfcSweptAreaSolid
{
public:
	IfcFixedReferenceSweptAreaSolid() = default;
	IfcFixedReferenceSweptAreaSolid( int id );
	~IfcFixedReferenceSweptAreaSolid() = default;
	virtual shared_ptr<BuildingObject> getDeepCopy( BuildingCopyOptions& options );
	virtual void getStepLine( std::stringstream& stream ) const;
	virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
	virtual void readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map );
	virtual void setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self );
	virtual size_t getNumAttributes() { return 6; }
	virtual void getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const;
	virtual void getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const;
	virtual void unlinkFromInverseCounterparts();
	virtual const char* className() const { return "IfcFixedReferenceSweptAreaSolid"; }
	virtual const std::wstring toString() const;

	// IfcRepresentationItem -----------------------------------------------------------
	// inverse attributes:
	//  std::vector<weak_ptr<IfcPresentationLayerAssignment> >	m_LayerAssignment_inverse;
	//  std::vector<weak_ptr<IfcStyledItem> >					m_StyledByItem_inverse;

	// IfcGeometricRepresentationItem -----------------------------------------------------------

	// IfcSolidModel -----------------------------------------------------------

	// IfcSweptAreaSolid -----------------------------------------------------------
	// attributes:
	//  shared_ptr<IfcProfileDef>								m_SweptArea;
	//  shared_ptr<IfcAxis2Placement3D>							m_Position;					//optional

	// IfcFixedReferenceSweptAreaSolid -----------------------------------------------------------
	// attributes:
	shared_ptr<IfcCurve>									m_Directrix;
	shared_ptr<IfcParameterValue>							m_StartParam;				//optional
	shared_ptr<IfcParameterValue>							m_EndParam;					//optional
	shared_ptr<IfcDirection>								m_FixedReference;
};


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ScanActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:clickable="false"
        android:duplicateParentState="false"
        android:ems="10"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:longClickable="false"
        android:selectAllOnFocus="false"
        android:text="@string/click_the_button_to_start_or_stop_scanning" android:inputType="text">

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/scanText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/scanButton"
        android:layout_marginTop="17dp"
        android:clickable="false"
        android:duplicateParentState="false"
        android:ems="10"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:gravity="left|top"
        android:inputType="textMultiLine"
        android:longClickable="false" />

    <Button
        android:id="@+id/scanButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:onClick="onScanButtonClicked" />

</RelativeLayout><!-- From: file:/Users/justin/AndroidstudioProjects/IBeaconPoC/IBeaconPoC/src/main/res/layout/activity_scan.xml -->


text:
import setuptools

with open('README.md', 'r') as f:
    long_description = f.read()

setuptools.setup(
    name='django-unixdatetimefield',
    version='1.2.0',
    author='Niklas Andersson',
    author_email='nandersson900@gmail.com',
    description='UnixDateTimeField in Django',
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='https://github.com/Niklas9/django-unixdatetimefield',
    zip_safe=False,
    install_requires=[
        'django',
    ],
    tests_require=[
        'psycopg2',
        'django-nose',
    ],
    packages=setuptools.find_packages(),
    #test_suite='runtests.runtests',
    include_package_data=True,
    classifiers=[
        "Framework :: Django",
        "Intended Audience :: Developers",
        "Intended Audience :: System Administrators",
        "Operating System :: OS Independent",
        "Topic :: Software Development"
    ],
)


text:
#if HAVE_CONFIG_H
#  include <config.h>
#endif				/* HAVE_CONFIG_H */

#include <complib/cl_spinlock.h>

void cl_spinlock_construct(IN cl_spinlock_t * const p_spinlock)
{
	CL_ASSERT(p_spinlock);

	p_spinlock->state = CL_UNINITIALIZED;
}

cl_status_t cl_spinlock_init(IN cl_spinlock_t * const p_spinlock)
{
	CL_ASSERT(p_spinlock);

	cl_spinlock_construct(p_spinlock);

	/* Initialize with pthread_mutexattr_t = NULL */
	if (pthread_mutex_init(&p_spinlock->mutex, NULL))
		return (CL_ERROR);

	p_spinlock->state = CL_INITIALIZED;
	return (CL_SUCCESS);
}

void cl_spinlock_destroy(IN cl_spinlock_t * const p_spinlock)
{
	CL_ASSERT(p_spinlock);
	CL_ASSERT(cl_is_state_valid(p_spinlock->state));

	if (p_spinlock->state == CL_INITIALIZED) {
		p_spinlock->state = CL_UNINITIALIZED;
		pthread_mutex_lock(&p_spinlock->mutex);
		pthread_mutex_unlock(&p_spinlock->mutex);
		pthread_mutex_destroy(&p_spinlock->mutex);
	}
	p_spinlock->state = CL_UNINITIALIZED;
}

void cl_spinlock_acquire(IN cl_spinlock_t * const p_spinlock)
{
	CL_ASSERT(p_spinlock);
	CL_ASSERT(p_spinlock->state == CL_INITIALIZED);

	pthread_mutex_lock(&p_spinlock->mutex);
}

void cl_spinlock_release(IN cl_spinlock_t * const p_spinlock)
{
	CL_ASSERT(p_spinlock);
	CL_ASSERT(p_spinlock->state == CL_INITIALIZED);

	pthread_mutex_unlock(&p_spinlock->mutex);
}


text: Record the dribs and drabs of life


text:
@implementation FBSDKTVLoginButtonElement

#pragma mark - FBSDKDeviceLoginButtonDelegate

- (void)deviceLoginButtonDidCancel:(FBSDKDeviceLoginButton *)button
{
  [self dispatchEventWithName:@"onFacebookLoginCancel"
                    canBubble:YES
                  cancellable:YES
                    extraInfo:nil
                   completion:NULL];
}
- (void)deviceLoginButtonDidFail:(FBSDKDeviceLoginButton *)button error:(NSError *)error
{
  [self dispatchEventWithName:@"onFacebookLoginError"
                    canBubble:YES
                  cancellable:YES
                    extraInfo: @{ @"error": error }
                   completion:NULL];
}
- (void)deviceLoginButtonDidLogIn:(FBSDKDeviceLoginButton *)button
{
  [self dispatchEventWithName:@"onFacebookLogin"
                    canBubble:YES
                  cancellable:YES
                    extraInfo:nil
                   completion:NULL];
}
- (void)deviceLoginButtonDidLogOut:(FBSDKDeviceLoginButton *)button
{
  [self dispatchEventWithName:@"onFacebookLogout"
                    canBubble:YES
                  cancellable:YES
                    extraInfo:nil
                   completion:NULL];
}
@end


text:
/**
 * Utility class for JavaScript compatible UTF-8 encoding and decoding.
 *
 * @see
 * http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-output
 * @author John Topley
 */
package net.daw.helper.statics;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

public class EncodingUtilHelper {

    /**
     * Decodes the passed UTF-8 String using an algorithm that's compatible with
     * JavaScript's decodeURIComponent function. Returns
     * null if the String is null.
     *
     * @param s The UTF-8 encoded String to be decoded
     * @return the decoded String
     */
    public static String decodeURIComponent(String s) {
        if (s == null) {
            return null;
        }

        String result = null;

        try {
            result = URLDecoder.decode(s, "UTF-8");
        } // This exception should never occur.
        catch (UnsupportedEncodingException e) {
            result = s;
        }

        return result;
    }

    /**
     * Encodes the passed String as UTF-8 using an algorithm that's compatible
     * with JavaScript's encodeURIComponent function. Returns
     * null if the String is null.
     *
     * @param s The String to be encoded
     * @return the encoded String
     */
    public static String encodeURIComponent(String s) {
        String result = null;

        try {
            result = URLEncoder.encode(s, "UTF-8")
                    .replaceAll("\\+", "%20")
                    .replaceAll("\\%21", "!")
                    .replaceAll("\\%27", "'")
                    .replaceAll("\\%28", "(")
                    .replaceAll("\\%29", ")")
                    .replaceAll("\\%7E", "~");
        } // This exception should never occur.
        catch (UnsupportedEncodingException e) {
            result = s;
        }

        return result;
    }

    public static String quotate(String s) {
        return "\"" + s + "\"";
    }

    public static String stringifyAndQuotate(Date s) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String value = format.format(s);
        return "\"" + value + "\"";
    }

    /**
     * Private constructor to prevent this class from being instantiated.
     */
    private EncodingUtilHelper() {
        super();
    }
}


text: export { ManageUserComponent } from './manage-user.component';


text:
<?php

namespace PhpSsrs\ReportingService2010;

class ModelDrillthroughReport
{

  /**
   *
   * @var string $Path
   * @access public
   */
  public $Path = null;

  /**
   *
   * @var DrillthroughType $Type
   * @access public
   */
  public $Type = null;

  /**
   *
   * @param string $Path
   * @param DrillthroughType $Type
   * @access public
   */
  public function __construct($Path = null, $Type = null)
  {
    $this->Path = $Path;
    $this->Type = $Type;
  }

}


text:
cd $(dirname $(readlink -f $0))

source ../../utils/libdeploy.bash

link_package \
  ./config ${HOME}/.config/ranger


text:
<?xml version="1.0" encoding="utf-8" ?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
	android:interpolator="@android:anim/decelerate_interpolator">
   <!-- <scale android:fromXScale="0.8" android:toXScale="1.0"
		android:fromYScale="0.8" android:toYScale="1.0"
		android:pivotX="50%p" android:pivotY="50%p"
		android:duration="@android:integer/config_mediumAnimTime" />

	-->
	<translate
		android:interpolator="@android:anim/accelerate_interpolator"
		android:fromXDelta="0"
		android:toXDelta="0"
		android:fromYDelta="720"
		android:toYDelta="0"
		android:duration="@android:integer/config_longAnimTime" />
</set>
<!-- From: file:/C:/Users/qweas/Desktop/ZprogrammerTool/app/src/main/res/anim/fade.xml -->


text:
mod config;
mod constants;
mod request;
mod response;
mod transports;

#[macro_use]
extern crate log;
extern crate rustls;
#[cfg(test)]
extern crate serde_json;
extern crate url;

use url::Url;

pub use config::Config;
pub use constants::{HttpMethods, ResponseCode};
pub use request::Request;

use response::Response;
use transports::*;

pub struct Hasty {
    config: Config,
}

impl Hasty {
    /// Returns a default Hasty instance
    pub fn new() -> Hasty {
        Hasty {
            config: Config::new(),
        }
    }

    /// Returns a Hasty instance with user defined configuration
    ///
    /// # Example
    ///
    /// ```
    /// use hasty::{Config, Hasty};
    /// let config = Config::new().disable_https_security();
    /// let hasty = Hasty::new_with_config(config);
    /// ```
    pub fn new_with_config(config: Config) -> Hasty {
        Hasty { config: config }
    }

    /// Perform an http request and return a response
    ///
    /// # Example
    ///
    /// ```
    /// extern crate hasty;
    /// extern crate url;
    /// extern crate serde_json;
    ///
    /// fn main() {
    ///     use serde_json::{Value, Error};
    ///     use url::Url;
    ///     use hasty::{Hasty,Config,Request};
    ///     let config = Config::new().disable_https_security();
    ///     let mut request = Request::new();
    ///     request.set_url("https://localhost:3001/basic_get".parse().unwrap());
    ///
    ///     let mut hasty = Hasty::new_with_config(config);
    ///     let response = hasty.request(request).unwrap();
    ///     let body = String::from_utf8(response.body()).unwrap();
    ///     assert_eq!(&body, "success");
    /// }
    /// ```
    pub fn request(&mut self, request: Request) -> Result<Response, String> {
        match request.url() {
            Some(url) => {
                let mut transport = match url.scheme() {
                    "https" => {
                        HttpsTransport::new(url.host(), url.port_or_known_default(), &self.config)
                    }
                    "http" => {
                        HttpTransport::new(url.host(), url.port_or_known_default(), &self.config)
                    }
                    _ => Err("Unsupported protocol!".to_owned()),
                }?;

                let mut req = request.clone();
                req.set_url(url);
                Response::from_request(&mut transport, req)
            }
            None => Err("No URL provided".to_owned()),
        }
    }

    /// Perform an http get and return a response
    ///
    /// # Example
    ///
    /// ```
    /// extern crate hasty;
    /// extern crate url;
    /// extern crate serde_json;
    ///
    /// fn main() {
    ///     use serde_json::{Value, Error};
    ///     use url::Url;
    ///     use hasty::{Hasty,Config,Request};
    ///     let config = Config::new().disable_https_security();
    ///
    ///     let mut hasty = Hasty::new_with_config(config);
    ///     let response = hasty.get("https://localhost:3001/basic_get").unwrap();
    ///     let body = String::from_utf8(response.body()).unwrap();
    ///     assert_eq!(&body, "success");
    /// }
    /// ```
    pub fn get(&mut self, url: &str) -> Result<Response, String> {
        let url: Url = url.parse().map_err(|_| "Unable to parse url".to_owned())?;
        let mut transport = match url.scheme() {
            "https" => HttpsTransport::new(url.host(), url.port_or_known_default(), &self.config),
            "http" => HttpTransport::new(url.host(), url.port_or_known_default(), &self.config),
            _ => Err("Unsupported protocol!".to_owned()),
        }?;

        let mut req = Request::new();
        req.set_url(url);
        Response::from_request(&mut transport, req)
    }
}

#[test]
fn http_post_basic() {
    extern crate url;
    extern crate serde_json;

    use serde_json::Value;
    use Config;
    use Request;

    let config = Config::new().disable_https_security();
    let mut request = Request::new();
    request.set_url("https://localhost:3001/basic_post".parse().unwrap());
    request.set_method(HttpMethods::Post);
    request.add_raw_header("my-header".to_owned(), "looking good!".to_owned());

    let mut hasty = Hasty::new_with_config(config);
    let response = hasty.request(request).unwrap();
    let body = String::from_utf8(response.body()).unwrap();
    let json: Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["headers"]["my-header"], "looking good!");
}

#[test]
fn http_post_with_body() {
    extern crate url;
    extern crate serde_json;
    extern crate mime;

    use serde_json::Value;

    use Config;
    use Request;

    let config = Config::new().disable_https_security();
    let mut request = Request::new();
    request.set_url("https://localhost:3001/basic_post".parse().unwrap());
    request.set_method(HttpMethods::Post);
    request.set_body(Some(vec![1, 2, 3, 4]));
    request.set_content_type(mime::APPLICATION_OCTET_STREAM);

    let mut hasty = Hasty::new_with_config(config);
    let response = hasty.request(request).unwrap();
    let body = String::from_utf8(response.body()).unwrap();
    let json: Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["bodyLength"].as_f64(), Some(4.0));
}

#[test]
fn http_post_by_ip_with_body() {
    extern crate url;
    extern crate serde_json;
    extern crate mime;

    use serde_json::Value;

    use Config;
    use Request;

    let config = Config::new().disable_https_security();
    let mut request = Request::new();
    request.set_url("https://127.0.0.1:3001/basic_post".parse().unwrap());
    request.set_method(HttpMethods::Post);
    request.set_body(Some(vec![1, 2, 3, 4]));
    request.set_content_type(mime::APPLICATION_OCTET_STREAM);

    let mut hasty = Hasty::new_with_config(config);
    let response = hasty.request(request).unwrap();
    let body = String::from_utf8(response.body()).unwrap();
    let json: Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["bodyLength"].as_f64(), Some(4.0));
}

#[test]
fn http_post_basic_409() {
    extern crate url;
    extern crate serde_json;

    use serde_json::Value;
    use Config;
    use Request;

    let config = Config::new().disable_https_security();
    let mut request = Request::new();
    request.set_url("https://localhost:3001/basic_409".parse().unwrap());
    request.set_method(HttpMethods::Post);
    request.add_raw_header("my-header".to_owned(), "looking good!".to_owned());

    let mut hasty = Hasty::new_with_config(config);
    let response = hasty.request(request).unwrap();
    let body = String::from_utf8(response.body()).unwrap();
    assert!(body.len() == 0);
}


text:
@interface ASQueue ()
{
    bool _isMainQueue;
    dispatch_queue_t _queue;

    const char *_name;
}

@end

@implementation ASQueue

- (instancetype)initWithName:(const char *)name
{
    self = [super init];
    if (self != nil)
    {
        _name = name;

        _queue = dispatch_queue_create(_name, 0);
        dispatch_queue_set_specific(_queue, _name, (void *)_name, NULL);
    }
    return self;
}

- (void)dealloc
{
#if !OS_OBJECT_HAVE_OBJC_SUPPORT
    dispatch_release(_queue);
#endif
    _queue = nil;
}

+ (ASQueue *)mainQueue
{
    static ASQueue *queue = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^
    {
        queue = [[ASQueue alloc] init];
        queue->_queue = dispatch_get_main_queue();
        queue->_isMainQueue = true;
    });
    return queue;
}

- (dispatch_queue_t)nativeQueue
{
    return _queue;
}

- (bool)isCurrentQueue
{
    if (_queue == nil)
        return false;

    if (_isMainQueue)
        return [NSThread isMainThread];
    else
        return dispatch_get_specific(_name) == _name;
}

- (void)dispatchOnQueue:(dispatch_block_t)block
{
    [self dispatchOnQueue:block synchronous:false];
}

- (void)dispatchOnQueue:(dispatch_block_t)block synchronous:(bool)synchronous
{
    if (block == nil)
        return;

    if (_queue != nil)
    {
        if (_isMainQueue)
        {
            if ([NSThread mainThread])
                block();
            else if (synchronous)
                dispatch_sync(_queue, block);
            else
                dispatch_async(_queue, block);
        }
        else
        {
            if (dispatch_get_specific(_name) == _name)
                block();
            else if (synchronous)
                dispatch_sync(_queue, block);
            else
                dispatch_async(_queue, block);
        }
    }
}

@end


text:
<?php

namespace Composer\DependencyResolver;

/**
 * An extension of SplDoublyLinkedList with seek and removal of current element
 *
 * SplDoublyLinkedList only allows deleting a particular offset and has no
 * method to set the internal iterator to a particular offset.
 *
 * @author Nils Adermann <naderman@naderman.de>
 * @extends \SplDoublyLinkedList<RuleWatchNode>
 */
class RuleWatchChain extends \SplDoublyLinkedList
{
    /**
     * Moves the internal iterator to the specified offset
     *
     * @param int $offset The offset to seek to.
     * @return void
     */
    public function seek($offset)
    {
        $this->rewind();
        for ($i = 0; $i < $offset; $i++, $this->next());
    }

    /**
     * Removes the current element from the list
     *
     * As SplDoublyLinkedList only allows deleting a particular offset and
     * incorrectly sets the internal iterator if you delete the current value
     * this method sets the internal iterator back to the following element
     * using the seek method.
     *
     * @return void
     */
    public function remove()
    {
        $offset = $this->key();
        $this->offsetUnset($offset);
        $this->seek($offset);
    }
}


text:
using System.Collections.Generic;
using Bridge.Test.NUnit;

namespace Bridge.ClientTest.Batch3.BridgeIssues
{
    [Category(Constants.MODULE_ISSUES)]
    [TestFixture(TestNameFormat = "#1520 - {0}")]
    public class Bridge1520
    {
        public static decimal x = 30;

        [Test]
        public void TestStaticDecimalInitialization()
        {
            Assert.AreEqual("Decimal", x.GetType().Name, "decimal type");

            x++;
            Assert.True(31 == x, "31");
        }

        [Test]
        public void TestLocalDecimalInitialization()
        {
            decimal x = 100;
            Assert.AreEqual("Decimal", x.GetType().Name, "decimal type");

            x++;
            Assert.True(101 == x, "101");
        }

        [Test]
        public void TestUseCase()
        {
            decimal newVal = 12;
            CustomList item = new CustomList();
            item.value += newVal;

            Assert.AreEqual("Decimal", item.value.GetType().Name, "decimal type");
            Assert.True(19 == item.value, "19");
        }

        private class CustomList
        {
            public List<int> ranges = new List<int>();
            public decimal value = 7;
        }
    }
}


text:
// Author: Prasanna V. Loganathar
// Created: 9:29 PM 11-02-2015
// Project: RedScooby
// License: http://www.apache.org/licenses/LICENSE-2.0

using System;
using System.Threading.Tasks;
using RedScooby.Common.Resources;
using RedScooby.Infrastructure.Composition;
using RedScooby.Infrastructure.Location;

namespace RedScooby.ViewModels.Around
{
    public class AroundMeViewModel : ViewModelBase
    {
        public static TimeSpan Recency = TimeSpan.FromMinutes(2);
        private readonly LocationManager locationManager;
        private GeoPosition lastKnownLocation;
        private Address lastKnownAddress;
        private IDisposable listener;

        public AroundMeViewModel(LocationManager locationManager)
        {
            this.locationManager = locationManager;

            LastKnownLocation = locationManager.LastKnownPosition;
            LastKnownAddress = locationManager.LastKnownAddress;

            AddDisposable(this.locationManager.PositionChanges.Subscribe(x =>
            {
                LastKnownLocation = x;
                locationManager.UpdateAddressAsync();
            }));

            AddDisposable(this.locationManager.AddressChanges.Subscribe(x => LastKnownAddress = x));
        }

        public GeoPosition LastKnownLocation
        {
            get { return lastKnownLocation; }
            private set { SetAndNotifyIfChanged(ref lastKnownLocation, value); }
        }

        public Address LastKnownAddress
        {
            get
            {
                return lastKnownAddress == Address.UnknownAddress
                    ? new Address(GeoPosition.ZeroPosition, CommonStrings.DeterminingLocation)
                    : lastKnownAddress;
            }
            private set { SetAndNotifyIfChanged(ref lastKnownAddress, value); }
        }

        public Task EnsureRecentLocation()
        {
            return locationManager.EnsureRecentLocationAsync(Recency);
        }

        public Task EnsureRecentAddress()
        {
            return locationManager.EnsureRecentAddressAsync(Recency);
        }

        public void StartListeningForGeoUpdates()
        {
            if (listener == null)
                listener = locationManager.Listen();

            LastKnownLocation = locationManager.LastKnownPosition;
            LastKnownAddress = locationManager.LastKnownAddress;
        }

        public void StopListeningForGeoUpdates()
        {
            if (listener != null)
            {
                listener.Dispose();
                listener = null;
            }
        }
    }
}


text:
@*
 * Copyright 2022 HM Revenue & Customs
 *
 * 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.
 *@

@import play.api.i18n._

@this()

@(formItem:Form[_],
  dateFieldName: String,
  dayFieldName: String,
  monthFieldName: String,
  yearFieldName: String,
  label: Html, args: (Symbol,Any)*
)(implicit messages: Messages)

@argsMap = @{args.toMap}
@dateErrors = @{formItem(dateFieldName).errors}

    <fieldset class="govuk-fieldset" role="group" aria-describedby="dob-hint@if(dateErrors.nonEmpty){ dob-error}">
        <legend class="govuk-fieldset__legend">
            @label
        </legend>
        @if(argsMap.contains('_hintText)) {

                @argsMap.get('_hintText)

        }
        @if(dateErrors.nonEmpty) {
            @messages(dateErrors.head.message)
        }

                        @messages("Service.field.dob.day")

                    <input class="govuk-input govuk-date-input__input govuk-input--width-2" id="@dayFieldName" name="@dayFieldName" type="text" pattern="[0-9]*" inputmode="numeric" value="@{formItem(dayFieldName).value}">

                        @messages("Service.field.dob.month")

                    <input class="govuk-input govuk-date-input__input govuk-input--width-2" id="@monthFieldName" name="@monthFieldName" type="text" pattern="[0-9]*" inputmode="numeric" value="@{formItem(monthFieldName).value}">

                        @messages("Service.field.dob.year")

                    <input class="govuk-input govuk-date-input__input govuk-input--width-4" id="@yearFieldName" name="@yearFieldName" type="text" pattern="[0-9]*" inputmode="numeric"  value="@{formItem(yearFieldName).value}">

    </fieldset>


text:
echo "==== Compiling mainwindow design... ===="
pyuic4 "../include/mainwindow.ui" -o "../include/design.py"
echo "==== Compilation terminated. ===="
./main.py


text:
layout: post
title: "Getting Started: Python Decorators"
description: "A decorator is a function that wraps another function to enhance its functionality with actually modifying source code of the function."
tags: [python]
comments: true
---

This post will help you in getting started with Python decorators through some real life examples. Some familiarity with Python language is expected.

Before directly jumping into decorators, let's take a step back and start with python functions.  This will help in understanding the concept in a better way.

### Functions

A function in python can be defined as follows:

~~~ python
def introduce(name):
    return 'My name is %s' % name

~~~

This function takes `name` as input and return a string, where:

* *def* is the keyword used to define a function.
* *introduce* is the name of the function.
* Variable inside parenthesis (*name*) is the required argument for the function.
* Next line is the body or definition of the function.

### Function Properties

In python, functions are treated as first-class objects. This means that python treats functions as values. We can assign function to a variable, pass as an
argument to a function or return as a value from a function.

~~~ python
def print_hello_world():
    print('Hello World!')
~~~

We have defined a function `print_hello_world'. Now we can assign it to a
variable.

~~~ python
>>> modified_world = print_hello_world
~~~
(Here >\>> is denoting the python  interactive shell)

Now we can call `modified_world` just like the function `print_hello_world`.

~~~
>>>modified_world()
Hello World!
~~~

We can also pass a function to another function as an argument.

~~~ python
def execute(func):
    print('Before execution')
    func()
    print('After execution')
~~~

So now when we pass `print_hello_world` function to `execute` function, the output will be as follows:

~~~ python
>>>execute(print_hello_world)
Before execution
Hello World!
After execution
~~~

Python also supports nesting of functions. It means we can define another function in body or definition of some other function.
Example:

~~~python
def foo(x):
    def bar(y):
        return x+y
    return bar
~~~

In the above example, we have used two concepts described before.
1. Returning a function (bar) as a return value of the function `foo`.
2. Nesting function `bar` in the definition of the function `foo`.

Let's see this code in action.

~~~ python
>>>v1 = foo(2)
~~~

Here `v1` stores the return value of the function `foo` which is another function `bar`. Now what will happen if we call `v1` with some parameter?

~~~ python
>>>print(v1(5))
7
~~~

When a function is handled as data (in our case, return as a value from another
        function), it implicitly carries information required to execute the function. This is called **closures** in python. We can check the closure of the function using `__closure__` attribute of the function. This will return a tuple containing all the closures of the function. If you want to see any content of the closure, you can do something like `v1.__closure__[0].cell_contents`.

~~~ python
>>>v1.__closure__
(<cell at 0x7f4368e6c590: int object at 0xa41140>,)
>>>v1.__closure__[0].cell_contents
2
~~~

So now, we understood both function properties. Let's see how can we use these properties in real scenarios.

### Going Ahead

Suppose we want to perform some generic functionality before or/and after function execution. It can be like printing execution time of the function.

One way to do this is by writing whatever we want to do before and after execution as initial and final statements respectively.
Example:

~~~ python
def print_hello_world():
    print('Before Execution')
    print('Hello World!')
    print('After Execution')
~~~

Is this a good way. I leave it to you. What will happen if I have several functions and need to perform the same task for all other functions too?

Another way could be to write a function that will take any other function as an argument and return the function along with performing the task before and after function execution.
Example:

~~~ python
def print_hello_world():
    print('Hello World')

def dec(func):
    def nest_func(*args, **kwargs):
        print('Before Execution')
        r =  func(*args, **kwargs)
        print('After Execution')
        return r
    return nest_func
~~~

Function `print_hello_world` just prints 'Hello World'. Function `dec` takes a
function as an argument, creates another function `nest_func` in its
definition. `nest_func` prints some statements before and after execution of
function passed as an argument in function `dec`.

Let's pass the function `print_hello_world` to `dec`.

~~~ python
>>> new_print_hello_world = dec(print_hello_world)
~~~

`new_print_function` is another function returned by the function `dec`. What
will be the output on calling `new_print_hello_world` function? Let's check it.

~~~ python
>>> new_print_hello_world()
Before Execution
Hello World
After Execution
~~~

What if, we assign the new function returned by the `dec` function to
`print_hello_world` function again?

~~~ python
>>> print_hello_world = dec(print_hello_world)
~~~

Let's call `print_hello_world` function now.

~~~ python
>>> print_hello_world()
Before Execution
Hello World!
After Execution
~~~

So we basically we have changed the functionality of the function
`print_hello_world` without changing the source code of the function itself.

So What next? If are clear till now, then you have already learnt about
decorators. Let me explain explicitly.

### Decorators

A decorator is a function which provides us the freedom to enhance or change
the functionality of any function dynamically, without making changes in the
code of the function.

In our case, function `dec` provides us this functionality (As it changes the
functionality of the function `print_hello_world`). So `dec` is called as
*decorator*.
Instead of passing `print_hello_world` explicitly to function `dec`, we can use
its shorthand syntax:

~~~ python
@dec
def print_hello_world():
    print('Hello World')
~~~

I hope by now we are clear about decorators. You might be wondering why do I
need to return a function from the `dec` function? Just call the function
in `dec` itself in which we can print statements along with executing the
function passed as argument.
Example:

~~~ python
def dec1(func):
    print('Before Execution')
    func()
    print('After Execution')
~~~

I have few questions for you in answer to this question. Suppose I agree with
you and decides to do it as suggested.

~~~ python
>>>print_hello_world = dec1(print_hello_world)
~~~

1. What value does `print_hello_world` store right now? Can you call it now?
(It is storing None which is return value of the function `dec1`. So you can't
 call `print_hello_world` now)
2. What if we want to enhance function having some arguments. One suggestion
could be like

~~~ python
def dec2(func, arg1, arg2):
    print('Before Execution')
    func(arg1, arg2)
    print('After Execution')
~~~

But here the problem is how will we get the value of arg1 and arg2 at time of
passing any function to `dec2`.

~~~ python
>>> print_hello_world = dec2(print_hello_world, arg1, arg2)
~~~

Here we will not be able to get the value of arg1 and arg2.

I hope above two points have cleared your doubts about why decorators are
required to return a function.

### Decorator Examples

* It can be used to compute execution time of any function.

~~~ python
def compute_execution_time(func):
    def nest_func(*args, **kwargs):
        start = time.time()
        response = func(*args, **kwargs)
        end = time.time()
        print(end-start)
        return response
    return nest_func
~~~

* In web applications, it can be used to check if user is logged in or not.

~~~ python
def login_required(func):
    def nest_function(request, *args, **kwargs):
        if request.user.is_authenticated():
            return func(request, *args, **kwargs)
        else
            return redirect('/login')
    return nest_function
~~~

I hope this article provided you a basic idea of python decorators and some of
its use cases. If you have any doubt or have any feedback, you can reach out to
me at udr [dot] ritesh [at] gmail [dot] com.


text:
"use strict";
var _ = require("lodash");
var SarathiClient = require("./SarathiClient");
var methodDefaults = require("../commons/defaults").methodDefaults;
var DiscoveryStrategy = require("sarathi-discovery-strategy");

var globalDefaults = {
	methods: {}, // methods to define on this client and their endpoints and other parameters
	loadBalancer: { // Load balancer config
		strategy: "round-robin" // random, disabled
	},
	discoveryStrategy: undefined,
	restClient: { // Rest client config
		retry: 2, // number of retries on failure before returning error; value 2 means: 1 + 2 = 3 max calls.
		timeout: 2000 // REST call timeout
	},
	_state: {}
};

function SarathiClientBuilder(options) {
    var instance = this;
    if (!(this instanceof SarathiClientBuilder)) {
        return new SarathiClientBuilder(options);
    }

    var globalConfig = {};
	_.merge(globalConfig, globalDefaults, options);

	// Enable testing of properties
	if (process.env.NODE_ENV === "test") {
		instance._globalConfig = globalConfig;
	}

    this.setConfig = function(options) {
        _.merge(globalConfig, globalDefaults, options);
        return this;
    };

    this.addMethod = function(methodName, options) {
        var methodOptions;
        if (_.isString(options)) {
			methodOptions = {url: options};
        } else {
			methodOptions = options;
        }

        globalConfig.methods[methodName] = methodOptions;
        return this;
    };

	this.setMethods = function(methodConfig) {
		globalConfig.methods = methodConfig;
		return this;
	};

	this.setRestClientConfig = function(restClientConfig) {
		globalConfig.restClient = restClientConfig;
		return this;
	};

	this.setRetryCount = function(retryCount) {
		globalConfig.restClient.retry = retryCount;
		return this;
	};

    this.setLoadBalanceStrategy = function(strategy) {
        globalConfig.loadBalancer.strategy = strategy;
        return this;
    };

	this.setDiscoveryStrategy = function(discoveryStrategyInst) {
		if (!(discoveryStrategyInst instanceof DiscoveryStrategy)) {
			throw new Error("discoveryStrategy must be an instace of DiscoveryStrategy from sarathi-discovery-strategy package.");
		}
		globalConfig._state.discoveryHandler = discoveryStrategyInst;
		return this;
	};

	this.newMethodDefaults = function() {
        return _.merge({}, methodDefaults);
    };

    this.build = function() {
		if (globalConfig.discoveryStrategy && globalConfig.discoveryStrategy instanceof DiscoveryStrategy) {
			globalConfig._state.discoveryHandler = globalConfig.discoveryStrategy;
		}

		// Only if someone tries to sneak past.
		if (!(globalConfig._state.discoveryHandler instanceof DiscoveryStrategy)) {
			throw new Error("discoveryStrategy must be an instace of DiscoveryStrategy from sarathi-discovery-strategy package.");
		}

        return new SarathiClient(globalConfig);
    };
}

module.exports = SarathiClientBuilder;


text:
package org.openehealth.ipf.commons.ihe.xds.core.transform.requests.ebxml30;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.openehealth.ipf.commons.ihe.xds.core.ebxml.EbXMLAdhocQueryRequest;
import org.openehealth.ipf.commons.ihe.xds.core.ebxml.EbXMLSlot;
import org.openehealth.ipf.commons.ihe.xds.core.ebxml.ebxml30.EbXMLFactory30;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.*;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetAllQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.QueryList;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.QueryType;
import org.openehealth.ipf.commons.ihe.xds.core.transform.requests.QueryParameter;
import org.openehealth.ipf.commons.ihe.xds.core.transform.requests.query.GetAllQueryTransformer;

/**
 * Tests for {@link GetAllQueryTransformer}.
 * @author Jens Riemschneider
 */
public class GetAllQueryTransformerTest {
    private GetAllQueryTransformer transformer;
    private GetAllQuery query;
    private EbXMLAdhocQueryRequest ebXML;

    @Before
    public void setUp() {
        transformer = new GetAllQueryTransformer();
        query = new GetAllQuery();

        query.setPatientId(new Identifiable("id1", new AssigningAuthority("uni1", "uniType1")));
        QueryList<Code> confidentialityCodes = new QueryList<Code>();
        confidentialityCodes.getOuterList().add(
                Arrays.asList(new Code("code10", null, "scheme10"), new Code("code11", null, "scheme11")));
        confidentialityCodes.getOuterList().add(
                Arrays.asList(new Code("code12", null, "scheme12")));
        query.setConfidentialityCodes(confidentialityCodes);
        query.setFormatCodes(Arrays.asList(new Code("code13", null, "scheme13"), new Code("code14", null, "scheme14")));
        query.setStatusDocuments(Arrays.asList(AvailabilityStatus.APPROVED, AvailabilityStatus.SUBMITTED));
        query.setStatusFolders(Arrays.asList(AvailabilityStatus.DEPRECATED));
        query.setStatusSubmissionSets(Arrays.asList(AvailabilityStatus.SUBMITTED));
        query.setHomeCommunityId("12.21.41");
        query.setDocumentEntryTypes(Arrays.asList(DocumentEntryType.STABLE));

        ebXML = new EbXMLFactory30().createAdhocQueryRequest();
    }

    @Test
    public void testToEbXML() {
        transformer.toEbXML(query, ebXML);
        assertEquals(QueryType.GET_ALL.getId(), ebXML.getId());
        assertEquals("12.21.41", ebXML.getHome());

        assertEquals(Arrays.asList("'id1^^^&uni1&uniType1'"),
                ebXML.getSlotValues(QueryParameter.PATIENT_ID.getSlotName()));

        List<EbXMLSlot> slots = ebXML.getSlots(QueryParameter.DOC_ENTRY_CONFIDENTIALITY_CODE.getSlotName());
        assertEquals(2, slots.size());
        assertEquals(Arrays.asList("('code10^^scheme10')", "('code11^^scheme11')"), slots.get(0).getValueList());
        assertEquals(Arrays.asList("('code12^^scheme12')"), slots.get(1).getValueList());

        assertEquals(Arrays.asList("('code13^^scheme13')", "('code14^^scheme14')"),
                ebXML.getSlotValues(QueryParameter.DOC_ENTRY_FORMAT_CODE.getSlotName()));

        assertEquals(Arrays.asList("('urn:oasis:names:tc:ebxml-regrep:StatusType:Approved')", "('urn:oasis:names:tc:ebxml-regrep:StatusType:Submitted')"),
                ebXML.getSlotValues(QueryParameter.DOC_ENTRY_STATUS.getSlotName()));

        assertEquals(Arrays.asList("('urn:oasis:names:tc:ebxml-regrep:StatusType:Deprecated')"),
                ebXML.getSlotValues(QueryParameter.FOLDER_STATUS.getSlotName()));

        assertEquals(Arrays.asList("('urn:oasis:names:tc:ebxml-regrep:StatusType:Submitted')"),
                ebXML.getSlotValues(QueryParameter.SUBMISSION_SET_STATUS.getSlotName()));

        assertEquals(Arrays.asList("('urn:uuid:7edca82f-054d-47f2-a032-9b2a5b5186c1')"),
                ebXML.getSlotValues(QueryParameter.DOC_ENTRY_TYPE.getSlotName()));

        assertEquals(8, ebXML.getSlots().size());
    }

    @Test
    public void testToEbXMLNull() {
        transformer.toEbXML(null, ebXML);
        assertEquals(0, ebXML.getSlots().size());
    }

    @Test
    public void testToEbXMLEmpty() {
        transformer.toEbXML(new GetAllQuery(), ebXML);
        assertEquals(0, ebXML.getSlots().size());
    }

    @Test
    public void testFromEbXML() {
        transformer.toEbXML(query, ebXML);
        GetAllQuery result = new GetAllQuery();
        transformer.fromEbXML(result, ebXML);

        assertEquals(query, result);
    }

    @Test
    public void testFromEbXMLNull() {
        GetAllQuery result = new GetAllQuery();
        transformer.fromEbXML(result, null);
        assertEquals(new GetAllQuery(), result);
    }

    @Test
    public void testFromEbXMLEmpty() {
        GetAllQuery result = new GetAllQuery();
        transformer.fromEbXML(result, ebXML);
        assertEquals(new GetAllQuery(), result);
    }
}


text:
YUI.add('aui-image-viewer-media-tests', function(Y) {

    var suite = new Y.Test.Suite('aui-image-viewer-media');

    suite.add(new Y.Test.Case({
        name: 'Media Viewer Plugin Tests',

        tearDown: function() {
            if (this._imageViewer) {
                this._imageViewer.destroy();
            }
        },

        _createImageViewer: function(config) {
            this._imageViewer = new Y.ImageViewer(Y.merge({
                caption: 'Some Caption',
                links: '#viewer a',
                plugins: [
                    {
                        fn: Y.MediaViewerPlugin
                    }
                ],
                preloadNeighborImages: false,
                zIndex: 1
            }, config || {})).render();
        },

        'should still work with images': function() {
            var instance = this,
                image,
                imageContainer;

            this._createImageViewer({
                thumbnailsConfig: false
            });

            this._imageViewer.getLink('1').simulate('click');

            image = this._imageViewer._getCurrentImage();
            imageContainer = image.get('parentNode');

            Y.Assert.isTrue(
                imageContainer.hasClass('image-viewer-base-loading'),
                'Image should have started loading'
            );

            image.once('load', function() {
                instance.resume(function() {
                    Y.Assert.isFalse(
                        imageContainer.hasClass('image-viewer-base-loading'),
                        'Image should have finished loading'
                    );
                });
            });
            this.wait();
        },

        'should only render media content after load': function() {
            var media,
                mediaContainer;

            this._createImageViewer();

            media = this._imageViewer._getCurrentImage();
            Y.Assert.isNull(media, 'The media should not be rendered yet');

            this._imageViewer.getLink('0').simulate('click');

            media = this._imageViewer._getCurrentImage();
            mediaContainer = media.get('parentNode');

            Y.Assert.isNotNull(media, 'The media should have been rendered on load');
            Y.Assert.isFalse(
                mediaContainer.hasClass('image-viewer-base-loading'),
                'Media should not have loading indicator'
            );
        },

        'should not render same media more than once': function() {
            var media,
                newMedia;

            this._createImageViewer();

            this._imageViewer.getLink('0').simulate('click');
            media = this._imageViewer._getCurrentImage();

            this._imageViewer.next();
            this._imageViewer.prev();
            newMedia = this._imageViewer._getCurrentImage();

            Y.Assert.areSame(
                media,
                newMedia,
                'Media node should not have been rerendered'
            );
        }
    }));

    Y.Test.Runner.add(suite);
}, '', {
    requires: ['aui-image-viewer-media', 'node-event-simulate', 'test']
});


text:
<?php
namespace Acme\HelloBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Irdor\Bundle\WebsiteBundle\Entity\Skill;

class LoadSkillData implements FixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $items = array('dev' => array('name' => 'Développement',
                                                          'description' => '

Frameworks PHP : Symfony 2, Symfony

CMS: Drupal 6

JAVA : bases en développements d\'applications lourdes
                                                                                et applications Android

Versionning : SVN, Git

'),
                                'web' => array('name' => 'Compétences web',
                                                            'description' => '

Frontend : XHTML, CSS, Javascript, jQuery, Twitter bootstrap

Webservices : REST

'),
                                'conduite_projet' => array('name' => 'Conduite de projet',
                                                            'description' => '

Méthodes Agile : SCRUM, XP, Kanban

'),
                'langues' => array('name' => 'Langues',
                                                          'description' => '

Anglais : bon niveau (TOEIC  750/990, 2009)

Espagnol : niveau débutant

'),
            );

        foreach ($items as $infos) {
            $item = new Skill();
            $item->setDescription($infos['description']);
            $item->setName($infos['name']);
            $manager->persist($item);
        }

        $manager->flush();
    }
}


text:
This is my collection of [SmartThings](https://www.smartthings.com/) apps and device handlers that I use.

* [Camera LED Controller SmartApp](smartapps/chadly/camera-led-controller.src)
* [AsusWRT Wifi Presence SmartApp](smartapps/chadly/asuswrt-wifi-presence.src)
* [LED Strip Light Controller](smartapps/chadly/led-strip-controller.src)
* [LED Night Lights](smartapps/chadly/led-night-lights.src)
* [Pet Lighting](smartapps/chadly/pet-lighting.src)
* [Baby Temperature Monitor](smartapps/chadly/baby-temperature-monitor.src)

## Installation

### Option 1: Github integration

The best way to get updates is to enable GitHub integration and add this repository.

1. Open the IDE and navigate to `My SmartApps`
2. Select `Settings`
3. Select `Add new repository`
4. Enter the following details:
	* Owner: `chadly`
	* Name: `smartthings`
	* Branch: `master`

Now whenever you need to update to the latest version, you can choose `↓ Update from Repo`, select the app or device handler, and get your updates.

### Option 2: Manual Install

You can also install it manually for those of you who really enjoy copying & pasting everything.

1. Navigate to the app or device handler you want to install and copy the code.
2. Follow the instructions from the [ThingsThatAreSmart.wiki](http://thingsthataresmart.wiki/index.php?title=Using_Custom_Code#Using_a_Custom_SmartApp) on how to install a SmartApp.


text:
require File.dirname(__FILE__) + '/../test_helper'
require 'sessions_controller'

# Re-raise errors caught by the controller.
class SessionsController; def rescue_action(e) raise e end; end

class SessionsControllerTest < Test::Unit::TestCase
  fixtures :users

  def setup
    @controller = SessionsController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
  end

  def test_should_login_and_redirect
    post :create, :login => 'mwiki', :password => 'mwiki'
    assert session[:user_id]
    assert_response :redirect
  end

  def test_should_fail_login_and_not_redirect
    post :create, :login => 'mwiki', :password => 'bad password'
    assert_nil session[:user_id]
    assert_response :success
  end

  def test_should_logout
    login_as :mwiki
    get :destroy
    assert_nil session[:user_id]
    assert_response :redirect
  end

  def test_should_remember_me
    post :create, :login => 'mwiki', :password => 'mwiki', :remember_me => "1"
    assert_not_nil @response.cookies["auth_token"]
  end

  def test_should_not_remember_me
    post :create, :login => 'mwiki', :password => 'mwiki', :remember_me => "0"
    assert_nil @response.cookies["auth_token"]
  end

  def test_should_delete_token_on_logout
    login_as :mwiki
    get :destroy
    assert_equal @response.cookies["auth_token"], []
  end

  def test_should_login_with_cookie
    users(:mwiki).remember_me
    @request.cookies["auth_token"] = cookie_for(:mwiki)
    get :new
    assert @controller.send(:logged_in?)
  end

  def test_should_fail_expired_cookie_login
    users(:mwiki).remember_me
    users(:mwiki).update_attribute :remember_token_expires_at, 5.minutes.ago
    @request.cookies["auth_token"] = cookie_for(:mwiki)
    get :new
    assert !@controller.send(:logged_in?)
  end

  def test_should_fail_cookie_login
    users(:mwiki).remember_me
    @request.cookies["auth_token"] = auth_token('invalid_auth_token')
    get :new
    assert !@controller.send(:logged_in?)
  end

  protected
    def auth_token(token)
      CGI::Cookie.new('name' => 'auth_token', 'value' => token)
    end

    def cookie_for(user)
      auth_token users(user).remember_token
    end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Wang & Pei, Mycotaxon 79: 312 (2001)

#### Original name
Trichophaea donglingensis Zheng Wang

### Remarks
null


text:
import Bacon from "baconjs";

import Constants from "./Constants.json";
import Actions from '../Actions/Main';

const clicksStream = Bacon.fromEvent(document, 'click');

const toggleCompletedStream = clicksStream
    .filter(event => {
        const eventHandle = event.target.getAttribute('data-on-click');
        return eventHandle === Constants.TOGGLE_COMPLETED;
    })
    .map(event => {
        const todoId = event.target.getAttribute('data-todo-id');
        return Actions.toggleComplete(todoId);
    });

export default toggleCompletedStream;


text:
layout: post
title: 'Embedded learning log - Running a FreeRTOS recurring task'
comments: true
categories: [embedded-learning-log]
date: 2021-02-21 21:00:51 +0200
excerpt: 'Running a recurring task with ESP8266_RTOS_SDK/FreeRTOS and calculating the stack size needed by a C function'
---

{% include embedded-learning-log.html %}

> Browse the accompanying repository [at the commit in which I was done with this part](https://github.com/fnune/toastboard/tree/061238f3ccffd2f7f13eb0a4d0844fc31d5ad9c8).

Documentation on the ESP8266_RTOS_SDK does not feature any information about task creation. I guess this is because the underlying RTOS is FreeRTOS, so I'm going to try to find documentation for that.

[Here's the documentation](https://www.freertos.org/a00125.html).

Apparently I can create tasks with `xTaskCreate` or `xTaskCreateStatic`. If I want to use `xTaskCreateStatic`, I need to provide my own memory, so I need to pass more parameters, but I can allocate this memory at compile time. I'm going to go with the simpler `xTaskCreate`, which allocates from [the FreeRTOS heap](https://www.freertos.org/a00111.html).

The most important argument to `xTaskCreate` is the task function I want to run:

> Tasks are normally implemented as an infinite loop, and must never attempt to return or exit from their implementing function. Tasks can however delete themselves.

To create a task that executes periodically, I just need to make it an infinite loop that calls `vTaskDelay` in it or `vTaskDelayUntil`. I'm going for the simpler `vTaskDelay`.

Another interesting argument is `usStackDepth`. It's in words, and the docs say a word is 32 bits in an ESP8266EX. One choice would be to find out the minimum stack size required for a task in FreeRTOS. I found this interesting article: [GNU Static Stack Usage Analysis](https://mcuoneclipse.com/2015/08/21/gnu-static-stack-usage-analysis/) by [Erich Styger](https://mcuoneclipse.com/author/mcuoneclipse/). I can pass `-fstack-usage` to `gcc` and get a nice `.su` file that gives me the stack usage of each function in bytes. I can append to `CFLAGS` for specific components, so I did so in `esp8266_sdk/memfault/component.mk`, and then found this file `memfault/memfault_platform_http_client.su`:

```
memfault_platform_http_client.c:178:5:memfault_platform_http_client_post_data	192	static
```

That's it! 192 bytes divided by my word size of 4 is exactly 48. I'll use 48 as a stack size for my task and eventually test to see if I can get by with less (I doubt it).

After creating the task, I get an crash loop due to a stack overflow on my new `task_upload_memfault_data`. Is my stack size not big enough?

## Finding out the stack size needed by a function

I found this interesting article: [GNU Static Stack Usage Analysis](https://mcuoneclipse.com/2015/08/21/gnu-static-stack-usage-analysis/) by [Erich Styger](https://mcuoneclipse.com/author/mcuoneclipse/). I can pass `-fstack-usage` to `gcc` and get a nice `.su` file that gives me the stack usage of each function in bytes.

I found out I can pass append to `CFLAGS` for specific components, so I did so in `esp8266_sdk/memfault/component.mk`, and then found this file `memfault/memfault_platform_http_client.su`:

```
memfault_platform_http_client.c:178:5:memfault_platform_http_client_post_data	192	static
```

That's it! 192 bytes divided by my word size of 4 is exactly 48. I'll use 48 as a stack size for my task and eventually test to see if I can get by with less (I doubt it).

### The stack size I calculated wasn't enough

I started by trying to allocate a stack of 48 words for my `task_upload_memfault_data` function, but that crashed my device due to bad allocations. I bluntly tried to increase it gradually until it worked, and it did! At 4096 words. I was off by a lot.

Could this be due to the fact that I measured stack usage for `memfault_platform_http_client_post_data` and not for my task's function `task_upload_memfault_data`? Let's build with `-fstack-usage` again, this time scouting for my task function instead. The number reported for `memfault_platform_http_client_post_data` was 192 bytes.

The output contains this:

```
main.c:148:6:task_upload_memfault_data	16	static
```

Eew! 16 is a lot less than 192. It seems like this isn't going all the way down the call stack to calculate stack usage. Maybe I'm missing some other flag?

## Runtime analysis of the target stack size

I'm going to try to let the code run and analyze how much memory the task takes after the fact. I probably need to make the task run through all of its different branches and take the maximum.

I remember that allocation of tasks created via `xTaskCreate` is handled by FreeRTOS, and there's another way to create tasks that lets me control allocation: `xTaskCreateStatic`.

My plan is to:

1. Refactor my task to use `xTaskCreateStatic`.
2. Flash and run the code.
3. Figure out how to analyze the memory layout after the fact.
4. Read how much of the stack I allocated was actually used by the task.

To be able to access `xTaskCreateStatic` I had to change `configSUPPORT_STATIC_ALLOCATION` to `1` in `components/freertos/include/freertos/FreeRTOS.h`. Surprisingly, this setting wasn't available under `make menuconfig` -> Component configuration -> FreeRTOS.

I'm giving up on this approach and returning to static analysis because compiling with `configSUPPORT_STATIC_ALLOCATION` requires me to implement my own allocators/deallocators for FreeRTOS's idle task, and I'm... not up for the task.

## Static analysis of the target stack size

The reason why my 192 number was wrong is because `gcc` outputs `.su` files for each `.o` file it produces; it doesn't look into other output objects to determine stack usage in a recursive fashion.

I found this Perl script by Daniel Beer [`avstack.pl`](https://dlbeer.co.nz/oss/avstack.html) which reportedly builds this tree or call graph for you and then sums the results:

> The script reads all .su files, and disassembles all .o files, including relocation data. The disassemblies are parsed and used to construct a call graph. Multiple functions in different translation units with the same name don't cause problems, provided there are no global namespace collisions. Information will appear on any unresolvable or ambiguous references.

I've added the script and results to the repository in [`src/avstack.txt`](src/avstack.txt). Functions prefixed with `>` are supposed to have a summary of function calls in lines below them, but my run seems to have produced a flat stack where no function calls other functions in its body. It's weird, and I got a 196 for `memfault_platform_http_client_post_data`, which looks like it's my previous 192 plus 4. This 4 is passed as an argument to `avstack.pl` called `call_cost`.

So! I'm giving up on this method as well. My last attempt: using FreeRTOS's `uxTaskGetStackHighWaterMark`.

## Measuring the target stack size at runtime using `uxTaskGetStackHighWaterMark`

I've instrumented my task like this:

```c
void task_upload_memfault_data( void * pvParameters )
{
    // [...]
    uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL);
    ESP_LOGD(TAG, "Water mark at task entry: %lu", uxHighWaterMark);

    while (true)
    {
        // [...]
        uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL);
        ESP_LOGD(TAG, "Water mark at task exit: %lu", uxHighWaterMark);
    }
}
```

The output looks like this, with irrelevant sections edited out:

```
D (807) TOASTBOARD: Water mark at task entry: 3976

D (10832) TOASTBOARD: Water mark at task exit: 3140

D (29036) TOASTBOARD: Water mark at task exit: 580
D (39037) TOASTBOARD: Water mark at task exit: 580
D (49039) TOASTBOARD: Water mark at task exit: 580
D (59041) TOASTBOARD: Water mark at task exit: 580
D (69042) TOASTBOARD: Water mark at task exit: 580
D (79045) TOASTBOARD: Water mark at task exit: 580
```

So it's 3976 on entry, on its first exit it's 3140, and then it's in the infinite loop (it has a 10 second delay after each run) and stabilizes at 580.

The initial drop from 3976 to 3140 is explained by the documentation:

> Calling the function will have used some stack space, we would therefore now expect uxTaskGetStackHighWaterMark() to return a value lower than when it was called on entering the task.

In my case, "the function(s)" are `vTaskDelay` and `memfault_esp_port_http_client_post_data`.

The second drop from 3140 to the stable 580 is explained by the fact that `memfault_esp_port_http_client_post_data` returned early because there was no more data to post. Cool!

Two questions remain:

- Is the high water mark going to be higher than 3976 if there's more than one chunk to send to Memfault? I've seen it post several at a time. I guess the stack size is going to be the same if the code runs inside a loop.
- I need to try and allocate a more optimized stack size to see if that affects execution. My new size in words is 3976.

With 3976 it works just fine, but on a new run the high water mark is 3864. Why couldn't it be more than my allocated 3976? Do people pad these values? I'm sticking with my original 4096 for good measure.

### Finding out the size of a word manually in C

I remember in Rust this would be the size of `usize`. I guess in C I can go `sizeof(some_type)` to get this.

After some Googling, I found `size_t`, which varies depending on the address size of the processor, and is the type returned by `sizeof`. So let's try `sizeof(size_t)`.

```
ESP_LOGI(TAG, "Size of a word is %u bytes!", sizeof(size_t));
```

And then in `make monitor`:

```
I (532) TOASTBOARD: Size of a word is 4 bytes!
```

Four bytes are 32 bits. Thanks Toastboard!

Next I'll be [integrating the Memfault Firmware SDK]({% post_url 2021-02-21-embedded-learning-log-4-integrating-the-memfault-firmware-sdk %}).


text:
FBGroupCommentCounter
=====================

Provides a list of the most popular/frequently appearing comments and/or posts made in a Facebook group. Useful for pointing out patterns of repetition in a group.

Usage
=====================
`./FBCommentStats.py --token=<access token> --group=<group ID> [--count-posts] [--verbose]`

Dependencies
=====================
The [Facebook Python SDK](https://github.com/pythonforfacebook/facebook-sdk) is needed to run the script and can be installed by using `pip install facebook-sdk`.

[Colorama](https://pypi.python.org/pypi/colorama) is optional and untested but should theoretically colorify the info/warning/etc. prefixes.