text:
/*
 * Declarations shared between the different parts of the io module
 */

/* ABCs */
extern PyTypeObject PyIOBase_Type;
extern PyTypeObject PyRawIOBase_Type;
extern PyTypeObject PyBufferedIOBase_Type;
extern PyTypeObject PyTextIOBase_Type;

/* Concrete classes */
extern PyTypeObject PyFileIO_Type;
extern PyTypeObject PyBytesIO_Type;
extern PyTypeObject PyStringIO_Type;
extern PyTypeObject PyBufferedReader_Type;
extern PyTypeObject PyBufferedWriter_Type;
extern PyTypeObject PyBufferedRWPair_Type;
extern PyTypeObject PyBufferedRandom_Type;
extern PyTypeObject PyTextIOWrapper_Type;
extern PyTypeObject PyIncrementalNewlineDecoder_Type;

extern int _PyIO_ConvertSsize_t(PyObject *, void *);

/* These functions are used as METH_NOARGS methods, are normally called
 * with args=NULL, and return a new reference.
 * BUT when args=Py_True is passed, they return a borrowed reference.
 */
extern PyObject* _PyIOBase_check_readable(PyObject *self, PyObject *args);
extern PyObject* _PyIOBase_check_writable(PyObject *self, PyObject *args);
extern PyObject* _PyIOBase_check_seekable(PyObject *self, PyObject *args);
extern PyObject* _PyIOBase_check_closed(PyObject *self, PyObject *args);

/* Helper for finalization.
   This function will revive an object ready to be deallocated and try to
   close() it. It returns 0 if the object can be destroyed, or -1 if it
   is alive again. */
extern int _PyIOBase_finalize(PyObject *self);

/* Returns true if the given FileIO object is closed.
   Doesn't check the argument type, so be careful! */
extern int _PyFileIO_closed(PyObject *self);

/* Shortcut to the core of the IncrementalNewlineDecoder.decode method */
extern PyObject *_PyIncrementalNewlineDecoder_decode(
    PyObject *self, PyObject *input, int final);

/* Finds the first line ending between `start` and `end`.
   If found, returns the index after the line ending and doesn't touch
   `*consumed`.
   If not found, returns -1 and sets `*consumed` to the number of characters
   which can be safely put aside until another search.

   NOTE: for performance reasons, `end` must point to a NUL character ('\0').
   Otherwise, the function will scan further and return garbage. */
extern Py_ssize_t _PyIO_find_line_ending(
    int translated, int universal, PyObject *readnl,
    int kind, char *start, char *end, Py_ssize_t *consumed);

/* Return 1 if an EnvironmentError with errno == EINTR is set (and then
   clears the error indicator), 0 otherwise.
   Should only be called when PyErr_Occurred() is true.
*/
extern int _PyIO_trap_eintr(void);

#define DEFAULT_BUFFER_SIZE (8 * 1024)  /* bytes */

/*
 * Offset type for positioning.
 */

/* Printing a variable of type off_t (with e.g., PyUnicode_FromFormat)
   correctly and without producing compiler warnings is surprisingly painful.
   We identify an integer type whose size matches off_t and then: (1) cast the
   off_t to that integer type and (2) use the appropriate conversion
   specification.  The cast is necessary: gcc complains about formatting a
   long with "%lld" even when both long and long long have the same
   precision. */

#ifdef MS_WINDOWS

/* Windows uses long long for offsets */
typedef PY_LONG_LONG Py_off_t;
# define PyLong_AsOff_t     PyLong_AsLongLong
# define PyLong_FromOff_t   PyLong_FromLongLong
# define PY_OFF_T_MAX       PY_LLONG_MAX
# define PY_OFF_T_MIN       PY_LLONG_MIN
# define PY_OFF_T_COMPAT    PY_LONG_LONG /* type compatible with off_t */
# define PY_PRIdOFF         "lld"        /* format to use for that type */

#else

/* Other platforms use off_t */
typedef off_t Py_off_t;
#if (SIZEOF_OFF_T == SIZEOF_SIZE_T)
# define PyLong_AsOff_t     PyLong_AsSsize_t
# define PyLong_FromOff_t   PyLong_FromSsize_t
# define PY_OFF_T_MAX       PY_SSIZE_T_MAX
# define PY_OFF_T_MIN       PY_SSIZE_T_MIN
# define PY_OFF_T_COMPAT    Py_ssize_t
# define PY_PRIdOFF         "zd"
#elif (HAVE_LONG_LONG && SIZEOF_OFF_T == SIZEOF_LONG_LONG)
# define PyLong_AsOff_t     PyLong_AsLongLong
# define PyLong_FromOff_t   PyLong_FromLongLong
# define PY_OFF_T_MAX       PY_LLONG_MAX
# define PY_OFF_T_MIN       PY_LLONG_MIN
# define PY_OFF_T_COMPAT    PY_LONG_LONG
# define PY_PRIdOFF         "lld"
#elif (SIZEOF_OFF_T == SIZEOF_LONG)
# define PyLong_AsOff_t     PyLong_AsLong
# define PyLong_FromOff_t   PyLong_FromLong
# define PY_OFF_T_MAX       LONG_MAX
# define PY_OFF_T_MIN       LONG_MIN
# define PY_OFF_T_COMPAT    long
# define PY_PRIdOFF         "ld"
#else
# error off_t does not match either size_t, long, or long long!
#endif

#endif

extern Py_off_t PyNumber_AsOff_t(PyObject *item, PyObject *err);

/* Implementation details */

/* IO module structure */

extern PyModuleDef _PyIO_Module;

typedef struct {
    int initialized;
    PyObject *locale_module;

    PyObject *unsupported_operation;
} _PyIO_State;

#define IO_MOD_STATE(mod) ((_PyIO_State *)PyModule_GetState(mod))
#define IO_STATE() _PyIO_get_module_state()

extern _PyIO_State *_PyIO_get_module_state(void);
extern PyObject *_PyIO_get_locale_module(_PyIO_State *);

extern PyObject *_PyIO_str_close;
extern PyObject *_PyIO_str_closed;
extern PyObject *_PyIO_str_decode;
extern PyObject *_PyIO_str_encode;
extern PyObject *_PyIO_str_fileno;
extern PyObject *_PyIO_str_flush;
extern PyObject *_PyIO_str_getstate;
extern PyObject *_PyIO_str_isatty;
extern PyObject *_PyIO_str_newlines;
extern PyObject *_PyIO_str_nl;
extern PyObject *_PyIO_str_read;
extern PyObject *_PyIO_str_read1;
extern PyObject *_PyIO_str_readable;
extern PyObject *_PyIO_str_readall;
extern PyObject *_PyIO_str_readinto;
extern PyObject *_PyIO_str_readline;
extern PyObject *_PyIO_str_reset;
extern PyObject *_PyIO_str_seek;
extern PyObject *_PyIO_str_seekable;
extern PyObject *_PyIO_str_setstate;
extern PyObject *_PyIO_str_tell;
extern PyObject *_PyIO_str_truncate;
extern PyObject *_PyIO_str_writable;
extern PyObject *_PyIO_str_write;

extern PyObject *_PyIO_empty_str;
extern PyObject *_PyIO_empty_bytes;
extern PyObject *_PyIO_zero;

