text:
import cookie from 'js-cookie'

var ven_sid=cookie.get('ven_sid');
if(!ven_sid) {
  /*based on https://github.com/makeable/uuid-v4.js*/
  var UUID=function(){for(var dec2hex=[],i=0;15>=i;i++)dec2hex[i]=i.toString(16);return function(){for(var uuid="",i=1;36>=i;i++)uuid+=9===i||14===i||19===i||24===i?"-":15===i?4:20===i?dec2hex[4*Math.random()|8]:dec2hex[15*Math.random()|0];return uuid}}();
  ven_sid=UUID();
}
cookie.set('ven_sid',ven_sid,180,'/',false,'.devel');

var _apiHost,_user,_project;
var _analyticsOneTimeEventFired={};
try {
  var location = window.location;
  var domain = location.origin || (location.protocol + '//' + location.hostname);
  var _actualRequest={
    referrer: document.referrer||undefined,
    url: location.href,
    protocol: location.protocol.substr(0,location.protocol.length-1),
    hostname: location.hostname,
    domain: domain,
    pathname: location.pathname || location.href.substr(domain.length).replace(/[\?\#].*$/,''),
    userAgent: typeof navigator!=='undefined' ? navigator.userAget : undefined,
    hash: location.hash.replace(/^\#/,''),
    query: (function parseParams() {
        if(location.search) {
          try {
            return location.search.replace(/^\?/,'').split('&').reduce(function (params, param) {
                var paramSplit = param.split('=').map(function (value) {
                    return decodeURIComponent(value.replace('+', ' '));
                });
                params[paramSplit[0]] = paramSplit[1];
                return params;
            }, {});
          } catch(e) {
            return location.search;
          }
        }
    })()
  };

  var origin = (function(request,cookie) {
    try {
      var o = JSON.parse(cookie.get('ctrse_origin')||null) || {createdAt: new Date()};
    } catch(e) {
      o = {createdAt: new Date()};
    }
    var fromCatarse=request.referrer && /^https?:\/\/([^\\/]+\.)?catarse\.me/.test(request.referrer);
    if(fromCatarse) {
      //Só pega o ultimo ref. Não atualiza utms...
      o.ref = (request.query&&request.query.ref) || o.ref; //preferencia para a query.
    } else if(/*!fromCatarse && */ request.referrer || (!o._time || new Date().getTime()-o._time>10*60*1000/*10min*/)) {
      var m=request.referrer && request.referrer.match(/https?:\/\/([^\/\?#]+)/);
      var refDomain=(m && m[1]) || undefined;
      var query=request.query;
      //se, e somente se, tem algum utm na query...
      if(query && ['utm_campaign','utm_source','utm_medium','utm_content','utm_term'].some(function(p){
        return !!query[p];
      })) {//então, substitui todos, mesmo os q nao tem, pois são um conjunto de informações...
        o.domain  = refDomain;
        o.campaign=query.utm_campaign;
        o.source=  query.utm_source;
        o.medium=  query.utm_medium;
        o.content= query.utm_content;
        o.term=    query.utm_term;
      } else if (refDomain && !['domain','utm_campaign','utm_source','utm_medium','utm_content','utm_term'].some(function(p){
        return !!o[p];
      })) {//se tem refDomain e não tem no origin algum utm ou domain anterior...
        o.domain  = refDomain;
      }

      if(!o.campaign && query && query.ref) {
        //nesse caso, como veio de outro dominio, sem utm params, mas com ref, assumimos q esse ref é um campaign.
        o.campaign = query.ref;
      }
    }
    //fazemos o _time aqui por causa da verificação acima !o._time, indicando q foi criado agora.
    o._time=new Date().getTime();
    cookie.set('ctrse_origin',JSON.stringify(o),180,'/',false,'.catarse.me');
    return o;
  })(_actualRequest,monster);
} catch(e) {
  console.error('[CatarseAnalytics] error',e);
}
//Metodos semelhantes ao modulo "h"
function _getApiHost() {
  if(window.CatarseAnalyticsURL)
    return window.CatarseAnalyticsURL;
  if(_apiHost)
    return _apiHost;

  var el=document.getElementById('api-host');
  _apiHost = (el && el.getAttribute('content'));
  if(_apiHost)
    _apiHost=_apiHost+'/rpc/track';
  return _apiHost;
}
function _getUser() {
  if(_user)
    return _user;

  var body = document.getElementsByTagName('body'),
      data = body && body[0] && body[0].getAttribute('data-user');
  if(data) {
    try {
      return _user=JSON.parse(data);
    } catch(e) {
      console.error('[CatarseAnalytics._getUser] error parsing data '+JSON.stringify(data), e);
    }
  }
}
function _getProject() {
  if(_project)
    return _project;
  var el = document.getElementById('project-show-root')||document.getElementById('project-header'),//pode não existir
      data = el && (el.getAttribute('data-parameters')||el.getAttribute('data-stats'));
  if(data) {
    try {
      return  _project=JSON.parse(data);
    } catch(e) {
      console.error('[CatarseAnalytics._getProject] error parsing data '+JSON.stringify(data), e);
    }
  }//else return undefined
}

function _event(eventObj, fn, ignoreGA) {
  if (eventObj) {
    try {
      var project = eventObj.project||_getProject(),
          user = eventObj.user||_getUser();
      var ga = window.ga;//o ga tem q ser verificado aqui pq pode não existir na criaçaõ do DOM
      var gaTracker = (typeof ga==='function' && ga.getAll && ga.getAll() && ga.getAll()[0]) || null;
      ignoreGA = ignoreGA || typeof ga!=='function';

      var data = eventObj.extraData&&typeof eventObj.extraData==='object' ? JSON.parse(JSON.stringify(eventObj.extraData)) : {};
      data.ctrse_sid=ctrse_sid;
      data.origin=origin;
      data.category=eventObj.cat;
      data.action=eventObj.act;
      data.label=eventObj.lbl;
      data.value=eventObj.val;
      data.request=_actualRequest;
      if(user&&user.user_id) {
        data.user={
          id: user.user_id,
          contributions: user.contributions,
          published_projects: user.published_projects
        };
      }
      if(project&&(project.id||project.project_id)) {
        data.project={
          id: project.id||project.project_id,
          user_id: project.user_id||project.project_user_id,
          category_id: project.category_id,
          state: project.address && project.address.state_acronym,
          city: project.address && project.address.city
        };
      }
      if(gaTracker) {
        data.ga={clientId: gaTracker.get('clientId')};
      }

      try {
        var apiUrl=_getApiHost();
        if(apiUrl) {
          var sendData = {
            event: data
          };

          ajax({
              url: apiUrl,
              // The key needs to match your method's input parameter (case-sensitive).
              body: JSON.stringify(sendData),
              headers: {
                'content-type': "application/json; charset=utf-8"
              }
          }, function(status, responseText, req){
            if(status!==200)
              console.error(status,responseText,req);
          });
        }
      } catch(e) {
        console.error('[CatarseAnalytics.event] error:', e);
      }

      if(!ignoreGA) {
        //https://developers.google.com/analytics/devguides/collection/analyticsjs/sending-hits#the_send_method
        ga('send', 'event', eventObj.cat, eventObj.act, eventObj.lbl, eventObj.val, {
          nonInteraction: eventObj.nonInteraction!==false,//default é true,e só será false se, e somente se, esse parametro for definido como false
          transport: 'beacon'
        });
      }
    } catch(e) {
      console.error('[CatarseAnalytics.event] error:',e);
    }
  }
  fn && fn();
}

/*function _lastOrigin() {
  var origin=localStorage
  if(documnet.referrer && /https?:\/\/[^\/]*catarse\.me/.test(document.referrer)) {

  }
}*/
function _pageView() {
  _event({cat:'navigation',act:'pageview',lbl:location.pathname}, null, true)
}
_pageView();

function _checkout(transactionId, prodName, sku, category, price, fee) {
  try {
    if(typeof ga==='function') {
      ga('ecommerce:addTransaction', {
        'id': transactionId,                     // Transaction ID. Required.
        //'affiliation': 'Acme Clothing',   // Affiliation or store name.
        'revenue': price,               // Grand Total.
        //'shipping': ,                  // Shipping.
        'tax': fee,                     // Tax.  Nossa porcentagem
        'current': 'BRL'
      });
      ga('ecommerce:addItem', {
        'id': transactionId,                     // Transaction ID. Required.
        'name': prodName,    // Product name. Required.
        'sku': sku,                 // SKU/code.
        'category': category,         // Category or variation.
        'price': price,                 // Unit price.
        'quantity': '1'                   // Quantity.
      });
      ga('ecommerce:send');
    }
  } catch(e) {
    console.error('[CatarseAnalytics.checkout]',e);
  }
}

export default {
  origin: origin,
  event: _event,
  oneTimeEvent: function(eventObj, fn) {
      if (!eventObj) {
          return fn;
      }
      try {
        if (!eventObj.cat && !eventObj.act) {
          throw new Error('Should inform cat or act');
        }
        var eventKey = eventObj.cat && eventObj.act ? eventObj.cat+'_'+eventObj.act : (eventObj.cat || eventObj.act);
        if (!_analyticsOneTimeEventFired[eventKey]) {
            //console.log('oneTimeEvent',eventKey);
            _analyticsOneTimeEventFired[eventKey] = true;
            _event(eventObj, fn);
        }
      } catch(e) {
        console.error('[CatarseAnalytics.oneTimeEvent] error:',e);
      }
  },
  checkout: _checkout
};


text:
My shopping lists

No shopping lists found

If you use a new device, please search for your lists

        <md-input-container style="width: 100%">
            <input mdInput placeholder="name"  name="name" [(ngModel)]="name">
        </md-input-container>
        <md-input-container style="width: 100%">
            <input mdInput placeholder="email"  name="email" [(ngModel)]="email">
        </md-input-container>
        <button md-button style="background:gray;margin: auto;display: flex;align-items: center;justify-content: center;" (tap)="searchSLists()">search</button>

0">

 Recently used shopping lists

{{a.title}}

{{a.description}}

        <button md-button style="background:gray;margin: auto;display: flex;align-items: center;justify-content: center;" (tap)="createNewList()">Create new shopping list</button>

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Running tests
 *
 * Run Unit Tests using PHPUnit. Note that the PHPUnit framework can be acquired through PEAR or Composer.
 */

namespace Testing\JetBrains;

// 1. Create a new Run Configuration based on PHPUnit. Name it "Run tests" and specify the directory to look for tests:
//      \08 - Testing\
//    Note that a specific class or method can also be run.
//    A PHPUnit XML configuration file can also be specified for this specific run configuration.
// 2. Unless you have PHPUnit installed through PEAR, tests can not be run yet as the PHPUnit framework is not available.
//
//    From Project Settings | PHP | PHPUnit, specify that PHPUnit should be loaded from phpunit.phar.
//    The IDE can automatically download this file.
//
//    If you are using Composer, PHPUnit can also be loaded from a custom file. Specify the path to Composer's
//    Autoload.php if that is the case.
// 3. Almost there! The Queue class ca not be loaded. To solve this, do one of the following:
//
//      Add the line require_once 'Code/Queue.php';
//
//      -or-
//
//      From the Project Settings | PHP | PHPUnit, set \08 - Testing\Code\Bootstrap.php as the default bootstrap file.
//      A bootstrap file can be used to run custom PHP code in the unit test runner. Bootstrap.php includes all required files
//      so that the tests can be run.
// 4. Execute the Run Configuration.
// 5. The Test tool window below shows test results. Using the context menu,
//    additional statistics such as the number of assertions can be viewed.


text:
this piece of software provides a skeleton to create micro services which has
one or multiple single RestFul(Like) interface which represents a database
tables without foreign key handling. The service only provides CRUD without
search capability.

### How does it work?
Create a database, configure db & entities, generate entities & start server.

### When to use?
Wanna build a service in under 15 minutes for one database table.

## Requirements
* PHP (v5.6.X or higher)
* MySQL (v5.5.X or higher) to run the included example
* phpcpd, phpcs, phpdoc, phpunit & ant (only if you want to run the full build)

## Generate Doctrine based entities.
This will create the entity classes required to access the database.
```
./setup-svc-entties.sh
```

## Run the service on localhost:8080
This will use the PHP built-in server to launch a server.
```
./start-server.sh
```

## Special Thanks
Jan and Andreas from http://aero-code.com/. See also their repositories
https://github.com/PiMastah and https://github.com/amandiel.

## Uses
https://github.com/slimphp/Slim

https://github.com/Seldaek/monolog

https://github.com/hassankhan/config

https://github.com/fuelphp/validation

https://github.com/doctrine/doctrine2

## License
https://github.com/mlatzko/SlimMicroService/blob/master/LICENSE


text:
using System;

namespace API
{
  /// <summary>
  /// Marks a class as an extension to an API class
  /// </summary>
  public class ExtensionAttribute : Attribute
  {
    public string Name;
    public string Register;
    public string Mod;

    public ExtensionAttribute(string mod, string name, string register)
    {
      Mod = mod;
      Name = name;
      Register = register;
    }
  }
}


text:
using namespace std;

class DFABuilder
{
	private:
		DFA * dfa;

	public:
		DFABuilder();
		~DFABuilder();
		DFABuilder * buildName(string name);
		DFABuilder * buildDescription(string description);
		DFABuilder * buildAlphabet(string alphabet);
		DFABuilder * buildStates(vector<State *> states);
		DFABuilder * buildState(State * state);
		DFA * build();
		DFA * getBuildingInstance();
		DFABuilder * reset(bool releaseInstance = false);
};

#endif


text: Examine Chicago Water Utilities


text:
<!doctype html>

	<meta charset="UTF-8"/>

Indices Challenge Sécurité 3

Besoin d'un petit coup de pouce pour démarrer ? En panne d'inspiration pour trouver la prochaine étape ? Voici quelques indices pour vous aider à avancer !

 (Cliquez sur un indice ou sur sa réponse pour l'afficher)

Indice 1

Quelles sont les machines présentes dans ce challenge ? Jetez un oeil à la capture wireshark et à la configuration réseau de votre machine pour relever les informations pertinentes.

Réponse :

Machine cliente (IP/MAC): 192.168.2.2 / 08:00:27:8c:8e:4d
 Machine Serveur (IP/MAC) : 192.168.2.1 / 08:00:27:8f:a6:b1
 Attaquant (IP/MAC) : 192.168.2.7 / 08:00:27:59:15:bf

Indice 2

Bon et si nous déroutions le trafic client-serveur pour pouvoir le visualiser ? Familiarisez-vous avec l'ARP Poisoning et jouez avec le script d'attaque.

Réponse :

Lancez le script python avec les bonnes entrées :
 target -> IP et MAC machine cliente
 ip to spoof -> IP du serveur (IP à usurper vis à vis du client)
 router -> Machine Serveur

Indice 3

Le Man In The Middle est en place ? Bien  joué ! Vérifiez que le trafic client-serveur peut être observé avec Wireshark...il y a comme un problème non ? Comment le résoudre ? Lisez la doc sur les iptables...

Réponse :

Le trafic client-serveur est chiffré (HTTPS). Le forum est accessible en HTTPS ET HTTP (communications non chiffrées), il faut donc forcer le client à passer en HTTP avec une règle iptables bloquant le trafic routé sur le port 443.

Indice 4

Le trafic est en clair maintenant ! Interceptez le mot de passe dans les échanges HTTP et connectez-vous avec le compte du suspect sur le forum !

Réponse :

Affichez les messages privés du compte volé.

Indice 5

Mais où est cette fameuse planque ? Curieux ces chiffres en fin de message...

Réponse :

Il s'agit de coordonnées GPS à entrer sur Google Maps par exemple.


text:
@interface DKLaunchApplicationLocalActionConfigViewController ()

@end

@implementation DKLaunchApplicationLocalActionConfigViewController

-(id)init {
	return [self initWithNibName:NSStringFromClass([self class]) bundle:nil];
}

+(NSSet *)keyPathsForValuesAffectingApplicationName {
	return [NSSet setWithObject:@"representedObject.bundleIdentifier"];
}

-(NSString *)applicationName {
	DKLaunchApplicationLocalAction *action = self.representedObject;
	NSString *path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:action.bundleIdentifier];
	if (path.length == 0) return action.bundleIdentifier;
	NSBundle *appBundle = [[NSBundle alloc] initWithPath:path];
	NSString *bundleName = [[appBundle infoDictionary] valueForKey:(__bridge NSString *)kCFBundleNameKey];
	if (bundleName.length > 0)
		return bundleName;
	else
		return [[path lastPathComponent] stringByDeletingPathExtension];
}

+(NSSet *)keyPathsForValuesAffectingApplicationIcon {
	return [NSSet setWithObject:@"representedObject.bundleIdentifier"];
}

-(NSImage *)applicationIcon {

	DKLaunchApplicationLocalAction *action = self.representedObject;
	NSString *path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:action.bundleIdentifier];
	if (path.length == 0) return [NSImage imageNamed:@"PlainAppIcon"];
	return [[NSWorkspace sharedWorkspace] iconForFile:path];
}

-(IBAction)chooseApplication:(id)sender {
	NSOpenPanel *openPanel = [NSOpenPanel openPanel];
	openPanel.delegate = self;
    openPanel.message = NSLocalizedString(@"please choose the application title", @"");
    openPanel.canChooseFiles = YES;
    openPanel.canChooseDirectories = YES;

	[openPanel beginSheetModalForWindow:self.view.window
					  completionHandler:^(NSInteger result) {

						  if (result != NSFileHandlingPanelOKButton) return;

						  NSBundle *appBundle = [NSBundle bundleWithURL:openPanel.URL];
						  if (appBundle.bundleIdentifier.length > 0) {
							  DKLaunchApplicationLocalAction *action = self.representedObject;
							  action.bundleIdentifier = appBundle.bundleIdentifier;
							  [[DKCECKeyMappingController sharedController] saveMappings];
						  } else {
                              NSAlert *alert = [NSAlert new];
                              alert.messageText = NSLocalizedString(@"invalid application chosen title", @"");
                              alert.informativeText = NSLocalizedString(@"invalid application chosen description", @"");
                              [alert addButtonWithTitle:NSLocalizedString(@"ok button title", @"")];
                              [alert runModal];
						  }
					  }];
}

-(BOOL)panel:(id)sender shouldEnableURL:(NSURL *)url {

    NSString *path = [url path];
    if ([[path pathExtension] compare:@"app" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
        return YES;
    } else {
        BOOL isDir = NO;
        [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir];
        return isDir;
    }
    return NO;
}

-(BOOL)panel:(id)sender validateURL:(NSURL *)url error:(NSError **)outError {

	NSString *path = [url path];
    if ([[path pathExtension] compare:@"app" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
        return YES;
    } else {
		if (outError != NULL)
			*outError = [NSError errorWithDomain:@"error"
											code:0
										userInfo:[NSDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"invalid application chosen title", @""), NSLocalizedDescriptionKey,
												  NSLocalizedString(@"invalid application chosen description", @""), NSLocalizedRecoverySuggestionErrorKey,
												  nil]];

		return NO;
	}
}

@end


text:
package org.apache.skywalking.oap.server.core.analysis.metrics;

import org.apache.skywalking.oap.server.core.remote.grpc.proto.RemoteData;
import org.junit.Assert;
import org.junit.Test;

public class MinLongMetricsTest {

    @Test
    public void testEntranceCombine() {
        MinLongMetricsImpl impl = new MinLongMetricsImpl();
        impl.combine(10);
        impl.combine(5);
        impl.combine(20);
        impl.calculate();
        Assert.assertEquals(5, impl.getValue());

        MinLongMetricsImpl impl2 = new MinLongMetricsImpl();
        impl2.combine(10);
        impl2.combine(0);
        impl2.combine(10000);
        impl2.calculate();

        Assert.assertEquals(0, impl2.getValue());
    }

    @Test
    public void testSelfCombine() {
        MinLongMetricsImpl impl = new MinLongMetricsImpl();
        impl.combine(10);
        impl.combine(5);

        MinLongMetricsImpl impl2 = new MinLongMetricsImpl();
        impl2.combine(2);
        impl2.combine(6);

        impl.combine(impl2);
        Assert.assertEquals(2, impl.getValue());
    }

    public class MinLongMetricsImpl extends MinLongMetrics {

        @Override
        protected String id0() {
            return null;
        }

        @Override
        public Metrics toHour() {
            return null;
        }

        @Override
        public Metrics toDay() {
            return null;
        }

        @Override
        public int remoteHashCode() {
            return 0;
        }

        @Override
        public void deserialize(RemoteData remoteData) {

        }

        @Override
        public RemoteData.Builder serialize() {
            return null;
        }
    }
}


text:
package com.ys.yoosir.zzshow.mvp.view;

import com.ys.yoosir.zzshow.mvp.base.BaseView;

/**
 * @version 1.0
 * @author  yoosir
 * Created by Administrator on 2016/11/30.
 */

public interface PhotoDetailView extends BaseView{

}


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

describe "/teams/new.html.haml" do
  include TeamsHelper

  before do
    @teams = mock_model(Teams)
    @teams.stub!(:new_record?).and_return(true)
    @teams.stub!(:name).and_return("MyString")
    assigns[:teams] = @teams
  end

  it "should render new form" do
    render "/teams/new.html.haml"

    response.should have_tag("form[action=?][method=post]", teams_path) do
      with_tag("input#teams_name[name=?]", "teams[name]")
    end
  end
end


text:
import cv2, platform

import numpy as np

class FaceDetection:
    @staticmethod
    def find(image, haarcascade, scaleFactor = 1.2, minNeighbors = 8):
        img = image.decode('base64', 'strict')
        img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), -1)
        faceCascade = cv2.CascadeClassifier(haarcascade)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = cv2.equalizeHist(gray)
        faces = faceCascade.detectMultiScale(gray, scaleFactor, minNeighbors)
        return faces

class MoveDetection:
    @staticmethod
    def find(image1, image2):
        rect = (0, 0, 0, 0)
        firstFrame = image1.decode('base64', 'strict')
        firstFrame = cv2.imdecode(np.fromstring(firstFrame, dtype=np.uint8), -1)
        img = image2.decode('base64', 'strict')
        img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), -1)
        if firstFrame is not None and img is not None:
            firstGray = cv2.cvtColor(firstFrame, cv2.COLOR_BGR2GRAY)
            firstGray = cv2.equalizeHist(firstGray)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            gray = cv2.equalizeHist(gray)
            frameDelta = cv2.absdiff(firstGray, gray)
            thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
            thresh = cv2.dilate(thresh, None, iterations=2)
            if platform.system() == 'Windows':
                _, cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            else:
                cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            contourMax = None
            areaMax = None
            for c in cnts:
                contour = cv2.contourArea(c)
                if contour < 500:
                    continue
                if contourMax is None or contour > contourMax:
                    contourMax = contour
                    areaMax = c
            if not areaMax is None:
                (x, y, w, h) = cv2.boundingRect(areaMax)
                rect = (x, y, w, h)
        return rect


text:
package matcher

import (
	"fmt"
	"os"
	"testing"
	"time"

	. "github.com/smartystreets/goconvey/convey"
)

func TestMain(m *testing.M) {
	RegisterDefaults()
	code := m.Run()
	os.Exit(code)
}

func TestErrorHandling(t *testing.T) {
	Convey("Given a non-struct", t, func() {
		v := "invalid"

		Convey("When a match is attempted, an error is returned", func() {
			clauses := []*Clause{&Clause{Field: "foo", Operator: "eq", Value: "bar"}}
			_, err := Matches(v, clauses)

			So(err, ShouldBeError)
		})
	})

	Convey("Given a struct", t, func() {
		v := struct {
			Name     string `matcher:"name"`
			Age      int    `matcher:"age"`
			Embedded struct {
				Foo int
				Bar float64
			} `matcher:"embedded"`
		}{"Alice", 32, struct {
			Foo int
			Bar float64
		}{32, 3.151459}}

		Convey("When a non-existent field is matched against, an error is returned", func() {
			clauses := []*Clause{&Clause{Field: "invalid", Operator: "eq", Value: "foo"}}
			_, err := Matches(v, clauses)

			So(err, ShouldBeError)
		})

		Convey("When attempting to match with an invalid operator, an error is returned", func() {
			clauses := []*Clause{&Clause{Field: "name", Operator: "foo", Value: "foo"}}
			_, err := Matches(v, clauses)

			So(err, ShouldBeError)
		})

		Convey("When a clause's value type doesn't match the struct, an error is returned", func() {
			clauses := []*Clause{&Clause{Field: "name", Operator: "eq", Value: 3.14159}}
			_, err := Matches(v, clauses)

			So(err, ShouldBeError)
		})

		Convey("When a comparison is attempted against an unknown type, an error is returned", func() {
			clauses := []*Clause{&Clause{Field: "embedded", Operator: "eq", Value: 3.14159}}
			_, err := Matches(v, clauses)

			So(err, ShouldBeError)
		})
	})
}

func TestMatching(t *testing.T) {
	Convey("Given a struct", t, func() {
		v := struct {
			Name    string `matcher:"name"`
			Age     int    `matcher:"age"`
			Unused  bool
			Skipped bool `matcher:"-"`
		}{"Alice", 32, false, false}

		Convey("When no clauses are provided, the struct should match", func() {
			clauses := []*Clause{}
			matched, err := Matches(v, clauses)

			So(err, ShouldBeNil)
			So(matched, ShouldBeTrue)
		})

		Convey("When all clauses match, the struct should match", func() {
			clauses := []*Clause{&Clause{Field: "name", Operator: "eq", Value: "Alice"},
				&Clause{Field: "age", Operator: "eq", Value: 32}}
			matched, err := Matches(v, clauses)

			So(err, ShouldBeNil)
			So(matched, ShouldBeTrue)
		})

		Convey("If one clause doesn't match, the struct shouldn't match", func() {
			clauses := []*Clause{&Clause{Field: "name", Operator: "eq", Value: "Alice"},
				&Clause{Field: "age", Operator: "eq", Value: 40}}
			matched, err := Matches(v, clauses)

			So(err, ShouldBeNil)
			So(matched, ShouldBeFalse)
		})
	})
}

func TestTypeMatching(t *testing.T) {
	type Person struct {
		Name     string    `matcher:"name"`
		Age      int       `matcher:"age"`
		Height   float64   `matcher:"height"`
		Birthday time.Time `matcher:"birthday"`
	}

	type TypeWrapper struct {
		Name  string
		Field string
		Base  interface{}
		Data  map[string]interface{}
	}

	baseTime, _ := time.Parse(time.RFC3339, "2000-01-01T00:00:00Z")

	p := Person{
		Name:     "foo",
		Age:      1,
		Height:   1.5,
		Birthday: baseTime,
	}

	operators := []string{"gt", "lt", "eq", "ne"}

	types := []*TypeWrapper{
		{
			Name:  "string",
			Field: "name",
			Base:  "foo",
			Data: map[string]interface{}{
				"gt": "e",
				"lt": "g",
				"eq": "foo",
				"ne": "bar",
			},
		},
		{
			Name:  "int",
			Field: "age",
			Base:  1,
			Data: map[string]interface{}{
				"gt": 0,
				"lt": 2,
				"eq": 1,
				"ne": 3,
			},
		},
		{
			Name:  "float",
			Field: "height",
			Base:  1.5,
			Data: map[string]interface{}{
				"gt": 1.0,
				"lt": 2.0,
				"eq": 1.5,
				"ne": 3.0,
			},
		},
		{
			Name:  "time",
			Field: "birthday",
			Base:  baseTime,
			Data: map[string]interface{}{
				"gt": baseTime.Add(time.Duration(-1) * time.Second),
				"lt": baseTime.Add(time.Duration(1) * time.Second),
				"eq": baseTime,
				"ne": baseTime.Add(time.Duration(1) * time.Hour),
			},
		},
	}

	Convey("Given a struct", t, func() {
		for _, typeTest := range types {
			for _, op := range operators {
				msg := fmt.Sprintf("When compared, %s %v is %s %v",
					typeTest.Name, typeTest.Base, op, typeTest.Data[op])
				Convey(msg, func() {
					clauses := []*Clause{&Clause{Field: typeTest.Field, Operator: op, Value: typeTest.Data[op]}}
					matched, err := Matches(p, clauses)

					So(err, ShouldBeNil)
					So(matched, ShouldBeTrue)
				})
			}
		}
	})
}


text:
/* $Xorg: PropAlloc.c,v 1.5 2001/02/09 02:03:35 xorgcvs Exp $ */
/*

Copyright 1989, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.

*/
/* $XFree86: xc/lib/X11/PropAlloc.c,v 1.3 2001/01/17 19:41:41 dawes Exp $ */

#include "Xlibint.h"
#include "Xutil.h"
#include <stdio.h>

/*
 * Routines for allocating space for structures that are expected to get
 * longer at some point.
 */

XSizeHints *XAllocSizeHints ()
{
    return ((XSizeHints *) Xcalloc (1, (unsigned) sizeof (XSizeHints)));
}

XStandardColormap *XAllocStandardColormap ()
{
    return ((XStandardColormap *)
	    Xcalloc (1, (unsigned) sizeof (XStandardColormap)));
}

XWMHints *XAllocWMHints ()
{
    return ((XWMHints *) Xcalloc (1, (unsigned) sizeof (XWMHints)));
}

XClassHint *XAllocClassHint ()
{
    register XClassHint *h;

    if ((h = (XClassHint *) Xcalloc (1, (unsigned) sizeof (XClassHint))))
      h->res_name = h->res_class = NULL;

    return h;
}

XIconSize *XAllocIconSize ()
{
    return ((XIconSize *) Xcalloc (1, (unsigned) sizeof (XIconSize)));
}


text:
* * *

title: "Artist: Nested Loops" view: page_curriculum theme: none

* * *

<%= partial('curriculum_header', :unittitle=>'Course 2', :lesson=>19, :title=> 'Artist: Nested Loops', :unplugged=>false, :time=>30) %>

[content]

[together]

## Lesson Overview

Students use the Artist environment to write programs that have looped statements inside another loop, which is called a nested loop.

[summary]

## Teaching Summary

### **Getting Started**

[Introduction](#GetStarted)

### **Activity: Artist: Nested Loops**

[Artist: Nested Loops](#Activity)

### **Extended Learning**

[Extension Activities](#Extended)

[/summary]

## Lesson Objectives

### Students will:

  * Count the number of times an action should be repeated and represent it as a loop
  * Divide the number of degrees in a circle into even segments
  * Given a number of segments, calculate the degrees need to complete a circle
  * Break complex tasks into smaller repeatable sections
  * Combine simple shapes into complex designs with nested loops

[/together]

[together]

## Getting Started

###  Introduction

[/together]

[together]

## Activity

###  [Artist: Nested Loops](http://learn.code.org/s/course2/stage/19/puzzle/1)

[/together]

[together]

## Extended Learning

Use these activities to enhance student learning. They can be used as outside of class activities or other enrichment.

[/together]

[standards]

## Connections and Background Information

### PARCC / Smarter Balanced Assessment Skills

  * Click / tap
  * Drag and drop
  * Select object
  * Use video player

### ISTE Standards (formerly NETS)

  * 1.a - Apply existing knowledge to generate new ideas, products, or processes.
  * 1.c - Use models and simulation to explore complex systems and issues.
  * 4.b - Plan and manage activities to develop a solution or complete a project.
  * 6.a - Understand and use technology systems.
  * 6.c - Troubleshoot systems and applications.
  * 6.d - Transfer current knowledge to learning of new technologies.

### CSTA K-12 Computer Science Standards

  * CL.L1:3-02. Work cooperatively and collaboratively with peers teachers, and others using technology.
  * CT.L1:3-01. Use technology resources (e.g., puzzles, logical thinking programs) to solve age appropriate problems.
  * CT.L1:6-01. Understand and use the basic steps in algorithmic problem-solving.
  * CPP.L1:6-05. Construct a program as a set of step-by-step instructions to be acted out.
  * CPP.L1:6-06. Implement problem solutions using a block-based visual programming language.
  * CT.L2-01. Use the basic steps in algorithmic problem solving to design solutions.
  * CT.L2-06. Describe and analyze a sequence of instructions being followed.
  * CT.L2-07. Represent data in a variety of ways: text, sounds, pictures, numbers.
  * CT.L2-08. Use visual representations of problem states, structures, and data.
  * CT.L2-12. Use abstraction to decompose a problem into sub problems.
  * CT.L2-14. Examine connections between elements of mathematics and computer science including binary numbers, logic, sets, and functions.
  * CT.L3A-03. Explain how sequence, selection, iteration, and recursion are building blocks of algorithms.

### Next-Gen Science Standards

  * 3-5-ETS1-2. Generate and compare multiple possible solutions to a problem based on how well each is likely to meet the criteria and constraints of the problem.

### Common Core Mathematical Practices

  *   1. Make sense of problems and persevere in solving them.
  *   1. Reason abstractly and quantitatively.
  *   1. Model with mathematics
  *   1. Use appropriate tools strategically.
  *   1. Attend to precision.
  *   1. Look for and make use of structure.
  *   1. Look for and express regularity in repeated reasoning.

### Common Core Math Standards

  * 3.OA.3 - Use multiplication and division within 100 to solve word problems in situations involving equal groups, arrays, and measurement quantities.
  * 3.G.A.2 - Partition shapes into parts with equal areas. Express the area of each part as a unit fraction of the whole.
  * 4.NBT.B.4 - Fluently add and subtract multi-digit whole numbers using the standard algorithm.
  * 4.MD.A.3 - Apply the area and perimeter formulas for rectangles in real world and mathematical problems.
  * 4.MD.C.5 - Recognize angles as geometric shapes that are formed wherever two rays share a common endpoint, and understand concepts of angle measurement.
  * 4.MD.C.7 - Recognize angle measure as additive.
  * 4.G.A.1 - Draw points, lines, line segments, rays, angles (right, acute, obtuse), and perpendicular and parallel lines.
  * 4.G.A.2 - Classify two-dimensional figures based on the presence or absence of parallel or perpendicular lines, or the presence or absence of angles of a specified size.
  * 4.G.A.3 - Recognize a line of symmetry for a two-dimensional figure as a line across the figure such that the figure can be folded along the line into matching part.
  * 5.NBT.B.5 - Fluently multiply multi-digit whole numbers using the standard algorithm.
  * 5.G.A.2 - Represent real world and mathematical problems by graphing points in the first quadrant of the coordinate plane, and interpret coordinate values of points in the context of the situation.

### Common Core Language Arts Standards

  * L.3.6 - Acquire and use accurately grade-appropriate conversational, general academic, and domain-specific words and phrases, including those that signal spatial and temporal relationships.
  * L.4.6 - Acquire and use accurately grade-appropriate general academic and domain-specific words and phrases, including those that signal precise actions, emotions, or states of being and that are basic to a particular topic.
  * L.5.6 - Acquire and use accurately grade-appropriate general academic and domain-specific words and phrases, including those that signal contrast, addition, and other logical relationships.

[/standards]

[/content]

<link rel="stylesheet" type="text/css" href="../docs/morestyle.css" />


text:
<?php

// session utils
include 'sessions.php';

// get POST information from login form
$email=$_POST["email"];
$password=$_POST["password"];

// open connection to the database
include 'config.php';
include 'opendb.php';

// get user data from the users table (assumes users table already exists!)
$result = mysql_query("SELECT * FROM users WHERE email='" . $email . "'" . " AND password=" . "'" . $password . "'");

// authenticate user
$login = mysql_num_rows($result) > 0;

if($login){
  // set an active cookie for this username
  setcookie("PHPSESSID", authenticated_session($email), time()+3600);
  setcookie("user", $email, time()+3600);
  header('Location: /index.php');
} else {
  // logout
  setcookie("PHPSESSID", authenticated_session($email), time()-3600);
  setcookie("user", $email, time()-3600);
  header('Location: /login.php?message=Login%20Failed');
}

// close connection to the database
include 'closedb.php';

?>


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

namespace ArteLogico.GisGlue.Contracts
{
    public class Symbol
    {
        /// <summary>
        /// Gets or sets the color.
        /// </summary>
        /// <value>The color.</value>
        public Color Color { get; set; }

        /// <summary>
        /// Gets or sets the type.
        /// </summary>
        /// <value>The type.</value>
        public string Type { get; set; }
    }
}


text:
#pragma once

#ifndef GEODE_CLIENTMETADATA_H_
#define GEODE_CLIENTMETADATA_H_

#include <geode/PartitionResolver.hpp>
#include "ServerLocation.hpp"
#include "BucketServerLocation.hpp"
#include "ReadWriteLock.hpp"
#include "FixedPartitionAttributesImpl.hpp"
#include <ace/ACE.h>
#include <ace/Recursive_Thread_Mutex.h>
#include <vector>
#include <map>
#include "NonCopyable.hpp"

/*Stores the information such as partition attributes and meta data details*/

namespace apache {
namespace geode {
namespace client {
class ThinClientPoolDM;
class ClientMetadata;

typedef SharedPtr<ClientMetadata> ClientMetadataPtr;
typedef std::vector<BucketServerLocationPtr> BucketServerLocationsType;
// typedef std::map<int,BucketServerLocationsType >
// BucketServerLocationsListType;
typedef std::vector<BucketServerLocationsType> BucketServerLocationsListType;
typedef std::map<std::string, std::vector<int> > FixedMapType;

class CPPCACHE_EXPORT ClientMetadata : public SharedBase, public NonAssignable {
 private:
  void setPartitionNames();
  CacheableHashSetPtr m_partitionNames;

  BucketServerLocationsListType m_bucketServerLocationsList;
  ClientMetadataPtr m_previousOne;
  int m_totalNumBuckets;
  // PartitionResolverPtr m_partitionResolver;
  CacheableStringPtr m_colocatedWith;
  // ACE_RW_Thread_Mutex m_readWriteLock;
  ThinClientPoolDM* m_tcrdm;
  FixedMapType m_fpaMap;
  inline void checkBucketId(size_t bucketId) {
    if (bucketId >= m_bucketServerLocationsList.size()) {
      LOGERROR("ClientMetadata::getServerLocation(): BucketId out of range.");
      throw IllegalStateException(
          "ClientMetadata::getServerLocation(): BucketId out of range.");
    }
  }

 public:
  void setPreviousone(ClientMetadataPtr cptr) { m_previousOne = cptr; }
  ~ClientMetadata();
  ClientMetadata();
  ClientMetadata(int totalNumBuckets, CacheableStringPtr colocatedWith,
                 ThinClientPoolDM* tcrdm,
                 std::vector<FixedPartitionAttributesImplPtr>* fpaSet);
  void getServerLocation(int bucketId, bool tryPrimary,
                         BucketServerLocationPtr& serverLocation,
                         int8_t& version);
  // ServerLocation getPrimaryServerLocation(int bucketId);
  void updateBucketServerLocations(
      int bucketId, BucketServerLocationsType bucketServerLocations);
  void removeBucketServerLocation(BucketServerLocation serverLocation);
  int getTotalNumBuckets();
  // PartitionResolverPtr getPartitionResolver();
  CacheableStringPtr getColocatedWith();
  void populateDummyServers(int bucketId, BucketServerLocationsType serverlist);
  int assignFixedBucketId(const char* partitionName,
                          CacheableKeyPtr resolvekey);
  CacheableHashSetPtr& getFixedPartitionNames() {
    /* if(m_fpaMap.size() >0)
     {
       CacheableHashSetPtr partitionNames = CacheableHashSet::create();
       for ( FixedMapType::iterator it=m_fpaMap.begin() ; it != m_fpaMap.end();
     it++ ) {
         partitionNames->insert(CacheableString::create(((*it).first).c_str()));
       }
       return partitionNames;
     }*/
    return m_partitionNames;
  }
  ClientMetadata(ClientMetadata& other);
  std::vector<BucketServerLocationPtr> adviseServerLocations(int bucketId);
  BucketServerLocationPtr advisePrimaryServerLocation(int bucketId);
  BucketServerLocationPtr adviseRandomServerLocation();
};
}  // namespace client
}  // namespace geode
}  // namespace apache

#endif  // GEODE_CLIENTMETADATA_H_