extern PyTypeObject _PyBytesIOBuffer_Type;


text:
package main

var (
	commandsMap map[string]command = make(map[string]command)
)

func init() {
	commands := []command{
		newBuilderCommand(newGoParameterMapper()),
		newBuilderCommand(newCmakeParameterMapper()),
	}
	for _, c := range commands {
		commandsMap[c.Name()] = c
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace PluralizationServices.Rules.RuleEndedInL
{
    using static System.Text.RegularExpressions.Regex;

    using static PluralizationServices.Rules.PluralizationRule;

    internal sealed class SpecialPluralizationRuleEndedInIl : PluralizationRule
    {
        private const string Pattern = "il$";

        public SpecialPluralizationRuleEndedInIl(string word)
            : base(word)
        {
        }

        internal override bool Verify() => IsMatch(this.Word, Pattern, RegexOptions);

        internal override string Apply()
        {
            if (IsMatch(this.Word, "[áéêíó]", RegexOptions))
            {
                return Replace(this.Word, Pattern, "eis");
            }

            return Replace(this.Word, Pattern, "is");
        }
    }
}


text:
layout: post
title: Building a chat app with @flightjs Part 2 - boarding RequireJS, Karma, and Jasmine
permalink: flightjs-part-2
category: Front-end Ninja
tags: [flightjs, karma, jasmine, testing, requirejs]
---

This is part three in my series on building [this chat app](http://flight-chat.herokuapp.com/) with Flight, check out [part 1 here](/flightjs-part-1) and [part 3 here](/flightjs-part-3). The source code is [available on github](https://github.com/stefanRitter/flight-chat).

## **Modules with RequireJS**

[RequireJS](http://requirejs.org/) is a module system for Javascript, wich makes it easy to write encapsulated and reusable code. RequireJs modules can then be dynamically required only when needed.
There are other methods of modularising Javascript, [this is a blogpost by Addi Osmani](http://addyosmani.com/writing-modular-js/) comparing AMD style modules like RequireJS to CommonJS-style modules.

Understanding RequireJS is very straightforward — all you need to know is the two functions **define()** and **require()**.
Yeoman has already installed and added RequireJS to our app/index.html so we won't need to add it to our app manually. Also take a look in app/js/ and you will see the main.js file which has a small piece of code to configure RequireJS (mainly setting up some shortcuts to the paths in our app, and calling the first require() to get Flight's own library).

First let's define a barebones module in a file called simpleModule.js and we can save it under app/js/mixin:

define(function() {
  console.log('in my simple module');
});

We can then make a call to require in main.js, and see output in the console:

require('mixin/simpleModule');

There are two optional parameters that can be passed into a call to define(). They can change the module definition's signature quite a bit. One parameter is for the module's name, and the other is an array to list the module's dependencies:

// 1 — giving a module a name
define('myNamedModule', function() {
  return {name: 'myModule'};
});

// 2 — defining a module's dependencies and giving it a name
define('moduleDependingOnJquery', ['jQuery'], function($) {
  return $('button');
});

// 3 — defining a module's dependencies without a name
define(['underscore', 'jQuery'], function(_, $) {
  var array = [2,3,4,2,3,4,6];
  return _.uniq(array);
});

// 4 — asking RequireJS to parse parameters for dependencies
define(function(underscore, jQuery) {
  var _ = underscore,
       $ = jQuery;
});

RequireJS looks for each dependency defined in the array and injects them into the module's function as its parameters. In example 3 our module has access to underscore's uniq function through the '_' parameter and it could use jQuery through the usual dollar-sign syntax.
Compare that with example 4 where we ask RequireJS to load dependencies based on parameter names — you can see we needed an extra var expression to get the same short access to these two libraries as a result.

If you don't want to list a module's dependencies right in the beginning when calling define(), you can do so later within the module by using **require()**:

// 5 — using require()
define(function(require) {

 var $ = require('jQuery');

 var templates = require('js/templates'),
      template = templates['templates/app_view.html'].render();

 return function() { $('#app').html(template); };
});

Notice that we had to ask for require as a dependency first before we could start using it.

Now you know how to define and require modules, and how to dynamically load pre-compiled Hogan templates and render them! Finally, let's write some Flight components.

## Good Karma with Jasmine tests

Our chat app has three Flight.js pages located in app/js/page: The first one is the default page which get's called when we enter the app for the first time. It attaches three basic components to the document, one of which checks if the user is already logged in and triggers a 'uiSwitchPage' event. In that event it tells the app to either go to the login page or the app page next.
Let's write the switchPage component, which listens for this event.

We start with calling our yeoman generator in the command line:

yo flight:component switchPage

This generates two files for us, one being for the component itself and one for its tests. The generator places all components into the app/js/component/ folder, but I prefer to split them into ui vs data components, so I'll move this one into app/js/component_ui/ as switchPage handles user interface events.

Our spec file will look like the following after generation — notice Flight uses [Jasmine](http://jasmine.github.io/1.3/introduction.html) for its tests, which is a behaviour driven testing framework, so it should be very straightforward - like reading in plain English - what the tests are about:

'use strict';
describeComponent('**component_ui**/switch_page', function () {

 // Initialise the component and attach it to the DOM
 beforeEach(function () {
   setupComponent();
 });

 it('should be defined', function () {
   expect(this.component).toBeDefined();
 });

 it('should do something');

});

You can run the test already in the command line with 'npm test', which will fire up karma and run our tests with PhantomJS (a command line webkit browser). Because the Yeoman generator created an empty component already our test should pass just fine.

Our switchPage component only listens to one event, which we called 'uiSwitchPage'. We can define it's behaviour as follows — replacing all functions within the describeComponent() of the auto-generated spec:

it('should initialize a new page on uiSwitchPage', function() {
  setupComponent();

  // 1. spy on the page's initialize function
  // 2. trigger event on component
  // 3. assert the page was initialized
});

Before we trigger the event on our component we need to ask Jasmine to spy on the signInPages initialize function, so that we can be sure the component called it. After that we can trigger the switchPage event and let Jasmine check if our component has reacted accordingly by initializing the page. The final test will look like this:

describeComponent('component_ui/switch_page', function () {
 it('should initialize a new page on uiSwitchPage', function() {
   setupComponent();

   **spyOn(this.component.attr, 'signinPage');**
   this.component.trigger('uiSwitchPage', {name: 'signinPage'});
   expect(this.component.attr.signinPage).toHaveBeenCalled();
 });
});

On the bold line you can see that we are planning to save the page's initialize function as a default attribute in our component. We are then using Jasmine's spyOn() method to be able to test if it was successfully called. When we run this again with npm test, obviously our test will fail.

Here is the implementation of the switchPage component, based on the above test:

define(function (require) {
 'use strict';

  var defineComponent = require('flight/lib/component'),
       **      appPage = require('page/app_page'),
      signinPage = require('page/signin_page');**

 return defineComponent(switchPage);

 function switchPage() {
   // attributes
   this.defaultAttrs({
**       'signinPage': signinPage,
       'appPage': appPage**
   });

   // initialize
   this.after('initialize', function () {
     this.on('uiSwitchPage', function(e, page) {
**       this.attr[page.name]();**
     });
   });
 }
});

In bold you can see the three main steps this component executes. First it requires our app's two pages, after which it saves each of them to the component's default attributes, and finally it calls the pages based on the page.name value coming from the 'uiSwitchPage' event.

Run the test again, and it should all pass nicely.

[Goto part 3 here.](/flightjs-part-3)


text:
require "fassets_core/engine"
require "fassets_core/plugins"
require "fancybox-rails"
require "best_in_place"

module FassetsCore
end


text:
package org.jetbrains.idea.devkit.kotlin.inspections;

import com.intellij.testFramework.TestDataPath;
import org.jetbrains.idea.devkit.inspections.LeakableMapKeyInspectionTestBase;
import org.jetbrains.idea.devkit.kotlin.DevkitKtTestsUtil;

@TestDataPath("$CONTENT_ROOT/testData/inspections/leakableMapKey")
public class LeakableMapKeyInspectionTest extends LeakableMapKeyInspectionTestBase {

  @Override
  protected String getBasePath() {
    return DevkitKtTestsUtil.TESTDATA_PATH + "inspections/leakableMapKey";
  }

  @Override
  public void testHighlighting() {
    myFixture.testHighlighting("Service.kt");
  }
}


text:
$packageName = 'passwordscan.install'
$installerType = 'exe'
$url = 'http://www.nirsoft.net/utils/passwordscan_setup.exe'
$checksum = '0ab067a6a29303a492a343d3ac9c9a7786a70e6c'
$checksumType = 'sha1'
$silentArgs = '/S'
$validExitCodes = @(0)

Install-ChocolateyPackage -PackageName "$packageName" `
                          -FileType "$installerType" `
                          -Url "$url" `
                          -SilentArgs "$silentArgs" `
                          -ValidExitCodes $validExitCodes `
                          -Checksum "$checksum" `
                          -ChecksumType "$checksumType"


text:
PalomaJS
=======

[![NPM version][npm-image]][npm-url]
[![Build status][travis-image]][travis-url]
[![Dependency Status][david-image]][david-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]

An angluar-like MVC framework, based on:

- koa Next generation web framework for node.js.
- bottlejs A powerful dependency injection micro container.

[npm-image]: https://img.shields.io/npm/v/paloma.svg?style=flat-square
[npm-url]: https://npmjs.org/package/paloma
[travis-image]: https://img.shields.io/travis/palomajs/paloma.svg?style=flat-square
[travis-url]: https://travis-ci.org/palomajs/paloma
[david-image]: http://img.shields.io/david/palomajs/paloma.svg?style=flat-square
[david-url]: https://david-dm.org/palomajs/paloma
[license-image]: http://img.shields.io/npm/l/paloma.svg?style=flat-square
[license-url]: LICENSE
[downloads-image]: http://img.shields.io/npm/dm/paloma.svg?style=flat-square
[downloads-url]: https://npmjs.org/package/paloma


text:
var vows = require("vows"),
    assert = require("assert"),
    Houkou = require("../houkou");

vows.describe("Matching")
  .addBatch({
    "An empty route": {
      topic: new Houkou(""),
      "should not resolve /": function(route) {
        assert.isFalse(route.match("/"));
      },
      "should resolve an empty string to an empty object": function(route) {
        assert.isObject(route.match(""));
        assert.isEmpty(route.match(""));
      },
    },
    "/": {
      topic: new Houkou("/"),
      "should resolve / to an empty object": function(route) {
        assert.isObject(route.match("/"));
        assert.isEmpty(route.match("/"));
      },
      "should not resolve an empty string": function(route) {
        assert.isFalse(route.match(""));
      },
    },
    "/hello/:name (no requirements)": {
      topic: new Houkou("/hello/:name"),
      "should resolve /hello/friend to an object {name: \"friend\"}": function(route) {
        assert.isObject(route.match("/hello/friend"));
        assert.equal(route.match("/hello/friend").name, "friend");
      },
      "should resolve /hello/とっと to an object {name: \"とっと\"}": function(route) {
        assert.isObject(route.match("/hello/とっと"));
        assert.equal(route.match("/hello/とっと").name, "とっと");
      },
    },
    "/hello/:name (:name only alphanumeric)": {
      topic: new Houkou("/hello/:name", {requirements: {name: "[a-z]+"}}),
      "should resolve /hello/friend to an object {name: \"friend\"}": function(route) {
        assert.isObject(route.match("/hello/friend"));
        assert.equal(route.match("/hello/friend").name, "friend");
      },
      "should not resolve /hello/とっと": function(route) {
        assert.isFalse(route.match("/hello/とっと"));
      },
    },
    "/hello/:name.:format (:format either json or html)": {
      topic: new Houkou("/hello/:name.:format", {requirements: {format: "json|html"}}),
      "should not resolve /hello/friend": function(route) {
        assert.isFalse(route.match("/hello/friend"));
      },
      "should resolve /hello/friend.json to an object {name: \"friend\", format: \"json\"}": function(route) {
        assert.isObject(route.match("/hello/friend.json"));
        assert.equal(route.match("/hello/friend.json").name, "friend");
        assert.equal(route.match("/hello/friend.json").format, "json");
      },
    },
    "document:section:!section:page:!page (custom parameter token char)": {
      topic: new Houkou("document:!id:section:!section:page:!page", {paramChar: '!'}),
      "should match document:1:section:1:page:1": function (route) {
        assert.isObject(route.match("document:1:section:1:page:1"));
        assert.equal(route.match("document:1:section:1:page:1").id, "1");
        assert.equal(route.match("document:1:section:1:page:1").section, "1");
        assert.equal(route.match("document:1:section:1:page:1").page, "1");
      }
    }
  })
.export(module);


text:
/**
@module ember
@submodule ember-templates
*/

/**
   Use the `{{hash}}` helper to create a hash to pass as an option to your
   components. This is specially useful for contextual components where you can
   just yield a hash:
   ```handlebars
   {{yield (hash
      name='Sarah'
      title=office
   )}}
   ```
   Would result in an object such as:
   ```js
   { name: 'Sarah', title: this.get('office') }
   ```
   Where the `title` is bound to updates of the `office` property.
   @method hash
   @for Ember.Templates.helpers
   @param {Object} options
   @return {Object} Hash
   @public
 */

export default function hashHelper(params, hash, options) {
  return hash;
}


text:
QuickSpecBegin(SDLRegisterAppInterfaceSpec)

SDLSyncMsgVersion* version = [[SDLSyncMsgVersion alloc] init];
SDLTTSChunk* chunk = [[SDLTTSChunk alloc] init];
SDLDeviceInfo* info = [[SDLDeviceInfo alloc] init];
SDLAppInfo* appInfo = [[SDLAppInfo alloc] init];

describe(@"Getter/Setter Tests", ^ {
    it(@"Should set and get correctly", ^ {
        SDLRegisterAppInterface* testRequest = [[SDLRegisterAppInterface alloc] init];

        testRequest.syncMsgVersion = version;
        testRequest.appName = @"app56";
        testRequest.ttsName = [@[chunk] mutableCopy];
        testRequest.ngnMediaScreenAppName = @"whatisanngn";
        testRequest.vrSynonyms = [@[@"paraphrase of the original name"] mutableCopy];
        testRequest.isMediaApplication = @NO;
        testRequest.languageDesired = SDLLanguageNoNo;
        testRequest.hmiDisplayLanguageDesired = SDLLanguagePtPt;
        testRequest.appHMIType = [@[SDLAppHMITypeMessaging, SDLAppHMITypeInformation] copy];
        testRequest.hashID = @"gercd35grw2";
        testRequest.deviceInfo = info;
        testRequest.appID = @"123456789";
        testRequest.appInfo = appInfo;

        expect(testRequest.syncMsgVersion).to(equal(version));
        expect(testRequest.appName).to(equal(@"app56"));
        expect(testRequest.ttsName).to(equal([@[chunk] mutableCopy]));
        expect(testRequest.ngnMediaScreenAppName).to(equal(@"whatisanngn"));
        expect(testRequest.vrSynonyms).to(equal([@[@"paraphrase of the original name"] mutableCopy]));
        expect(testRequest.isMediaApplication).to(equal(@NO));
        expect(testRequest.languageDesired).to(equal(SDLLanguageNoNo));
        expect(testRequest.hmiDisplayLanguageDesired).to(equal(SDLLanguagePtPt));
        expect(testRequest.appHMIType).to(equal([@[SDLAppHMITypeMessaging, SDLAppHMITypeInformation] copy]));
        expect(testRequest.hashID).to(equal(@"gercd35grw2"));
        expect(testRequest.deviceInfo).to(equal(info));
        expect(testRequest.appID).to(equal(@"123456789"));
        expect(testRequest.appInfo).to(equal(appInfo));
    });

    it(@"Should get correctly when initialized", ^ {
        NSMutableDictionary* dict = [@{SDLNameRequest:
                                           @{SDLNameParameters:
                                                 @{SDLNameSyncMessageVersion:version,
                                                   SDLNameAppName:@"app56",
                                                   SDLNameTTSName:[@[chunk] mutableCopy],
                                                   SDLNameNGNMediaScreenAppName:@"whatisanngn",
                                                   SDLNameVRSynonyms:[@[@"paraphrase of the original name"] mutableCopy],
                                                   SDLNameIsMediaApplication:@NO,
                                                   SDLNameLanguageDesired:SDLLanguageNoNo,
                                                   SDLNameHMIDisplayLanguageDesired:SDLLanguagePtPt,
                                                   SDLNameAppHMIType:[@[SDLAppHMITypeMessaging, SDLAppHMITypeInformation] copy],
                                                   SDLNameHashId:@"gercd35grw2",
                                                   SDLNameDeviceInfo:info,
                                                   SDLNameAppId:@"123456789",
                                                   SDLNameAppInfo:appInfo},
                                             SDLNameOperationName:SDLNameRegisterAppInterface}} mutableCopy];
        SDLRegisterAppInterface* testRequest = [[SDLRegisterAppInterface alloc] initWithDictionary:dict];

        expect(testRequest.syncMsgVersion).to(equal(version));
        expect(testRequest.appName).to(equal(@"app56"));
        expect(testRequest.ttsName).to(equal([@[chunk] mutableCopy]));
        expect(testRequest.ngnMediaScreenAppName).to(equal(@"whatisanngn"));
        expect(testRequest.vrSynonyms).to(equal([@[@"paraphrase of the original name"] mutableCopy]));
        expect(testRequest.isMediaApplication).to(equal(@NO));
        expect(testRequest.languageDesired).to(equal(SDLLanguageNoNo));
        expect(testRequest.hmiDisplayLanguageDesired).to(equal(SDLLanguagePtPt));
        expect(testRequest.appHMIType).to(equal([@[SDLAppHMITypeMessaging, SDLAppHMITypeInformation] copy]));
        expect(testRequest.hashID).to(equal(@"gercd35grw2"));
        expect(testRequest.deviceInfo).to(equal(info));
        expect(testRequest.appID).to(equal(@"123456789"));
        expect(testRequest.appInfo).to(equal(appInfo));
    });

    it(@"Should return nil if not set", ^ {
        SDLRegisterAppInterface* testRequest = [[SDLRegisterAppInterface alloc] init];

        expect(testRequest.syncMsgVersion).to(beNil());
        expect(testRequest.appName).to(beNil());
        expect(testRequest.ttsName).to(beNil());
        expect(testRequest.ngnMediaScreenAppName).to(beNil());
        expect(testRequest.vrSynonyms).to(beNil());
        expect(testRequest.isMediaApplication).to(beNil());
        expect(testRequest.languageDesired).to(beNil());
        expect(testRequest.hmiDisplayLanguageDesired).to(beNil());
        expect(testRequest.appHMIType).to(beNil());
        expect(testRequest.hashID).to(beNil());
        expect(testRequest.deviceInfo).to(beNil());
        expect(testRequest.appID).to(beNil());
        expect(testRequest.appInfo).to(beNil());
    });
});

QuickSpecEnd


text:
#include "mitkPivotCalibration.h"
#include "vnl/algo/vnl_svd.h"
#include "vnl/vnl_matrix.h"
#include "vnl/vnl_vector.h"
#include <vtkMatrix4x4.h>

mitk::PivotCalibration::PivotCalibration() : m_NavigationDatas(std::vector<mitk::NavigationData::Pointer>()), m_ResultPivotPoint(mitk::Point3D(0.0))
{

}

mitk::PivotCalibration::~PivotCalibration()
{

}

void mitk::PivotCalibration::AddNavigationData(mitk::NavigationData::Pointer data)
{
  m_NavigationDatas.push_back(data);
}

bool mitk::PivotCalibration::ComputePivotResult()
{
  return ComputePivotPoint();
}

bool mitk::PivotCalibration::ComputePivotPoint()
{
  double defaultThreshold = 1e-1;

  std::vector<mitk::NavigationData::Pointer> _CheckedTransforms;
  for (size_t i = 0; i < m_NavigationDatas.size(); ++i)
  {
    if (!m_NavigationDatas.at(i)->IsDataValid())
    {
      MITK_WARN << "Skipping invalid transform " << i << ".";
      continue;
    }
    _CheckedTransforms.push_back(m_NavigationDatas.at(i));
  }

  if (_CheckedTransforms.empty())
  {
    MITK_WARN << "Checked Transforms are empty";
    return false;
  }

  unsigned int rows = 3 * _CheckedTransforms.size();
  unsigned int columns = 6;

  vnl_matrix< double > A(rows, columns), minusI(3, 3, 0), R(3, 3);
  vnl_vector< double > b(rows), x(columns), t(3);

  minusI(0, 0) = -1;
  minusI(1, 1) = -1;
  minusI(2, 2) = -1;

  //do the computation and set the internal variables
  unsigned int currentRow = 0;

  for (size_t i = 0; i < _CheckedTransforms.size(); ++i)
  {
    t = _CheckedTransforms.at(i)->GetPosition().GetVnlVector();// t = the current position of the tracked sensor
    t *= -1;
    b.update(t, currentRow); //b = combines the position for each collected transform in one column vector
    R = _CheckedTransforms.at(i)->GetOrientation().rotation_matrix_transpose().transpose().as_ref(); // R = the current rotation of the tracked sensor, *rotation_matrix_transpose().transpose() is used to obtain original matrix
    A.update(R, currentRow, 0); //A = the matrix which stores the rotations for each collected transform and -I
    A.update(minusI, currentRow, 3);
    currentRow += 3;
  }
  vnl_svd<double> svdA(A); //The singular value decomposition of matrix A
  svdA.zero_out_absolute(defaultThreshold);

  //there is a solution only if rank(A)=6 (columns are linearly
  //independent)
  if (svdA.rank() < 6)
  {
    MITK_WARN << "svdA.rank() < 6";
    return false;
  }
  else
  {
    x = svdA.solve(b); //x = the resulting pivot point

    m_ResultRMSError = (A * x - b).rms();  //the root mean sqaure error of the computation

    //sets the Pivot Point
    m_ResultPivotPoint[0] = x[0];
    m_ResultPivotPoint[1] = x[1];
    m_ResultPivotPoint[2] = x[2];

  }
  return true;

}


text:
import { ResourceMetrics } from '@opentelemetry/sdk-metrics';
import { baggageUtils, getEnv } from '@opentelemetry/core';
import { OTLPMetricExporterOptions } from '../../OTLPMetricExporterOptions';
import { OTLPMetricExporterBase } from '../../OTLPMetricExporterBase';
import {
  OTLPExporterBrowserBase,
  OTLPExporterConfigBase,
  appendResourcePathToUrl,
  appendRootPathToUrlIfNeeded
} from '@opentelemetry/otlp-exporter-base';
import { createExportMetricsServiceRequest, IExportMetricsServiceRequest } from '@opentelemetry/otlp-transformer';

const DEFAULT_COLLECTOR_RESOURCE_PATH = 'v1/metrics';
const DEFAULT_COLLECTOR_URL = `http://localhost:4318/${DEFAULT_COLLECTOR_RESOURCE_PATH}`;

class OTLPExporterBrowserProxy extends OTLPExporterBrowserBase<ResourceMetrics, IExportMetricsServiceRequest> {

  constructor(config?: OTLPMetricExporterOptions & OTLPExporterConfigBase) {
    super(config);
    this._headers = Object.assign(
      this._headers,
      baggageUtils.parseKeyPairsIntoRecord(
        getEnv().OTEL_EXPORTER_OTLP_METRICS_HEADERS
      )
    );
  }

  getDefaultUrl(config: OTLPExporterConfigBase): string {
    return typeof config.url === 'string'
      ? config.url
      : getEnv().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length > 0
        ? appendRootPathToUrlIfNeeded(getEnv().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT)
        : getEnv().OTEL_EXPORTER_OTLP_ENDPOINT.length > 0
          ? appendResourcePathToUrl(getEnv().OTEL_EXPORTER_OTLP_ENDPOINT, DEFAULT_COLLECTOR_RESOURCE_PATH)
          : DEFAULT_COLLECTOR_URL;
  }

  convert(metrics: ResourceMetrics[]): IExportMetricsServiceRequest {
    return createExportMetricsServiceRequest(metrics);
  }
}

/**
 * Collector Metric Exporter for Web
 */
export class OTLPMetricExporter extends OTLPMetricExporterBase<OTLPExporterBrowserProxy> {
  constructor(config?: OTLPExporterConfigBase & OTLPMetricExporterOptions) {
    super(new OTLPExporterBrowserProxy(config), config);
  }
}


text:
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterfaceV2;
using osu.Game.Rulesets.Objects;
using osu.Game.Screens.Edit.Timing;
using osuTK;

namespace osu.Game.Screens.Edit.Compose.Components.Timeline
{
    public class DifficultyPointPiece : HitObjectPointPiece, IHasPopover
    {
        public readonly HitObject HitObject;

        private readonly BindableNumber<double> speedMultiplier;

        public DifficultyPointPiece(HitObject hitObject)
            : base(hitObject.DifficultyControlPoint)
        {
            HitObject = hitObject;

            speedMultiplier = hitObject.DifficultyControlPoint.SliderVelocityBindable.GetBoundCopy();
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            speedMultiplier.BindValueChanged(multiplier => Label.Text = $"{multiplier.NewValue:n2}x", true);
        }

        protected override bool OnClick(ClickEvent e)
        {
            this.ShowPopover();
            return true;
        }

        public Popover GetPopover() => new DifficultyEditPopover(HitObject);

        public class DifficultyEditPopover : OsuPopover
        {
            private readonly HitObject hitObject;

            private IndeterminateSliderWithTextBoxInput<double> sliderVelocitySlider;

            [Resolved(canBeNull: true)]
            private EditorBeatmap beatmap { get; set; }

            public DifficultyEditPopover(HitObject hitObject)
            {
                this.hitObject = hitObject;
            }

            [BackgroundDependencyLoader]
            private void load()
            {
                Children = new Drawable[]
                {
                    new FillFlowContainer
                    {
                        Width = 200,
                        Direction = FillDirection.Vertical,
                        AutoSizeAxes = Axes.Y,
                        Spacing = new Vector2(0, 15),
                        Children = new Drawable[]
                        {
                            sliderVelocitySlider = new IndeterminateSliderWithTextBoxInput<double>("Velocity", new DifficultyControlPoint().SliderVelocityBindable)
                            {
                                KeyboardStep = 0.1f
                            },
                            new OsuTextFlowContainer
                            {
                                AutoSizeAxes = Axes.Y,
                                RelativeSizeAxes = Axes.X,
                                Text = "Hold shift while dragging the end of an object to adjust velocity while snapping."
                            }
                        }
                    }
                };

                // if the piece belongs to a currently selected object, assume that the user wants to change all selected objects.
                // if the piece belongs to an unselected object, operate on that object alone, independently of the selection.
                var relevantObjects = (beatmap.SelectedHitObjects.Contains(hitObject) ? beatmap.SelectedHitObjects : hitObject.Yield()).ToArray();
                var relevantControlPoints = relevantObjects.Select(h => h.DifficultyControlPoint).ToArray();

                // even if there are multiple objects selected, we can still display a value if they all have the same value.
                var selectedPointBindable = relevantControlPoints.Select(point => point.SliderVelocity).Distinct().Count() == 1 ? relevantControlPoints.First().SliderVelocityBindable : null;

                if (selectedPointBindable != null)
                {
                    // there may be legacy control points, which contain infinite precision for compatibility reasons (see LegacyDifficultyControlPoint).
                    // generally that level of precision could only be set by externally editing the .osu file, so at the point
                    // a user is looking to update this within the editor it should be safe to obliterate this additional precision.
                    sliderVelocitySlider.Current.Value = selectedPointBindable.Value;
                }

                sliderVelocitySlider.Current.BindValueChanged(val =>
                {
                    if (val.NewValue == null)
                        return;

                    beatmap.BeginChange();

                    foreach (var h in relevantObjects)
                    {
                        h.DifficultyControlPoint.SliderVelocity = val.NewValue.Value;
                        beatmap.Update(h);
                    }

                    beatmap.EndChange();
                });
            }

            protected override void LoadComplete()
            {
                base.LoadComplete();
                ScheduleAfterChildren(() => GetContainingInputManager().ChangeFocus(sliderVelocitySlider));
            }
        }
    }
}


text:
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license

<https://opensource.org/licenses/BSD-3-Clause>
"""
import logging
import re
import os
import dateparser
from cameo.utility import Utility as CameoUtility
from crawlermaster.utility import Utility as CmUtility

class ConverterForCROWDCUBE:

    #建構子
    def __init__(self):
        self.cmUtility = CmUtility()
        self.cameoUtility = CameoUtility()
        self.dicParsedResultOfStartup = {} #startup.json 資料

    #轉換 startup 資訊
    def convertStartup(self, lstLstDicRawData=[]):
        #_company.html raw data
        lstDicCompanyPageRawData = lstLstDicRawData[0]
        for dicCompanyPageRawData in lstDicCompanyPageRawData[0:]:
            strCompanyFilePath = dicCompanyPageRawData.get("meta-data-html-filepath", None)
            logging.info("convert: %s"%strCompanyFilePath)
            strCompanyId = re.search("^.*\\\\(.*)_company.html$", strCompanyFilePath).group(1)
            strCompanyUrl = u"https://www.crowdcube.com/companies/" + strCompanyId
            #檢查 資料是否有誤
            lstCompanyData = dicCompanyPageRawData.get("cc-company", [])
            lstLocationData = dicCompanyPageRawData.get("cc-Location", [])
            if lstCompanyData == [] or lstLocationData == []:
                #錯誤資料 跳過
                #os.remove(strOrganizationHtmlFilePath)
                continue
            #建立 dict
            if strCompanyUrl not in self.dicParsedResultOfStartup:
                self.dicParsedResultOfStartup[strCompanyUrl] = {}
            #strCompany
            strCompany = self.cmUtility.extractFirstInList(lstSource=dicCompanyPageRawData.get("cc-company", []))
            self.dicParsedResultOfStartup[strCompanyUrl]["strCompany"] = strCompany
            #strUrl
            self.dicParsedResultOfStartup[strCompanyUrl]["strUrl"] = strCompanyUrl
            #strCrawlTime
            strCrawlTime = self.cmUtility.getCtimeOfFile(strFilePath=strCompanyFilePath)
            self.dicParsedResultOfStartup[strCompanyUrl]["strCrawlTime"] = strCrawlTime
            #lstStrFounders
            lstStrFounders = dicCompanyPageRawData.get("cc-company-founders", [])
            self.dicParsedResultOfStartup[strCompanyUrl]["lstStrFounders"] = lstStrFounders
            #strIntro
            lstStrIntro = dicCompanyPageRawData.get("cc-company-intro", [])
            self.dicParsedResultOfStartup[strCompanyUrl]["strIntro"] = u" ".join(lstStrIntro)
            """
            #lstStrProduct
            lstStrProduct = dicCompanyPageRawData.get("cb-lstStrProduct", [])
            self.dicParsedResultOfStartup[strCompanyUrl]["lstStrProduct"] = lstStrProduct
            """
            #lstIndustry
            lstIndustry = dicCompanyPageRawData.get("cc-Industry", [])
            self.dicParsedResultOfStartup[strCompanyUrl]["lstIndustry"] = lstIndustry
            #strLocation
            lstStrLocation = dicCompanyPageRawData.get("cc-Location", [])
            strLocation = u" ".join(lstStrLocation[0:-1])
            strLocation = re.sub("[\s]+", " ", strLocation).strip()
            self.dicParsedResultOfStartup[strCompanyUrl]["strLocation"] = strLocation
            #strCity
            strAddress = None
            if strLocation and strLocation != u"":
                (strAddress, fLatitude, fLongitude) = self.cameoUtility.geopyGeocode(strOriginLocation=strLocation)
            else:
                pass
            self.dicParsedResultOfStartup[strCompanyUrl]["strCity"] = strAddress
            #strCountry
            strOriginCountry = None
            if strAddress:
                strOriginCountry = strAddress.split(u",")[-1].strip()
            self.dicParsedResultOfStartup[strCompanyUrl]["strCountry"] = self.cameoUtility.getCountryCode(strCountryName=strOriginCountry)
            #strContinent
            self.dicParsedResultOfStartup[strCompanyUrl]["strContinent"] = self.cameoUtility.getContinentByCountryNameWikiVersion(strCountryName=strOriginCountry)
            #lstDicSeries
            lstDicSeries = []
            lstStrSeriesDate = dicCompanyPageRawData.get("cc-SeriesDate", [])
            for intSeriesIndex in range(len(lstStrSeriesDate)):
                dicSeries = {}
                #intSeriesValuation
                dicSeries.setdefault("intSeriesValuation", 0)
                #intSeriesMoney
                lstStrSeriesMoney = dicCompanyPageRawData.get("cc-SeriesMoney", [])
                if len(lstStrSeriesMoney) >= intSeriesIndex:
                    dicSeries.setdefault("intSeriesMoney", self.parseCrowdcubeMoney(strOriginMoney=lstStrSeriesMoney[intSeriesIndex]))
                else:
                    dicSeries.setdefault("intSeriesMoney", 0)
                #lstStrInvestorUrl
                dicSeries.setdefault("lstStrInvestorUrl", [])
                #strDate
                lstStrSeriesDate = dicCompanyPageRawData.get("cc-SeriesDate", [])
                if len(lstStrSeriesDate) >= intSeriesIndex:
                    dicSeries.setdefault("strDate", self.cameoUtility.parseStrDateByDateparser(strOriginDate=lstStrSeriesDate[intSeriesIndex]))
                else:
                    dicSeries.setdefault("strDate", "")
                #strSeriesType
                dicSeries.setdefault("strSeriesType", "")
                #lstStrInvestor
                dicSeries.setdefault("lstStrInvestor", [])
                #strCurrency
                dicSeries.setdefault("strCurrency", "GBP")
                #strCrawlTime
                dicSeries.setdefault("strCrawlTime", strCrawlTime)
                lstDicSeries.append(dicSeries)
            self.dicParsedResultOfStartup[strCompanyUrl]["lstDicSeries"] = lstDicSeries
            #lstStrFollowers (無此資料)
            self.dicParsedResultOfStartup[strCompanyUrl]["lstStrFollowers"] = []
            #isFundraising (需定義問題)
            self.dicParsedResultOfStartup[strCompanyUrl]["isFundraising"] = True
            #lstStrFoundersDesc (無此資料)
            self.dicParsedResultOfStartup[strCompanyUrl]["lstStrFoundersDesc"] = []
            #intRaisedMoney
            self.dicParsedResultOfStartup[strCompanyUrl]["intRaisedMoney"] = 0
            #intRaisedMoneyInTWD
            self.dicParsedResultOfStartup[strCompanyUrl]["intRaisedMoneyInTWD"] = 0
            #lstStrTierTagId
            self.dicParsedResultOfStartup[strCompanyUrl]["lstStrTierTagId"] = []
            #lstStrNewSubCategoryId
            self.dicParsedResultOfStartup[strCompanyUrl]["lstStrNewSubCategoryId"] = []
            #lstStrNewCategoryId
            self.dicParsedResultOfStartup[strCompanyUrl]["lstStrNewCategoryId"] = []
            #lstStrTopic (無此資料)
            #intFollower (無此資料)
            #lstStrTeam
            self.dicParsedResultOfStartup[strCompanyUrl]["lstStrTeam"] = []
            #lstStrTeamDesc
            self.dicParsedResultOfStartup[strCompanyUrl]["lstStrTeamDesc"] = []
            #lstStrInvestor
            self.dicParsedResultOfStartup[strCompanyUrl]["lstStrInvestor"] = []

    #解析 crowdcube 金額的數字
    def parseCrowdcubeMoney(self, strOriginMoney=None):
        intDefaultMoney = 0
        if not strOriginMoney or not re.search("[\d\.]+", strOriginMoney):
            return intDefaultMoney
        else:
            intParsedMoney = 0
            mMoneyWithK = re.search("([\d\.]+)k", strOriginMoney)
            mMoneyWithM = re.search("([\d\.]+)M", strOriginMoney)
            mMoneyWithB = re.search("([\d\.]+)B", strOriginMoney)
            if mMoneyWithK:
                intParsedMoney = int(float(mMoneyWithK.group(1)) * 1000)
            if mMoneyWithM:
                intParsedMoney = int(float(mMoneyWithM.group(1)) * 1000000)
            if mMoneyWithB:
                intParsedMoney = int(float(mMoneyWithB.group(1)) * 1000000000)
            return intParsedMoney

    #將 startup convert 結果寫入 startup.json
    def flushConvertedStartupDataToJsonFile(self, strJsonFilePath=None):
        self.cmUtility.writeObjectToJsonFile(dicData=self.dicParsedResultOfStartup, strJsonFilePath=strJsonFilePath)
        self.dicParsedResultOfStartup = {}


text:
layout: post
title: Cobot Business Model (Lean Startup Canvas)
date: 2010-12-03 22:01:00.000000000 +01:00
type: post
published: true
status: publish
categories: []
tags:
- businessmodel
- coworking
- english
- entrepreneurship
- leanstartup
meta:
  _original_post_id: ''
  _original_import_author: 'Ramon Suarez: Internet Entrepreneurship and Marketing'
author:
  login: ramonsuarez
  email: ramon@betacowork.com
  display_name: ramonsuarez
  first_name: Ramon
  last_name: Suarez
excerpt: 'Problem What???s the problem we think we have identified? Running a coworking
  space involves too much repetitive work (which costs too much money to do by hand):
  managing members (sign up, sign contract, change plan or other details from time
  to tim...'
---

Problem

What???s the problem we think we have identified?

Running a coworking space involves too much repetitive work (which costs too much money to do by hand):

managing members (sign up, sign contract, change plan or other details from time to time)

collecting payments, invoicing

In order to be profitable coworking spaces need to make more money by providing extra services/access to resources.

The management/accounting part is hard, so it keeps spaces from doing it.

Coworking spaces don???t know how much money they could actually make because of missing metrics.

Solution

What???s our proposed solution?

Users can sign up and manage their memberships themselves using cobot, taking a lot of work from the space managers.

Spaces can automate collecting payments for rent and extra services, which again reduces their work load and makes offering some services feasible in the first place.

Our analytics section provides spaces with the numbers they need to optimize their business and make more/enough money.

Unique Value Proposition

What value do we provide that no-one else does?

By combining features from different areas like accounting, payments and member management into a single tool and tailoring them to coworking we can help a coworking space much better than other, more generic and not so well integrated tools can.

Unfair Advantage

What makes cobot stand out against the competition, why can???t it be copied easily?

It???s pretty complicated to build a system that fits all the different requirements the coworking spaces have. As a software company that also runs a coworking space we have a lot of knowledge about both - coworking and creating software.

Customer Segments

Coworking spaces around the world (at the time ~600 spaces worldwide)

Spaces can be segmented by size and location

Location:

U.S. where coworking is already very popular and there are hundreds of spaces, language is English

Europe: ~ 200 spaces (Oct 2010), many speak English, but also requirements for localization

Rest of the world - probably a large market but many different languages, we don???t know anyone there yet

Size:

Small spaces that just started, < 20 members - don???t really need cobot that much, but it???s easier to use it from the start than to transition later

Medium spaces, 20 to 60 members, this is our main target group

Large, > 60 members, might still use cobot, but maybe some of those need their own,  more specific/customized tools

Channels

How can we reach new customers?

The global coworking mailing list allows us to see when and where new spaces open and we can get in contact with existing spaces as well.

Word of mouth: new spaces ask the established ones for advice, they will recommend us if we can build a great product.

Coworking conferences and other events, where we can give talks and demo cobot.

Key Activity

What will our users do on cobot?

Coworking managers will manage their members, charge people for services, collect payments.

Coworkers will use the site to book additional services, change their information/plan etc.

Revenue Streams

Where does the money come from?

We charge the coworking spaces money for using cobot, depending on their size (more coworkers = more income = higher fee)

We expect a coworking space who uses cobot as its business backend to keep using it pretty much for the lifetime of the space (> 5 years). An average space with ~30 coworkers would pay us 3600 EUR in 5 years (2 EUR * 30 coworkers * 12 months * 5 years)

If we can sign up 66 spaces within 1 year our monthly revenue would be 4000 EUR

If we can sign up 200 spaces in 2 years our monthly revenue would be 12000 EUR

Cost Structure

After 1 year

People:

Alex: 3500 EUR/month

contractors for sales: ?

Servers: ~200 EUR

After 2 years

People:

Thilo, Alex: 8000 EUR/month

1 support/PR/sales: 3000 EUR/month

= 11k EUR

cobot is not inherently viral so we need to do sales to get new customers (esp. in the beginning, until word of mouth generates enough customers)

New customers are acquired by email/phone, demoing/explaining the product, giving support. If we convert 5.5 spaces per month and a sales person costs us 1.5k/month our acquisition cost would be 300 EUR

Hosting: the more spaces we add the more servers we have to add

Right now we are running 170 coworkers on a small EC2 instance for ~60 EUR/month with some space to spare

200 spaces with 30 coworkers would be 6000 coworkers = 20 instances; I think we could do with 15 instances = 900 EUR/month; with larger, more cost effective instances we can bring this down to 500 EUR/month

Overall cost = 11.5k EUR/month

Competition

Nadine and other open source projects:

advantages: people can extend it the way they want, don???t have to pay for it (at least no service fee, they have to pay for setup, maintenance, development though)

disadvantages: no commercial support (for now), spaces have to set up hosting themselves, no clear product vision or product owner

Existing (membership) management apps:

advantages: they may be better than cobot at specific tasks

disadvantages: not an integrated solution specifically for coworking, so will never be an ideal solution

via cobot.tumblr.com

A great exercise by Alex: public distribution of the business model of his great tool to manage coworking spaces and a step further into lean startup. Can only say bravo!


text:
package no.digipost.signature.jaxb.adapter;

import no.digipost.signature.api.xml.XMLPortalSignatureStatusValue;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public final class XMLPortalSignatureStatusValueXmlAdapter extends XmlAdapter<String, XMLPortalSignatureStatusValue> {

    @Override
    public XMLPortalSignatureStatusValue unmarshal(String statusString) {
        return XMLPortalSignatureStatusValue.of(statusString);
    }

    @Override
    public String marshal(XMLPortalSignatureStatusValue status) {
        return status.asString();
    }

}


text:
@interface SCLinkIDExtractorTest : XCTestCase

@property (strong, nonatomic) SCLinkIDExtractor *linkIDExtractor;

@end

@implementation SCLinkIDExtractorTest

- (void)setUp {
    [super setUp];

    self.linkIDExtractor = [[SCLinkIDExtractor alloc] init];
}

- (void)test_linkIDFromURL {
    NSURL *url;
    NSString *expectedLinkID;

    url = [NSURL URLWithString:@"sc.shortcut://foo?sc_link_id=123"];
    expectedLinkID = @"123";
    XCTAssertEqualObjects([self.linkIDExtractor linkIDFromURL:url], expectedLinkID);

    url = [NSURL URLWithString:@"sc.shortcut://foo?foo=bar&sc_link_id=456"];
    expectedLinkID = @"456";
    XCTAssertEqualObjects([self.linkIDExtractor linkIDFromURL:url], expectedLinkID);

    url = [NSURL URLWithString:@"sc.shortcut://foo?foo=bar"];
    expectedLinkID = nil;
    XCTAssertEqualObjects([self.linkIDExtractor linkIDFromURL:url], expectedLinkID);
}

- (void)test_URLWithoutLinkID {
    NSURL *url, *expectedURL;

    url = [NSURL URLWithString:@"sc.shortcut://foo?sc_link_id=123"];
    expectedURL = [NSURL URLWithString:@"sc.shortcut://foo"];
    XCTAssertEqualObjects([self.linkIDExtractor URLWithoutLinkID:url], expectedURL);

    url = [NSURL URLWithString:@"sc.shortcut://foo?foo=bar&sc_link_id=456"];
    expectedURL = [NSURL URLWithString:@"sc.shortcut://foo?foo=bar"];
    XCTAssertEqualObjects([self.linkIDExtractor URLWithoutLinkID:url], expectedURL);

    url = [NSURL URLWithString:@"sc.shortcut://foo?foo=bar"];
    expectedURL = [NSURL URLWithString:@"sc.shortcut://foo?foo=bar"];
    XCTAssertEqualObjects([self.linkIDExtractor URLWithoutLinkID:url], expectedURL);
}

@end


text:
package com.setycz.AnotherDustsMod.Crusher;

import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by setyc on 30.01.2016.
 */
public final class CrusherRegistry {
    private final static List<CrusherRegistryItem> recipes = new ArrayList<CrusherRegistryItem>();

    public static void registerRecipe(Block ore, int blockMeta, Item resultItem, int resultItemMeta, int resultAmount) {
        recipes.add(new CrusherRegistryItem(ore, blockMeta, resultItem, resultAmount, resultItemMeta));
    }

    public static ItemStack createItemsForBlock(Block oreBlock, int oreMeta) {
        for (CrusherRegistryItem registeredItem : recipes) {
            if (registeredItem.getOre().equals(oreBlock) && registeredItem.getOreMeta() == oreMeta) {
                return registeredItem.createStack();
            }
        }
        return null;
    }

    public static List<CrusherRegistryItem> getAllRecipes() {
        return recipes;
    }
}


text:
/**
 * This file is part of the CernVM File System.
 */

#include "x509_helper_log.h"

#include <errno.h>
#include <fcntl.h>
#include <syslog.h>
#include <unistd.h>

#include <cassert>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>

using namespace std;  // NOLINT

namespace {
int fd_debug = -1;
FILE *file_debug = NULL;
int syslog_facility = LOG_USER;
int syslog_level = LOG_NOTICE;
char *syslog_prefix = NULL;
}

void SetLogAuthzDebug(const string &path) {
  assert(!path.empty());
  if (fd_debug >= 0)
    close(fd_debug);
  int fd_debug = open(path.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0600);
  if (fd_debug < 0) {
    syslog(LOG_USER | LOG_ERR, "could not open debug log %s (%d), abort",
           path.c_str(), errno);
    abort();
  }
  file_debug = fdopen(fd_debug, "a");
  assert(file_debug != NULL);
}

void SetLogAuthzSyslogLevel(const int level) {
  switch (level) {
    case 1:
      syslog_level = LOG_DEBUG;
      break;
    case 2:
      syslog_level = LOG_INFO;
      break;
    case 3:
      syslog_level = LOG_NOTICE;
      break;
    default:
      syslog_level = LOG_NOTICE;
      break;
  }
}

void SetLogAuthzSyslogFacility(const int local_facility) {
  switch (local_facility) {
    case 0:
      syslog_facility = LOG_LOCAL0;
      break;
    case 1:
      syslog_facility = LOG_LOCAL1;
      break;
    case 2:
      syslog_facility = LOG_LOCAL2;
      break;
    case 3:
      syslog_facility = LOG_LOCAL3;
      break;
    case 4:
      syslog_facility = LOG_LOCAL4;
      break;
    case 5:
      syslog_facility = LOG_LOCAL5;
      break;
    case 6:
      syslog_facility = LOG_LOCAL6;
      break;
    case 7:
      syslog_facility = LOG_LOCAL7;
      break;
    default:
      syslog_facility = LOG_USER;
  }
}

void SetLogAuthzSyslogPrefix(const string &prefix) {
  if (syslog_prefix)
    free(syslog_prefix);

  if (prefix == "") {
    syslog_prefix = NULL;
  } else {
    unsigned len = prefix.length() + 1;
    syslog_prefix = static_cast<char *>(malloc(len));
    assert(syslog_prefix != NULL);
    syslog_prefix[len-1] = '\0';
    memcpy(syslog_prefix, &prefix[0], prefix.length());
  }
}

void LogAuthz(const int flags, const char *format, ...) {
  char *msg = NULL;
  va_list variadic_list;
  va_start(variadic_list, format);
  int retval = vasprintf(&msg, format, variadic_list);
  assert(retval != -1);  // else: out of memory
  va_end(variadic_list);

  if ((flags & kLogAuthzDebug) && (file_debug != NULL)) {
    time_t rawtime;
    time(&rawtime);
    struct tm now;
    localtime_r(&rawtime, &now);
    fprintf(file_debug, "%s    [%02d-%02d-%04d %02d:%02d:%02d %s]\n", msg,
            (now.tm_mon)+1, now.tm_mday, (now.tm_year)+1900, now.tm_hour,
            now.tm_min, now.tm_sec, now.tm_zone);
    fflush(file_debug);
  }

  if (flags & (kLogAuthzSyslog | kLogAuthzSyslogWarn | kLogAuthzSyslogErr)) {
    int level = syslog_level;
    if (flags & kLogAuthzSyslogWarn) level = LOG_WARNING;
    if (flags & kLogAuthzSyslogErr) level = LOG_ERR;
    if (syslog_prefix) {
      syslog(syslog_facility | level, "(%s) %s", syslog_prefix, msg);
    } else {
      syslog(syslog_facility | level, "%s", msg);
    }
  }

  free(msg);
}


text:
Run_In_Intake::Run_In_Intake() {
	Requires(Subsystems::intake);
}

void Run_In_Intake::Execute() {
	Subsystems::intake->set_normalized(1.0);
}

bool Run_In_Intake::IsFinished() {
	return false;
}

void Run_In_Intake::Interrupted() {
	Subsystems::intake->set_normalized(0.0);
}

void Run_In_Intake::End() {
	Subsystems::intake->set_normalized(0.0);
}