text:
namespace offline_pages {

namespace {

const version_info::Channel kTestChannel = version_info::Channel::UNKNOWN;

class StubPrefetchBackgroundTaskHandler : public PrefetchBackgroundTaskHandler {
 public:
  StubPrefetchBackgroundTaskHandler() = default;

  StubPrefetchBackgroundTaskHandler(const StubPrefetchBackgroundTaskHandler&) =
      delete;
  StubPrefetchBackgroundTaskHandler& operator=(
      const StubPrefetchBackgroundTaskHandler&) = delete;

  ~StubPrefetchBackgroundTaskHandler() override = default;
  void CancelBackgroundTask() override {}
  void EnsureTaskScheduled() override {}
  void Backoff() override {}
  void ResetBackoff() override {}
  void PauseBackoffUntilNextRun() override {}
  void Suspend() override {}
  void RemoveSuspension() override {}
  int GetAdditionalBackoffSeconds() const override { return 0; }
};

}  // namespace

PrefetchServiceTestTaco::PrefetchServiceTestTaco() {
  dispatcher_ = std::make_unique<TestPrefetchDispatcher>();
  gcm_handler_ = std::make_unique<TestPrefetchGCMHandler>();

  pref_service_ = std::make_unique<TestingPrefServiceSimple>();
  prefetch_prefs::RegisterPrefs(
      static_cast<TestingPrefServiceSimple*>(pref_service_.get())->registry());

  metrics_collector_ =
      std::make_unique<TestOfflineMetricsCollector>(pref_service_.get());
  network_request_factory_ =
      std::make_unique<TestPrefetchNetworkRequestFactory>(
          new network::TestSharedURLLoaderFactory, pref_service_.get());

  prefetch_store_ =
      std::make_unique<PrefetchStore>(base::ThreadTaskRunnerHandle::Get());

  download_service_ = std::make_unique<TestDownloadService>();
  prefetch_downloader_ = std::make_unique<PrefetchDownloaderImpl>(
      download_service_.get(), kTestChannel, pref_service_.get());
  download_client_ =
      std::make_unique<TestDownloadClient>(prefetch_downloader_.get());
  download_service_->SetClient(download_client_.get());
  prefetch_importer_ = std::make_unique<TestPrefetchImporter>();

  thumbnail_image_fetcher_ =
      std::make_unique<image_fetcher::MockImageFetcher>();

  prefetch_background_task_handler_ =
      std::make_unique<StubPrefetchBackgroundTaskHandler>();
  offline_page_model_ = std::make_unique<StubOfflinePageModel>();
}

PrefetchServiceTestTaco::~PrefetchServiceTestTaco() = default;

void PrefetchServiceTestTaco::SetOfflineMetricsCollector(
    std::unique_ptr<OfflineMetricsCollector> metrics_collector) {
  CHECK(!prefetch_service_);
  CHECK(metrics_collector);
  metrics_collector_ = std::move(metrics_collector);
}

void PrefetchServiceTestTaco::SetPrefetchDispatcher(
    std::unique_ptr<PrefetchDispatcher> dispatcher) {
  CHECK(!prefetch_service_);
  CHECK(dispatcher);
  dispatcher_ = std::move(dispatcher);
}

void PrefetchServiceTestTaco::SetPrefetchGCMHandler(
    std::unique_ptr<PrefetchGCMHandler> gcm_handler) {
  CHECK(!prefetch_service_);
  gcm_handler_ = std::move(gcm_handler);
}

void PrefetchServiceTestTaco::SetPrefetchNetworkRequestFactory(
    std::unique_ptr<PrefetchNetworkRequestFactory> network_request_factory) {
  CHECK(!prefetch_service_);
  CHECK(network_request_factory);
  network_request_factory_ = std::move(network_request_factory);
}

void PrefetchServiceTestTaco::SetPrefetchStore(
    std::unique_ptr<PrefetchStore> prefetch_store) {
  CHECK(!prefetch_service_);
  CHECK(prefetch_store);
  prefetch_store_ = std::move(prefetch_store);
}

void PrefetchServiceTestTaco::SetPrefetchDownloader(
    std::unique_ptr<PrefetchDownloader> prefetch_downloader) {
  CHECK(!prefetch_service_);
  CHECK(prefetch_downloader);
  prefetch_downloader_ = std::move(prefetch_downloader);
}

void PrefetchServiceTestTaco::SetPrefetchImporter(
    std::unique_ptr<PrefetchImporter> prefetch_importer) {
  CHECK(!prefetch_service_);
  prefetch_importer_ = std::move(prefetch_importer);
}

void PrefetchServiceTestTaco::SetPrefetchBackgroundTaskHandler(
    std::unique_ptr<PrefetchBackgroundTaskHandler>
        prefetch_background_task_handler) {
  CHECK(!prefetch_service_);
  prefetch_background_task_handler_ =
      std::move(prefetch_background_task_handler);
}

void PrefetchServiceTestTaco::SetThumbnailImageFetcher(
    std::unique_ptr<image_fetcher::ImageFetcher> thumbnail_image_fetcher) {
  CHECK(!prefetch_service_);
  thumbnail_image_fetcher_ = std::move(thumbnail_image_fetcher);
}

void PrefetchServiceTestTaco::SetOfflinePageModel(
    std::unique_ptr<OfflinePageModel> offline_page_model) {
  CHECK(!prefetch_service_);
  offline_page_model_ = std::move(offline_page_model);
}

void PrefetchServiceTestTaco::SetPrefService(
    std::unique_ptr<PrefService> prefs) {
  if (pref_service_.get())
    pref_service_.reset(nullptr);

  pref_service_ = std::move(prefs);
}

void PrefetchServiceTestTaco::CreatePrefetchService() {
  CHECK(!prefetch_service_);
  auto service = std::make_unique<PrefetchServiceImpl>(
      std::move(metrics_collector_), std::move(dispatcher_),
      std::move(network_request_factory_), offline_page_model_.get(),
      std::move(prefetch_store_), std::move(prefetch_downloader_),
      std::move(prefetch_importer_), std::move(gcm_handler_),
      std::move(prefetch_background_task_handler_),
      thumbnail_image_fetcher_.get(), pref_service_.get());
  prefetch_service_ = std::move(service);
}

std::unique_ptr<PrefetchService>
PrefetchServiceTestTaco::CreateAndReturnPrefetchService() {
  CreatePrefetchService();
  return std::move(prefetch_service_);
}

}  // namespace offline_pages


text:
import { Cell, Transaction, CellLoop, CellSink, Stream, StreamSink, Tuple2, lambda2, lambda3 } from "sodiumjs";
import { SelfDisposingContainer } from "../../../lib/display/SelfDisposingContainer";
import { Menu, CreateMenuItem } from "../../../lib/menu/Menu";
import { Main, CanvasWidth, CanvasHeight } from "../../main/Main";
import {Draggable, DraggableEvent, DraggableEventType, DraggableGesture} from "../../../lib/draggable/Draggable";
import { Shape, CreateShapes } from "./Move_UI";

export class Move extends SelfDisposingContainer {
    private _dispose: () => void;

    constructor() {
        super();

        const unlisteners = new Array<() => void>();

        //ui
        const shapes = CreateShapes();
        shapes.forEach(shape => this.addChild(shape));

        //create draggables for ui elements, and assign for later disposing
        const draggables = shapes.map(shape => new Draggable(shape));

        //combine all drag events into one stream (we're not interested in multi-touch)
        const sDragEvents = draggables
                .map(drag => drag.sEvent)
                .reduce((acc: Stream<DraggableEvent>, elem: Stream<DraggableEvent>) => acc.orElse(elem));

        //listen to updates and change highlight (position updates are handled via Draggable)
        Transaction.run((): void => {
            unlisteners.push(
                sDragEvents
                    .filter(evt => evt.type === DraggableEventType.START)
                    .listen(evt => {
                        (evt.displayTarget as Shape).selected = true;
                    }),

                sDragEvents
                    .filter(evt => evt.type === DraggableEventType.END)
                    .listen(evt => {
                        (evt.displayTarget as Shape).selected = false;
                    }),

                sDragEvents
                    .filter(evt => evt.gesture === DraggableGesture.TAP)
                    .listen(evt => {
                        alert((evt.displayTarget as Shape).opts.type + " was tapped!")
                    }),
            );
        });

        this._dispose = () => {
            unlisteners.forEach(unlistener => unlistener());
            draggables.forEach(drag => drag.dispose());
        }
    }

    //cleanup
    dispose() {
        this._dispose();
    }
}

redpajama_set_name: RedPajamaGithub


text:
Spiritual clone of ink ( https://github.com/inkle/ink ) but with static code compilation and a few other premises.
Is a homage on inkable's ink, but in a different flavour (Name means "Python Ink", because of the syntax changes).

# Premises

This is the brainstorm list:

* Keep the homage on Markdown and Ink if possible (well, it looks like it's going to be "better")
* Visualization
* Multiple Choices
* Different types of "messages" (Images, Video, Audio, Mini-Games)
* Time (Delay, Mission-Clock)
* State (Position, Health, Inventory, etc., Anxiety)
* I18N, T10N
* Links?

# Unsorted Link List (reference)

* https://github.com/antlr/antlr4/blob/master/doc/predicates.md
* https://github.com/antlr/grammars-v4/tree/master/python3
* https://github.com/yshavit/antlr-denter
* https://github.com/tabatkins/bikeshed
* https://github.com/inkle/ink/blob/master/Documentation/WritingWithInk.md
* http://blog.yuvalshavit.com/2014/02/python-like-indentation-using-antlr4.html


text:
package com.galactogolf.specificobjectmodel;

import com.galactogolf.genericobjectmodel.BoundingBox;
import com.galactogolf.genericobjectmodel.GameWorld;
import com.galactogolf.genericobjectmodel.NonPlayerEntity;
import com.galactogolf.genericobjectmodel.Vector2D;
import com.galactogolf.genericobjectmodel.GameWorld.CollisionModes;
import com.galactogolf.views.RenderInstructionBuffer;

/***
 * Represents a 2d line barrier in space, which destroys the player if we hit it
 *
 */
public class BarrierEntity extends NonPlayerEntity {

	/***
	 * because the barrier is a long line, test for visibility by testing the
	 * end points
	 *
	 * TODO - this won't work with long lines!
	 */
	@Override
	public boolean isVisibleAndInFrustrum(float cameraMinX, float cameraMinY,
			float cameraMaxX, float cameraMaxY) {
		if (_position1.x > cameraMinX && _position1.y > cameraMinY
				&& _position1.x < cameraMaxX && _position1.y < cameraMaxY) {
			return true;
		}

		else if (_position2.x > cameraMinX && _position2.y > cameraMinY
				&& _position2.x < cameraMaxX && _position2.y < cameraMaxY)

		{
			return true;
		} else {
			return false;
		}

	}

	protected Vector2D _position1;

	public Vector2D getPosition1() {
		return _position1;
	}

	public void setPosition1(Vector2D position1) {
		_position1 = position1;
	}

	public Vector2D getPosition2() {
		return _position2;
	}

	public void setPosition2(Vector2D position2) {
		_position2 = position2;
	}

	protected Vector2D _position2;

	public BarrierEntity(String name, GameWorld world) {
		super(name, world);
		_position1 = new Vector2D();
		_position2 = new Vector2D();
		_boundingBox = new BoundingBox();
	}

	private float _timeSinceLastFrameChange = 100000.0f;

	@Override
	protected void updateAnimation(long timeSinceLastFrame) {
		_timeSinceLastFrameChange += timeSinceLastFrame;
		if (_timeSinceLastFrameChange > 200.0) {
			_currentFrame = (_currentFrame + 1) % 4;
			_timeSinceLastFrameChange = 0;
		}
		calculateBoundingBox();

	}

	@Override
	public float getAngle() {
		_angle = (float) Vector2D.Sub(_position2, _position1).GetAngle();
		return super.getAngle();
	}

	@Override
	public Vector2D getPosition() {
		_position.x = (_position1.x + _position2.x) / 2;
		_position.y = (_position1.y + _position2.y) / 2;

		return super.getPosition();
	}

	@Override
	public void render(RenderInstructionBuffer instructionList,
			long timeSinceLastFrame) {
		// TODO Auto-generated method stub
		updateAnimation(timeSinceLastFrame);
		instructionList.AddRenderSimpleSpriteInstruction(getPosition().x,
				getPosition().y, (float) (getAngle() * 180 / Math.PI), Vector2D
						.Sub(_position2, _position1).magnitude() / 128, 1.0f,
				GetCurrentFrameSet(), getCurrentFrame(), GetRenderable());
	}

	@Override
	public CollisionModes getCollisionMode() {
		return CollisionModes.BOUNDING_BOX;
	}

	private void calculateBoundingBox() {
		setBoundingSphereRadius(Vector2D.Sub(_position1, _position2)
				.magnitude() / 2);
		_boundingBox.setup(getPosition(), getBoundingSphereRadius(), 2,
				getAngle());
	}

}


text:
Having coached in both Rails Girls and Rails Bridge, I found that quite a few students are confused by all the magic happening behind Rails. This gem aims to make it easier to understand for beginners, especially those who are programming for the first time.

The changes include:

- Instead of loading models through `before_action`, explicitly load in each action instead.
- Do not use `respond_to`, but just assume HTML instead.
- Comment about each action's respective view file path

[Check out how a scaffolded controller looks like here](https://gist.github.com/lulalala/02b9e75a54a96ad20d4f)

## Installation

Add this line to your Rails application's Gemfile:

```ruby
gem 'toy_scaffold'
```

And then execute:

    $ bundle

## Usage

When calling `rails generate scaffold Post`, the toy_scaffold's version will be used automatically.

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

1. Fork it ( https://github.com/[my-github-username]/toy_scaffold/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
<?php include "header.php";
include "subheader.php";
require_once "common/class/user.class.php";
$user=new user();
require_once "common/class/helpdesk.class.php";
require_once "common/class/common.class.php";
$common=new common();

$helpdesk=new helpdesk();
$result=$helpdesk->get_message_by_id($_GET['helpdesk_id']);
$subject=$helpdesk->get_subject_by_id($_GET['helpdesk_id']);
?>

Helpdesk Message

<form name="frmaddcategory" action="helpdesk.php?wtdo=send_message" method="post" onSubmit="if(validateForm(this)) { if(check_amount()) return true; } else return false; ">

		 From Username:

		 +-
		 <?php
		 echo $user->getUserNameFromUserId($_SESSION['foongigs_userid']);
		 ?>

		 Subject:

		 +-
		 <?php
		 echo $subject;
		 ?>

		<?php foreach($result as $message)
		{
		echo '

				Description:'.$message['description'].'
By:
				By:';
				if(is_numeric($message['userid']))
				{
				echo $user->getUserNameFromUserId($message['userid']);
				}
				else
				{
				echo $message['userid'];
				}
				echo '

				   Posted Time:'.$common->fuzzyTime($message['time_stamp']).'

';
	}
	?>

<a href="javascript: loadPage('/ajax/helpdesk_new_request.php?helpdesk_id=<?php echo $_GET['helpdesk_id'];?>')">Add New Entry

</form>

<?php
include "subfooter.php";
include "footer.php";
?>


text:
<?php require_once(realpath(APPPATH.'views/template/head_left_nav.php')); ?>
<?php $is_logged_in = $this->session->userdata('is_logged_in');?>

                                keyboard_arrow_right
                                keyboard_arrow_down
                                Ticket List

Search Field :

                                                <input class="validate" id="search_tickets" placeholder="Search for (ID ,Service, status, Date Created)" type='search'>

                                                    TicketID
                                                    Applicant Name
                                                    Sales Rep.
                                                    Service
                                                    Status
                                                    Date Created
                                                    Action

<?php require_once(realpath(APPPATH.'views/template/_footer.php')); ?>
<?php require_once(realpath(APPPATH.'views/template/footer.php')); ?>


text:
package com.aspectran.core.activity;

import com.aspectran.core.activity.request.ParameterMap;
import com.aspectran.core.adapter.DefaultRequestAdapter;
import com.aspectran.core.adapter.DefaultResponseAdapter;
import com.aspectran.core.adapter.DefaultSessionAdapter;
import com.aspectran.core.adapter.RequestAdapter;
import com.aspectran.core.adapter.ResponseAdapter;
import com.aspectran.core.adapter.SessionAdapter;
import com.aspectran.core.context.ActivityContext;
import com.aspectran.core.context.rule.type.MethodType;
import com.aspectran.core.util.OutputStringWriter;

import java.io.Writer;
import java.util.Map;

/**
 * CoreActivity could only be executed by the framework, but
 * using this InstantActivity could also be executed by user code.
 */
public class InstantActivity extends CoreActivity {

    private ParameterMap parameterMap;

    private Map<String, Object> attributeMap;

    private volatile boolean performed;

    /**
     * Instantiates a new InstantActivity.
     * @param context the activity context
     */
    public InstantActivity(ActivityContext context) {
        super(context);
    }

    @Override
    public void setSessionAdapter(SessionAdapter sessionAdapter) {
        super.setSessionAdapter(sessionAdapter);
    }

    @Override
    public void setRequestAdapter(RequestAdapter requestAdapter) {
        super.setRequestAdapter(requestAdapter);
    }

    @Override
    public void setResponseAdapter(ResponseAdapter responseAdapter) {
        super.setResponseAdapter(responseAdapter);
    }

    public void setParameterMap(ParameterMap parameterMap) {
        this.parameterMap = parameterMap;
    }

    public void setAttributeMap(Map<String, Object> attributeMap) {
        this.attributeMap = attributeMap;
    }

    @Override
    protected void adapt() throws AdapterException {
        if (getSessionAdapter() == null && getParentActivity() != null) {
            setSessionAdapter(getParentActivity().getSessionAdapter());
        }
        if (getRequestAdapter() == null) {
            MethodType requestMethod = (getTranslet() != null ? getTranslet().getRequestMethod() : null);
            DefaultRequestAdapter requestAdapter = new DefaultRequestAdapter(requestMethod);
            setRequestAdapter(requestAdapter);
        }
        if (getResponseAdapter() == null) {
            Writer writer = new OutputStringWriter();
            DefaultResponseAdapter responseAdapter = new DefaultResponseAdapter(null, writer);
            setResponseAdapter(responseAdapter);
        }

        if (!hasParentActivity() && getSessionAdapter() instanceof DefaultSessionAdapter) {
            ((DefaultSessionAdapter)getSessionAdapter()).getSessionAgent().access();
        }

        super.adapt();
    }

    @Override
    protected void parseRequest() {
        if (parameterMap != null) {
            getRequestAdapter().putAllParameters(parameterMap);
        }
        if (attributeMap != null) {
            getRequestAdapter().putAllAttributes(attributeMap);
        }
    }

    @Override
    public <V> V perform(InstantAction<V> instantAction) throws ActivityPerformException {
        if (performed) {
            throw new ActivityPerformException("Activity has already been performed");
        }
        performed = true;

        return super.perform(instantAction);
    }

    @Override
    protected void release() {
        if (!hasParentActivity() && getSessionAdapter() instanceof DefaultSessionAdapter) {
            ((DefaultSessionAdapter)getSessionAdapter()).getSessionAgent().complete();
        }

        super.release();
    }

}


text:
Trump head ice luge sound + lights

Full writeup here: http://michaelweinberg.org/post/153153112600/trump-head-ice-luge

Final.ino.ino is the script that you want to use.  Realanswer turned out to not quite be the real answer.


text:
import HttpError from "connections/HttpError";// eslint-disable-line
import chai from "chai";// eslint-disable-line import/no-extraneous-dependencies
import Messages from "application/Messages";// eslint-disable-line
describe("HttpError.js", () => {
    // parse = (jqXHR: any, exception: any): Map => {
    it("parse().responseJSON", () => {
        let errorCode = 403;
        let errorMessage = "Custom Error Message";
        let errorXHR = {
            url: "http://localhost:8080/example",
            responseJSON: {
                code: errorCode,
                message: errorMessage
            }
        };

        let expectedError = {
            code: errorCode,
            message: errorMessage
        };

        chai.assert.deepEqual(HttpError.parse(errorXHR), expectedError);

        delete errorXHR.responseJSON.message;

        expectedError.message = Messages.http[errorCode];

        chai.assert.deepEqual(HttpError.parse(errorXHR), expectedError);
    });
    it("parse().responseText", () => {
        let errorCode = 403;
        let errorMessage = "Custom Error Message";
        let errorXHR = {
            url: "http://localhost:8080/example",
            responseText: `{ "code": ${errorCode}, "message": "${errorMessage}" }`
        };

        let expectedError = {
            code: errorCode,
            message: errorMessage
        };

        chai.assert.deepEqual(HttpError.parse(errorXHR), expectedError);

        expectedError.message = Messages.http[errorCode];

        errorXHR = {
            url: "http://localhost:8080/example",
            responseText: `{ "code": ${errorCode} }`
        };

        chai.assert.deepEqual(HttpError.parse(errorXHR), expectedError);
    });

    it("parse().status", () => {
        let errorCode = 403;
        let errorMessage = "Custom Error Message";
        let errorXHR = {
            url: "http://localhost:8080/example",
            status: errorCode
        };

        let expectedError = {
            code: errorCode,
            message: errorMessage
        };

        chai.assert.deepEqual(HttpError.parse(errorXHR, errorMessage), expectedError);

        expectedError.message = Messages.http[errorCode];

        chai.assert.deepEqual(HttpError.parse(errorXHR), expectedError);
        chai.assert.deepEqual(HttpError.parse(errorXHR, "  "), expectedError);
        chai.assert.deepEqual(HttpError.parse(errorXHR, "error"), expectedError);
    });

    it("parse().508", () => {
        let errorCode = 508;

        let errorXHR = {

        };

        let expectedError = {
            code: errorCode,
            message: Messages.http[errorCode]
        };
        chai.assert.deepEqual(HttpError.parse(errorXHR), expectedError);
    });
    it("parse().520", () => {
        let errorCode = 520;

        let errorXHR = {
            url: "http:/localhost:8080/example"
        };

        let expectedError = {
            code: errorCode,
            message: Messages.http[errorCode]
        };
        chai.assert.deepEqual(HttpError.parse(errorXHR, "parsererror"), expectedError);
    });
    it("parse().521", () => {
        let errorCode = 521;

        let errorXHR = {
            url: "http:/localhost:8080/example"
        };

        let expectedError = {
            code: errorCode,
            message: Messages.http[errorCode]
        };
        chai.assert.deepEqual(HttpError.parse(errorXHR, "timeout"), expectedError);
    });
    it("parse().523", () => {
        let errorCode = 523;

        let errorXHR = {
            url: "http:/localhost:8080/example"
        };

        let expectedError = {
            code: errorCode,
            message: Messages.http[errorCode]
        };
        chai.assert.deepEqual(HttpError.parse(errorXHR, "abort"), expectedError);
    });
});


text:
<!DOCTYPE html>
<title>Test "controls" attribute.</title>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script src="media-file.js"></script>
<video controls></video>
<script>
async_test(function(t) {
    var video = document.querySelector("video");
    assert_true(video.controls);

    video.oncanplaythrough = t.step_func_done(function() {
        assert_true(video.controls);
        video.removeAttribute("controls");
        assert_false(video.controls);
        video.controls = true;
        assert_equals(video.getAttribute("controls"), "");
        video.controls = false;
        assert_false(video.controls);
        video.setAttribute("controls", "controls");
        assert_true(video.controls);
    });

    video.src = findMediaFile("video", "content/test");
});
</script>


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Apple Cream Lasagne</title>
      <categories>
        <cat>8</cat>
        <cat>Desserts</cat>
        <cat>Fruits</cat>
        <cat>Italian</cat></categories>
      <yield>8</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>9</qty>
          <unit/></amt>
        <item>Oven ready lasagne noodles</item></ing>
      <ing>
        <amt>
          <qty>1/3</qty>
          <unit>cups</unit></amt>
        <item>Butter</item></ing>
      <ing>
        <amt>
          <qty>6</qty>
          <unit/></amt>
        <item>Granny Smith apples-</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Peeled,cored and sliced.</item></ing>
      <ing>
        <amt>
          <qty>1/3</qty>
          <unit>cups</unit></amt>
        <item>Packed brown sugar</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>cups</unit></amt>
        <item>Toasted, chopped pecans</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>teaspoons</unit></amt>
        <item>Ground cinnamon</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>package</unit></amt>
        <item>Light cream cheese,softened</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit/></amt>
        <item>Egg</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>teaspoon</unit></amt>
        <item>Vanilla</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Whipping cream, whipped</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>cups</unit></amt>
        <item>Fresh breadcrumbs</item></ing>
      <ing>
        <amt>
          <qty>1/4</qty>
          <unit>cups</unit></amt>
        <item>Granulated sugar</item></ing></ingredients>
    <directions>
      <step>  Place noodles in a 11 x 7 inch baking dish, cover with warm water and soak
  20 minutes.  Drain and set aside. Meanwhile, in saucepan, melt 1/4 cup
  butter over medium heat. Add apples, cover and cook 10 minutes, or until
  tender, stirring occasionally.  Remove from heat and stir in 3 tbsp. brown
  sugar, pecans and cinnamon; set aside. Place cream cheese and remaining
  brown sugar in large bowl.  Beat 3 minutes or until light and fluffy. Beat
  in egg and vanilla.  Fold whipped cream into cream cheese mixture in thirds
  and set aside. Melt remaining butter. In small bowl, combine breadcrumbs,
  sugar and melted butter. Spread half of the apple mixture in bottom of same
  baking dish.  Layer with 3 noodles.  Spread with half of cream cheese
  mixture, and layer with 3 more noodles. Spread with remaining apple mixture
  and layer with last three noodles. Top with remaining cream mixture and
  sprinkle with breadcrumb mixture. Bake at 305=F8F for 30 minutes. Let stand
  20 minutes before serving. Makes 8 servings. Source: Primo Family
  Favourites ch.
  Posted to MM-Recipes Digest V3 #282

  Date: Mon, 14 Oct 1996 22:46:41 -0400

  From: Cindy J Hartlin <chartlin@total.net>

</step></directions></recipe></recipeml>


text:
FOUNDATION_EXPORT double XHLaunchAdVersionNumber;
FOUNDATION_EXPORT const unsigned char XHLaunchAdVersionString[];


text:
var test = require("tape");
var cliArgs = require("../");

var optionDefinitions = [
    { name: "one", type: Number }
];

test("type-number: different values", function(t){
    t.deepEqual(
        cliArgs(optionDefinitions).parse([ "--one", "1" ]),
        { one: 1 }
    );
    t.deepEqual(
        cliArgs(optionDefinitions).parse([ "--one" ]),
        { one: null }
    );

    t.end();
});


text:
$script:SPDscUtilModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\..\Modules\SharePointDsc.Util'
Import-Module -Name $script:SPDscUtilModulePath

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.HashTable])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $Url,

        [Parameter(Mandatory = $true)]
        [System.String]
        $Key,

        [Parameter()]
        [System.String]
        $Value,

        [Parameter()]
        [ValidateSet('Present', 'Absent')]
        [System.String]
        $Ensure = 'Present',

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $InstallAccount
    )

    Write-Verbose -Message "Looking for SPSite property '$Key'"

    $result = Invoke-SPDscCommand -Credential $InstallAccount `
        -Arguments @($PSBoundParameters, $MyInvocation.MyCommand.Source) `
        -ScriptBlock {
        $params = $args[0]
        $eventSource = $args[1]

        $spSite = Get-SPSite -Identity $params.Url -ErrorAction SilentlyContinue

        if ($null -eq $spSite)
        {
            $message = "Specified site collection could not be found."
            Add-SPDscEvent -Message $message `
                -EntryType 'Error' `
                -EventID 100 `
                -Source $eventSource
            throw $message
        }

        if ($null -ne $spSite.RootWeb.Properties -and `
                $spSite.RootWeb.Properties.ContainsKey($params.Key) -eq $true)
        {
            $localEnsure = 'Present'
            $currentValue = $spSite.RootWeb.Properties[$params.Key]
        }
        else
        {
            $localEnsure = 'Absent'
            $currentValue = $null
        }

        return @{
            Url    = $params.Url
            Key    = $params.Key
            Value  = $currentValue
            Ensure = $localEnsure
        }
    }
    return $result
}

function Set-TargetResource()
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $Url,

        [Parameter(Mandatory = $true)]
        [System.String]
        $Key,

        [Parameter()]
        [System.String]
        $Value,

        [Parameter()]
        [ValidateSet('Present', 'Absent')]
        [System.String]
        $Ensure = 'Present',

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $InstallAccount
    )

    Write-Verbose -Message "Setting SPSite property '$Key'"

    Invoke-SPDscCommand -Credential $InstallAccount `
        -Arguments @($PSBoundParameters, $MyInvocation.MyCommand.Source) `
        -ScriptBlock {
        $params = $args[0]
        $eventSource = $args[1]

        $spSite = Get-SPSite -Identity $params.Url -ErrorAction SilentlyContinue

        if ($null -eq $spSite)
        {
            $message = "Specified site collection could not be found."
            Add-SPDscEvent -Message $message `
                -EntryType 'Error' `
                -EventID 100 `
                -Source $eventSource
            throw $message
        }

        $spWeb = $spSite.OpenWeb()

        if ($null -ne $spWeb.Properties)
        {
            if ($params.Ensure -eq 'Present')
            {
                Write-Verbose -Message "Adding property '$($params.Key)'='$($params.value)' to SPWeb.Properties"
                $spWeb.Properties[$params.Key] = $params.Value
                $spWeb.Properties.Update()
                $spWeb.Update()
            }
            else
            {
                Write-Verbose -Message "Removing property '$($params.Key)' from SPWeb.AllProperties"
                $spWeb.AllProperties.Remove($params.Key.ToLower())
                $spWeb.Update()
            }
        }
        else
        {
            $message = "Cannot retrieve the property bag. Please check if you have the correct permissions."
            Add-SPDscEvent -Message $message `
                -EntryType 'Error' `
                -EventID 100 `
                -Source $eventSource
            throw $message
        }
    }
}

function Test-TargetResource()
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $Url,

        [Parameter(Mandatory = $true)]
        [System.String]
        $Key,

        [Parameter()]
        [System.String]
        $Value,

        [Parameter()]
        [ValidateSet('Present', 'Absent')]
        [System.String]
        $Ensure = 'Present',

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $InstallAccount
    )

    Write-Verbose -Message "Testing SPSite property '$Key'"

    $CurrentValues = Get-TargetResource @PSBoundParameters

    Write-Verbose -Message "Current Values: $(Convert-SPDscHashtableToString -Hashtable $CurrentValues)"
    Write-Verbose -Message "Target Values: $(Convert-SPDscHashtableToString -Hashtable $PSBoundParameters)"

    if ($Ensure -eq 'Present')
    {
        $result = Test-SPDscParameterState -CurrentValues $CurrentValues `
            -Source $($MyInvocation.MyCommand.Source) `
            -DesiredValues $PSBoundParameters `
            -ValuesToCheck @('Ensure', 'Key', 'Value')
    }
    else
    {
        $result = Test-SPDscParameterState -CurrentValues $CurrentValues `
            -Source $($MyInvocation.MyCommand.Source) `
            -DesiredValues $PSBoundParameters `
            -ValuesToCheck @('Ensure', 'Key')

    }

    Write-Verbose -Message "Test-TargetResource returned $result"

    return $result
}

Export-ModuleMember -Function *-TargetResource


text:
@implementation UIImage (TLCommon)

+ (UIImage *)imageWithName:(NSString *)fileName {
  return [[self class] imageWithName:fileName extension:@"png"];
}

+ (UIImage *)imageWithName:(NSString *)fileName extension:(NSString *)fileExtension {
  NSString *imagePath = [[NSBundle mainBundle] pathForResource:fileName ofType:fileExtension];
  return [[self class] imageWithContentsOfFile:imagePath];
}

// modified from https://devforums.apple.com/message/75921#75921
- (UIImage *)imageScaledToSize:(CGSize)size {
  UIGraphicsBeginImageContext(size);
  [self drawInRect:CGRectZeroWithSize(size)];
  UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return scaledImage;
}

@end


text:
template <typename node_type>
void reverse_binary_tree(node_type *node) {
	if(!node) return;

	reverse_binary_tree(node->left());
	reverse_binary_tree(node->right());

	node_type *tmp = node->left();
	node->left(node->right());
	node->right(tmp);
}

int main() {
	auto balanced = build_balanced_binary_tree();
	print_binary_tree("Before:", balanced.get());
	reverse_binary_tree(balanced.get());
	print_binary_tree("After:", balanced.get());

	auto unbalanced = build_unbalanced_binary_tree();
	print_binary_tree("Before:", unbalanced.get());
	reverse_binary_tree(unbalanced.get());
	print_binary_tree("After:", unbalanced.get());

	return 0;
}


text:
from bda.plone.orders.common import get_order
from bda.plone.payment import Payment
from bda.plone.payment import Payments
from Products.Five import BrowserView
from zope.i18nmessageid import MessageFactory
from zope.interface import Attribute
from zope.interface import Interface

_ = MessageFactory('bda.plone.payment')

class ICashOnDeliverySettings(Interface):

    currency = Attribute(u"Currency of cash on delivery")

    costs = Attribute(u"Costs of cash on delivery as decimal in gross")

class CashOnDelivery(Payment):
    pid = 'cash_on_delivery'

    @property
    def label(self):
        settings = ICashOnDeliverySettings(self.context)
        return _('cash_on_delivery',
                 default=u'Cash on delivery. An extra fee of ${costs} '
                         u'${currency} will be charged on order delivery',
                 mapping={
                     'costs': settings.costs,
                     'currency': settings.currency
                 })

    def init_url(self, uid):
        return '%s/@@cash_on_delivery?uid=%s' % (self.context.absolute_url(), uid)

class DoCashOnDelivery(BrowserView):

    def __call__(self, **kw):
        uid = self.request['uid']
        payment = Payments(self.context).get('cash')
        payment.succeed(self.request, uid)
        url = '%s/@@cash_on_delivery_done?uid=%s' % (
            self.context.absolute_url(), uid)
        self.request.response.redirect(url)

class CashOnDeliveryFinished(BrowserView):

    def id(self):
        uid = self.request.get('uid', None)
        try:
            order = get_order(self.context, uid)
        except ValueError:
            return None
        return order.attrs.get('ordernumber')


text:
jQuery(document).ready(function($) {

	var slideCount = $('#product_slider .product_slide').length;
	var slideWidth = $('#product_slider .product_slide').width();
	var slideHeight = $('#product_slider .product_slide').height();
	var sliderWidth = slideCount * slideWidth;

	 $('#product_slider').css({
		//width : slideWidth,
		 height : slideHeight
	});

	//$('#product_slider .product_slide:last').hide();
	$('.next').hide();
	function moveLeft() {
		$('#product_slider .product_slide:first').animate({
			'left': '-100%'
		});
		$('#product_slider .product_slide:last').animate({
			'left': '0'
		}, 500, function() {
			$('.previous').hide().removeClass("active");
	    	$('.next').show().addClass("active");
		});

	};

	function moveRight() {
		$('#product_slider .product_slide:first').animate({
			'left': '0%'
		});
		$('#product_slider .product_slide:last').animate({
			'left': '-100%'
		}, 500, function() {
			$('.previous').show().addClass("active");
	    	$('.next').hide().removeClass("active");
		});
	};

	$('.previous').click(function() {
		moveLeft();
	});

	$('.next').click(function() {
		moveRight();
	});

	$('.change_color').click(function(){
		$("body").toggleClass("changecolor");
	});

});


text:
def slidingwindowsegment(sequence, create_segment, compute_error, max_error, seq_range=None):
    """
    Return a list of line segments that approximate the sequence.

    The list is computed using the sliding window technique.

    Parameters
    ----------
    sequence : sequence to segment
    create_segment : a function of two arguments (sequence, sequence range) that returns a line segment that approximates the sequence data in the specified range
    compute_error: a function of two argments (sequence, segment) that returns the error from fitting the specified line segment to the sequence data
    max_error: the maximum allowable line segment fitting error

    """
    if not seq_range:
        seq_range = (0,len(sequence)-1)

    start = seq_range[0]
    end = start
    result_segment = create_segment(sequence,(seq_range[0],seq_range[1]))
    while end < seq_range[1]:
        end += 1
        test_segment = create_segment(sequence,(start,end))
        error = compute_error(sequence,test_segment)
        if error <= max_error:
            result_segment = test_segment
        else:
            break

    if end == seq_range[1]:
        return [result_segment]
    else:
        return [result_segment] + slidingwindowsegment(sequence, create_segment, compute_error, max_error, (end-1,seq_range[1]))

def bottomupsegment(sequence, create_segment, compute_error, max_error):
    """
    Return a list of line segments that approximate the sequence.

    The list is computed using the bottom-up technique.

    Parameters
    ----------
    sequence : sequence to segment
    create_segment : a function of two arguments (sequence, sequence range) that returns a line segment that approximates the sequence data in the specified range
    compute_error: a function of two argments (sequence, segment) that returns the error from fitting the specified line segment to the sequence data
    max_error: the maximum allowable line segment fitting error

    """
    segments = [create_segment(sequence,seq_range) for seq_range in zip(range(len(sequence))[:-1],range(len(sequence))[1:])]
    mergesegments = [create_segment(sequence,(seg1[0],seg2[2])) for seg1,seg2 in zip(segments[:-1],segments[1:])]
    mergecosts = [compute_error(sequence,segment) for segment in mergesegments]

    while min(mergecosts) < max_error:
        idx = mergecosts.index(min(mergecosts))
        segments[idx] = mergesegments[idx]
        del segments[idx+1]

        if idx > 0:
            mergesegments[idx-1] = create_segment(sequence,(segments[idx-1][0],segments[idx][2]))
            mergecosts[idx-1] = compute_error(sequence,mergesegments[idx-1])

        if idx+1 < len(mergecosts):
            mergesegments[idx+1] = create_segment(sequence,(segments[idx][0],segments[idx+1][2]))
            mergecosts[idx+1] = compute_error(sequence,mergesegments[idx])

        del mergesegments[idx]
        del mergecosts[idx]

    return segments

def topdownsegment(sequence, create_segment, compute_error, max_error, seq_range=None):
    """
    Return a list of line segments that approximate the sequence.

    The list is computed using the bottom-up technique.

    Parameters
    ----------
    sequence : sequence to segment
    create_segment : a function of two arguments (sequence, sequence range) that returns a line segment that approximates the sequence data in the specified range
    compute_error: a function of two argments (sequence, segment) that returns the error from fitting the specified line segment to the sequence data
    max_error: the maximum allowable line segment fitting error

    """
    if not seq_range:
        seq_range = (0,len(sequence)-1)

    bestlefterror,bestleftsegment = float('inf'), None
    bestrighterror,bestrightsegment = float('inf'), None
    bestidx = None

    for idx in range(seq_range[0]+1,seq_range[1]):
        segment_left = create_segment(sequence,(seq_range[0],idx))
        error_left = compute_error(sequence,segment_left)
        segment_right = create_segment(sequence,(idx,seq_range[1]))
        error_right = compute_error(sequence, segment_right)
        if error_left + error_right < bestlefterror + bestrighterror:
            bestlefterror, bestrighterror = error_left, error_right
            bestleftsegment, bestrightsegment = segment_left, segment_right
            bestidx = idx

    if bestlefterror <= max_error:
        leftsegs = [bestleftsegment]
    else:
        leftsegs = topdownsegment(sequence, create_segment, compute_error, max_error, (seq_range[0],bestidx))

    if bestrighterror <= max_error:
        rightsegs = [bestrightsegment]
    else:
        rightsegs = topdownsegment(sequence, create_segment, compute_error, max_error, (bestidx,seq_range[1]))

    return leftsegs + rightsegs


text:
'use strict';
const uuid = require('uuid/v4');
const httpProxy = require('http-proxy');
const Proxy = require('./proxy.js');

/**
 * Class representating a reverse proxy for a HTTP server.
 * @extends Proxy
 * @author Thomas Minier
 */
class HttpProxy extends Proxy {
	/**
	 * Constructor
	 * @param {string} serverHost - The host of the server (ex: localhost)
	 * @param {number} serverPort - The port on which the server run
	 * @param {number} proxyPort - The port on which the proxy will be running (the proxy's host will be localhost)
	 * @param {function} collectionConstructor - The constructor used to encapsulate data from dataframes
	 * @param {LazyTransformStream[]} metrics - The list of metrics used by the proxy to process dataframes
	 * @param {TimeMetric|undefined} timeMetric - (optional) The time metric used to record elapsed time
	 */
	constructor (serverHost, serverPort, proxyPort, collectionConstructor, metrics, timeMetric) {
		super(serverHost, serverPort, proxyPort, metrics, timeMetric);
		this.target = {
			port: serverPort,
			host: serverHost
		},
		this.proxy = httpProxy.createServer({
			target: this.target
		});
		this.collectionConstructor = collectionConstructor;
		this.setupHeaders();
		this.connectLazyTransformStreams();
	}

	/**
	 * Setup the headers of every request to embed some informations
	 * @return {void}
	 * @private
	 */
	setupHeaders () {
		if (this.proxy !== null) {
			// on request, stamp headers with an UUID & the query key, and then start the timer
			this.proxy.on('proxyReq', (proxyReq, req) => {
				const id = uuid();
				const origin = req.headers.Origin || 'unknown';
				req.headers['commodore-query-key'] = this.currentKey;
				req.headers['commodore-time-uuid'] = id;
				this.startTimer(id, this.currentKey, origin, this.target);
			});
		}
	}

	/**
	 * Connect metrics to the traffic between the server and the client
	 * @return {void}
	 * @private
	 */
	connectLazyTransformStreams () {
		if (this.proxy !== null) {
			this.proxy.on('proxyRes', (proxyRes, req) => {
				const key = req.headers['commodore-query-key'];
				const id = req.headers['commodore-time-uuid'];
				// apply the metrics on incoming dataframe
				proxyRes.on('data', data => {
					const collection = new this.collectionConstructor(data.toString('utf-8'));
					this.metrics.forEach(metric => metric.push(key, {
						id,
						headers: req.headers,
						origin: req.headers.Origin || 'unknown',
						target: this.target,
						data: collection
					}));
				});

				// flush metrics and apply the time metric if present when the response is fully transmitted
				proxyRes.once('end', () => {
					this.stopTimer(id);
					if(this.timeMetric) {
						this.applyTimeMetric(key, this.timeMetric);
					}
				});
			});
		}
	}
}

module.exports = HttpProxy;


text:
package docker

import (
	"encoding/binary"
	"fmt"
	"github.com/dotcloud/docker/utils"
	"io"
	"log"
	"net"
	"sync"
	"syscall"
	"time"
)

const (
	UDPConnTrackTimeout = 90 * time.Second
	UDPBufSize          = 2048
)

type Proxy interface {
	// Start forwarding traffic back and forth the front and back-end
	// addresses.
	Run()
	// Stop forwarding traffic and close both ends of the Proxy.
	Close()
	// Return the address on which the proxy is listening.
	FrontendAddr() net.Addr
	// Return the proxied address.
	BackendAddr() net.Addr
}

type TCPProxy struct {
	listener     *net.TCPListener
	frontendAddr *net.TCPAddr
	backendAddr  *net.TCPAddr
}

func NewTCPProxy(frontendAddr, backendAddr *net.TCPAddr) (*TCPProxy, error) {
	listener, err := net.ListenTCP("tcp", frontendAddr)
	if err != nil {
		return nil, err
	}
	// If the port in frontendAddr was 0 then ListenTCP will have a picked
	// a port to listen on, hence the call to Addr to get that actual port:
	return &TCPProxy{
		listener:     listener,
		frontendAddr: listener.Addr().(*net.TCPAddr),
		backendAddr:  backendAddr,
	}, nil
}

func (proxy *TCPProxy) clientLoop(client *net.TCPConn, quit chan bool) {
	backend, err := net.DialTCP("tcp", nil, proxy.backendAddr)
	if err != nil {
		log.Printf("Can't forward traffic to backend tcp/%v: %v\n", proxy.backendAddr, err.Error())
		client.Close()
		return
	}

	event := make(chan int64)
	var broker = func(to, from *net.TCPConn) {
		written, err := io.Copy(to, from)
		if err != nil {
			// If the socket we are writing to is shutdown with
			// SHUT_WR, forward it to the other end of the pipe:
			if err, ok := err.(*net.OpError); ok && err.Err == syscall.EPIPE {
				from.CloseWrite()
			}
		}
		to.CloseRead()
		event <- written
	}
	utils.Debugf("Forwarding traffic between tcp/%v and tcp/%v", client.RemoteAddr(), backend.RemoteAddr())
	go broker(client, backend)
	go broker(backend, client)

	var transferred int64 = 0
	for i := 0; i < 2; i++ {
		select {
		case written := <-event:
			transferred += written
		case <-quit:
			// Interrupt the two brokers and "join" them.
			client.Close()
			backend.Close()
			for ; i < 2; i++ {
				transferred += <-event
			}
			goto done
		}
	}
	client.Close()
	backend.Close()
done:
	utils.Debugf("%v bytes transferred between tcp/%v and tcp/%v", transferred, client.RemoteAddr(), backend.RemoteAddr())
}

func (proxy *TCPProxy) Run() {
	quit := make(chan bool)
	defer close(quit)

	utils.Debugf("Starting proxy on tcp/%v for tcp/%v", proxy.frontendAddr, proxy.backendAddr)
	for {
		client, err := proxy.listener.Accept()
		if err != nil {
			if utils.IsClosedError(err) {
				utils.Debugf("Stopping proxy on tcp/%v for tcp/%v (socket was closed)", proxy.frontendAddr, proxy.backendAddr)
			} else {
				utils.Errorf("Stopping proxy on tcp/%v for tcp/%v (%v)", proxy.frontendAddr, proxy.backendAddr, err.Error())
			}
			return
		}
		go proxy.clientLoop(client.(*net.TCPConn), quit)
	}
}

func (proxy *TCPProxy) Close()                 { proxy.listener.Close() }
func (proxy *TCPProxy) FrontendAddr() net.Addr { return proxy.frontendAddr }
func (proxy *TCPProxy) BackendAddr() net.Addr  { return proxy.backendAddr }

// A net.Addr where the IP is split into two fields so you can use it as a key
// in a map:
type connTrackKey struct {
	IPHigh uint64
	IPLow  uint64
	Port   int
}

func newConnTrackKey(addr *net.UDPAddr) *connTrackKey {
	if len(addr.IP) == net.IPv4len {
		return &connTrackKey{
			IPHigh: 0,
			IPLow:  uint64(binary.BigEndian.Uint32(addr.IP)),
			Port:   addr.Port,
		}
	}
	return &connTrackKey{
		IPHigh: binary.BigEndian.Uint64(addr.IP[:8]),
		IPLow:  binary.BigEndian.Uint64(addr.IP[8:]),
		Port:   addr.Port,
	}
}

type connTrackMap map[connTrackKey]*net.UDPConn

type UDPProxy struct {
	listener       *net.UDPConn
	frontendAddr   *net.UDPAddr
	backendAddr    *net.UDPAddr
	connTrackTable connTrackMap
	connTrackLock  sync.Mutex
}

func NewUDPProxy(frontendAddr, backendAddr *net.UDPAddr) (*UDPProxy, error) {
	listener, err := net.ListenUDP("udp", frontendAddr)
	if err != nil {
		return nil, err
	}
	return &UDPProxy{
		listener:       listener,
		frontendAddr:   listener.LocalAddr().(*net.UDPAddr),
		backendAddr:    backendAddr,
		connTrackTable: make(connTrackMap),
	}, nil
}

func (proxy *UDPProxy) replyLoop(proxyConn *net.UDPConn, clientAddr *net.UDPAddr, clientKey *connTrackKey) {
	defer func() {
		proxy.connTrackLock.Lock()
		delete(proxy.connTrackTable, *clientKey)
		proxy.connTrackLock.Unlock()
		utils.Debugf("Done proxying between udp/%v and udp/%v", clientAddr.String(), proxy.backendAddr.String())
		proxyConn.Close()
	}()

	readBuf := make([]byte, UDPBufSize)
	for {
		proxyConn.SetReadDeadline(time.Now().Add(UDPConnTrackTimeout))
	again:
		read, err := proxyConn.Read(readBuf)
		if err != nil {
			if err, ok := err.(*net.OpError); ok && err.Err == syscall.ECONNREFUSED {
				// This will happen if the last write failed
				// (e.g: nothing is actually listening on the
				// proxied port on the container), ignore it
				// and continue until UDPConnTrackTimeout
				// expires:
				goto again
			}
			return
		}
		for i := 0; i != read; {
			written, err := proxy.listener.WriteToUDP(readBuf[i:read], clientAddr)
			if err != nil {
				return
			}
			i += written
			utils.Debugf("Forwarded %v/%v bytes to udp/%v", i, read, clientAddr.String())
		}
	}
}

func (proxy *UDPProxy) Run() {
	readBuf := make([]byte, UDPBufSize)
	utils.Debugf("Starting proxy on udp/%v for udp/%v", proxy.frontendAddr, proxy.backendAddr)
	for {
		read, from, err := proxy.listener.ReadFromUDP(readBuf)
		if err != nil {
			// NOTE: Apparently ReadFrom doesn't return
			// ECONNREFUSED like Read do (see comment in
			// UDPProxy.replyLoop)
			if utils.IsClosedError(err) {
				utils.Debugf("Stopping proxy on udp/%v for udp/%v (socket was closed)", proxy.frontendAddr, proxy.backendAddr)
			} else {
				utils.Errorf("Stopping proxy on udp/%v for udp/%v (%v)", proxy.frontendAddr, proxy.backendAddr, err.Error())
			}
			break
		}

		fromKey := newConnTrackKey(from)
		proxy.connTrackLock.Lock()
		proxyConn, hit := proxy.connTrackTable[*fromKey]
		if !hit {
			proxyConn, err = net.DialUDP("udp", nil, proxy.backendAddr)
			if err != nil {
				log.Printf("Can't proxy a datagram to udp/%s: %v\n", proxy.backendAddr.String(), err)
				continue
			}
			proxy.connTrackTable[*fromKey] = proxyConn
			go proxy.replyLoop(proxyConn, from, fromKey)
		}
		proxy.connTrackLock.Unlock()
		for i := 0; i != read; {
			written, err := proxyConn.Write(readBuf[i:read])
			if err != nil {
				log.Printf("Can't proxy a datagram to udp/%s: %v\n", proxy.backendAddr.String(), err)
				break
			}
			i += written
			utils.Debugf("Forwarded %v/%v bytes to udp/%v", i, read, proxy.backendAddr.String())
		}
	}
}

func (proxy *UDPProxy) Close() {
	proxy.listener.Close()
	proxy.connTrackLock.Lock()
	defer proxy.connTrackLock.Unlock()
	for _, conn := range proxy.connTrackTable {
		conn.Close()
	}
}

func (proxy *UDPProxy) FrontendAddr() net.Addr { return proxy.frontendAddr }
func (proxy *UDPProxy) BackendAddr() net.Addr  { return proxy.backendAddr }

func NewProxy(frontendAddr, backendAddr net.Addr) (Proxy, error) {
	switch frontendAddr.(type) {
	case *net.UDPAddr:
		return NewUDPProxy(frontendAddr.(*net.UDPAddr), backendAddr.(*net.UDPAddr))
	case *net.TCPAddr:
		return NewTCPProxy(frontendAddr.(*net.TCPAddr), backendAddr.(*net.TCPAddr))
	default:
		panic(fmt.Errorf("Unsupported protocol"))
	}
}


text:
package cn.kukool.downloader.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * User: jackfengji
 * Date: 15/6/25
 */
public class NetworkUtil {
    private static final String TAG = "NetworkUtil";
    public static boolean networkAvailable;

    // after ICS, android doesn't allow us to get the proxy, so we do not use it
    public static boolean checkNetwork2(Context context) {
        ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifi = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifi != null && wifi.isConnected() && wifi.isAvailable()) {
            networkAvailable = true;
            return true;
        }

        NetworkInfo mobile = mgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobile != null && mobile.isConnected() && mobile.isAvailable()) {
            networkAvailable = true;
            return true;
        }

        networkAvailable = false;
        return false;
    }

    private static BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (!intent.getAction().equalsIgnoreCase(ConnectivityManager.CONNECTIVITY_ACTION))
                return;

            if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
                Log.debug(TAG, "-----> network changed no connectivity");
                networkAvailable = false;
                return;
            }

            checkNetwork2(context);
        }
    };

    public static void registerNetworkCheck(final Context context) {
        IntentFilter netStateIntentFilter = new IntentFilter();
        netStateIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(receiver, netStateIntentFilter);
        checkNetwork2(context);
    }

    public static void unRegisterNetworkCheck(Context context) {
        if (receiver != null) {
            context.unregisterReceiver(receiver);
        }
    }
}


text:
Function Set-VMProcessorCompatibility {

    param
    (

        [Parameter(Mandatory = $true)]
        [string] $VMClusterFQDN

    )

    cls
    #Get the hosts that belong to the cluster
    $Hosts = Get-SCVMHost | ? {$_.HostCluster -match $VMClusterFQDN}

    Foreach ($vHost in $Hosts) {

        #Get all the VMs on each host that are not enabled for VM Processor Compatibility
        Write-Host "Getting VMs from host $vHost that need to be changed" -ForegroundColor DarkYellow
        $VMs2Change = Get-SCVirtualMachine | ? {$_.HostName -eq $vHost -and $_.LimitCPUForMigration -eq $false}
        #Shutdown the VMs, so we can set processor compatibility
        Foreach ($vm in $VMs2Change) {

            Try {

                If ($vm.StatusString -eq "Stopped") {
                    Write-Host "VM: $vm is currently powered off" -ForegroundColor DarkCyan
                    $status = $false
                }

                If ($vm.StatusString -eq "Missing") {
                    Write-Host "VM: $vm is currently MISSING. Exiting Script. Fix Issue before proceeding" -ForegroundColor Red
                    return

                    If ($vm.StatusString -eq "Running") {
                        Write-Host "VM: $vm is currently powered on" -ForegroundColor DarkCyan
                        Write-Host "Shutting Down VM: $vm" -ForegroundColor Cyan
                        $vm | Use-SCShutdownVM | Out-Null
                        $status = $true
                    }

                }

                If ($vm.StatusString -eq "Update Failed") {
                    Write-Host "VM: $vm is currently in a Failed State. Exiting Script. Fix Issue before proceeding" -ForegroundColor Red
                    return
                }

                If ($vm.StatusString -eq "Running") {
                    Write-Host "VM: $vm is currently powered on" -ForegroundColor DarkCyan
                    Write-Host "Shutting Down VM: $vm" -ForegroundColor Cyan
                    $vm | Use-SCShutdownVM | Out-Null
                    $status = $true
                }

            }

            Catch {

                Write-Host "ERROR! Error in Shutting down $vm." -ForegroundColor Red

            }

            #now, lets go ahead and set the VM processor Compatibility
            Write-Host "Limiting CPU for Migration: $vm" -ForegroundColor Cyan

            Try {
                Set-SCVirtualMachine -VM $vm.Name -CPULimitForMigration $true | Out-Null
            }
            Catch {
                Write-Host "There was a problem setting CPULimitForMigration on VM: $VM"
            }
            #If VM was previously on, let's turn it on. If not, we'll keep it off.
            Write-Host "Starting VM: $vm" -ForegroundColor Green
            Write-Host " "
            if ($status -eq $true) {
                $VM | Start-SCVirtualMachine | Out-Null
                $VM | Read-SCVirtualMachine | Out-Null
            }

        }
    }

}


text:
    <button class="btn dtn-default" ng-click="clkRegister()">Click here to register</button>

    Email address
    <input type="email" class="form-control" id="newUserEmail" ng-model="newUser.email"placeholder="Email address">

    Password
    <input type="password" class="form-control" id="newUserPassword" ng-model="newUser.password"placeholder="password">

    Confirm Password
    <input type="password" class="form-control" id="newUserConfirmPW" ng-model="newUser.confirmPW"placeholder="confirm password">

    First Name
    <input type="text" class="form-control" id="newUserFirstName" ng-model="newUser.firstName"placeholder="First Name">

    Last Name
    <input type="text" class="form-control" id="newUserLastName" ng-model="newUser.lastName"placeholder="Last Name">

    <button ng-click="registerUser()">Register
                </button>

        need to add in details such as organisation etc.
        should document what a complete profile looks like, but what we have above will do for now!


text:
const std::vector<unsigned int> & PolygonalGeometry::indices() const
{
    return m_indices;
}

void PolygonalGeometry::setIndices(const std::vector<unsigned int> & indices)
{
    m_indices = indices;
}

void PolygonalGeometry::setIndices(std::vector<unsigned int> && indices)
{
    m_indices = std::move(indices);
}

const std::vector<glm::vec3> & PolygonalGeometry::vertices() const
{
    return m_vertices;
}

void PolygonalGeometry::setVertices(const std::vector<glm::vec3> & vertices)
{
    m_vertices = vertices;
}

void PolygonalGeometry::setVertices(std::vector<glm::vec3> && vertices)
{
    m_vertices = std::move(vertices);
}

bool PolygonalGeometry::hasNormals() const
{
    return !m_normals.empty();
}

const std::vector<glm::vec3> & PolygonalGeometry::normals() const
{
    return m_normals;
}

void PolygonalGeometry::setNormals(const std::vector<glm::vec3> & normals)
{
    m_normals = normals;
}

void PolygonalGeometry::setNormals(std::vector<glm::vec3> && normals)
{
    m_normals = std::move(normals);
}


text:
package net.pagejects.core.annotation;

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

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * TODO describe
 *
 * @author Andrey Paslavsky
 * @since 0.1
 */
@PublicAPI
@Documented
@UserAction
@Retention(RUNTIME) @Target(METHOD)
public @interface FillForm {}


text:
import logging
from bson.errors import InvalidId
from django.http import JsonResponse, HttpResponseNotFound, HttpResponseBadRequest, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from api.models import db_model
from bson import ObjectId
from api.models.auth import RequireLogin
from api.models import rule_model
import json
from datetime import datetime

logger = logging.getLogger(__name__)

@csrf_exempt
def rest(request, *pargs, **kwargs):
    """
    Calls python function corresponding with HTTP METHOD name.
    Calls with incomplete arguments will return HTTP 400
    """
    if request.method == 'GET':
        rest_function = get
    elif request.method == 'POST':
        rest_function = post
    elif request.method == 'PUT':
        rest_function = put
    elif request.method == 'DELETE':
        rest_function = delete
    else:
        return JsonResponse({"error": "HTTP METHOD UNKNOWN"})

    try:
        return rest_function(request, *pargs, **kwargs)
    except TypeError:
        return HttpResponseBadRequest("argument mismatch")

@RequireLogin()
def get(request, rule_id=None):
    """
    Retrieve rule based on rule_id.
    """
    if rule_id is None:
        return get_all_rules()
    dbc = db_model.connect()
    try:
        rule = dbc.rule.find_one({"_id": ObjectId(rule_id)})
    except InvalidId:
        return HttpResponseNotFound()
    if rule is None:
        return HttpResponseNotFound()
    else:
        rule['id'] = str(rule.pop('_id'))
        return JsonResponse(rule)

def get_all_rules():
    """
    Retrieve all rules.
    """
    dbc = db_model.connect()
    rules = [r for r in dbc.rule.find()]
    for rule in rules:
        rule['id'] = str(rule.pop('_id'))
    return JsonResponse({"rules": rules})

@RequireLogin()
def post(request):
    """
    Create new rule.
    """

    try:
        new = json.loads(request.body)
    except ValueError:
        return HttpResponseBadRequest("invalid JSON")

    rule = rule_model.validate(new)
    if rule is None:
        return HttpResponseBadRequest("invalid rule")
    else:
        dbc = db_model.connect()
        rule['createdAt'] = datetime.isoformat(datetime.now())
        rule['updatedAt'] = datetime.isoformat(datetime.now())
        rule_id = str(dbc.rule.save(rule))
        r = JsonResponse({"id": rule_id})
        r['location'] = "/api/rule/%s" % rule_id
        logger.info("rule '%s' created by '%s'" % (rule_id, request.user['username']))
        return r

@RequireLogin()
def put(request, rule_id):
    """
    Update existing rule based on rule_id.
    """
    try:
        in_json = json.loads(request.body)
    except ValueError:
        return HttpResponseBadRequest("invalid JSON")

    dbc = db_model.connect()
    try:
        rule = dbc.rule.find_one({"_id": ObjectId(rule_id)})
    except InvalidId:
        return HttpResponseNotFound()
    if rule is None:
        return HttpResponseNotFound()
    else:
        in_json['createdAt'] = rule['createdAt']
        rule = rule_model.validate(in_json)
        if rule is None:
            return HttpResponseBadRequest("invalid rule")
        else:

            rule['_id'] = ObjectId(rule_id)
            rule['updatedAt'] = datetime.isoformat(datetime.now())
            dbc.rule.save(rule)
            r = JsonResponse({"id": rule_id})
            r['location'] = "/api/rule/%s" % rule_id
            logger.info("rule '%s' updated by '%s'" % (rule_id, request.user['username']))
            return r

@RequireLogin()
def delete(request, rule_id):
    """
    Delete rule based on rule_id.
    """
    dbc = db_model.connect()
    try:
        rule = dbc.rule.find_one({'_id': ObjectId(rule_id)})
    except InvalidId:
        return HttpResponseNotFound()
    if rule is None:
        return HttpResponseNotFound()
    else:
        dbc.rule.remove({"_id": ObjectId(rule_id)})
        logger.info("rule '%s' deleted by '%s'" % (rule_id, request.user['username']))
        return HttpResponse()


text:
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;

fn vbroadcastf64x2_1() {
    run_test(&Instruction { mnemonic: Mnemonic::VBROADCASTF64X2, operand1: Some(Direct(YMM1)), operand2: Some(IndirectScaledDisplaced(EAX, Four, 1208633944, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 242, 253, 169, 26, 12, 133, 88, 74, 10, 72], OperandSize::Dword)
}

fn vbroadcastf64x2_2() {
    run_test(&Instruction { mnemonic: Mnemonic::VBROADCASTF64X2, operand1: Some(Direct(YMM0)), operand2: Some(IndirectScaledIndexed(RAX, RDI, Four, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 242, 253, 170, 26, 4, 184], OperandSize::Qword)
}


text:
<?php

	/*
	Created by Open Fibers
	25'O Clock Inc.
	Sep 9 2012
	 */

	namespace PHP_TOT_OTAServer;

	error_reporting( E_ALL );
	ini_set( 'display_errors', 'on' );

	require_once 'Classes/TOTClasses/unzip.php';
	require_once 'Classes/TOTClasses/HandleInfoPlistInPayload.php';
	require_once 'Classes/TOTClasses/FileSystemHelper.php';
	require_once 'Classes/TOTClasses/GenManifest.php';
	require_once 'Classes/TOTClasses/XMLHelper.php';

	require_once 'Classes/ApkParser/ApkParser.php';

/*
* $tempFile : handle of uploaded temp file
* return value : is temp file available
*/
	function isTempFileAvailable($tempFile)
	{
		$isFileAvailabel = false;
		echo "
";
		if (($_FILES["file"]["type"] != "application/octet-stream"))//file is not an ipa
		{
			echo "File is not an ipa\n";
		}
		else if ($_FILES["file"]["size"] > 1024 * 1024 * 800)//ipa file size limit to 800M
		{
			echo "File should not be larger than 800M\n";
		}
		else if ($_FILES["file"]["error"] > 0)//上传失败
		{
    		echo "Return Code: " . $_FILES["file"]["error"] . "\n";
		}
		else//Upload successed
		{
			echo "File Available";
			$isFileAvailabel = true;
		}
		echo "
";
		return $isFileAvailabel;
	}

//Move uploaded ipa file from temp dir to "./Temp/"
/*
* $tempFile : uploaded ipa file
* return : new fileName of ipa
*/
	function moveTempFileToTempDir($tempFile)
	{
		print("
");

		$uploadDir = 'Temp/';
		CreateDir($uploadDir);

		$filename = "BetaTest.ipa";
		if( strtolower( substr( $tempFile["name"], -4 ) ) == ".apk" )
			$filename = "BetaTest.apk";

		//将其复制到非临时目录
		$tempPath = $tempFile['tmp_name'];
		$uploadPath = $uploadDir . $filename;

		echo "Moving From " . $tempPath . " to " . $uploadPath . "
";
		$isMoveSuccessed = false;
		if (move_uploaded_file($tempPath, $uploadPath))
		{
			print "Upload Successed\n";
			$isMoveSuccessed = true;
		}
		else
		{
			print "Move temp file failed, may be a permission issue\n";
		}
		print("
");
		if ($isMoveSuccessed)
		{
			return $filename;
		}
		return null;
	}

/*
* $tempFile : handle of uploaded temp file
* return value : path of unziped dir of ipa if unzip successed. else null
*/
	function unzipIpaFile($ipaFile)
	{
		unzip($ipaFile, "Temp/");
		return "Temp/";
	}

/*
* $unzipPath : unzipPath of ipa
* return value : path of app dir in unzipPath
*/
	function appPathFromUnzipPath($unzipPath)
	{
		print("
");
		$payloadPath = $unzipPath . "Payload";
		$appPath = null;
		if (file_exists($payloadPath))
		{
			if ($handle = opendir($payloadPath))
			{
				while (false !== ($file = readdir($handle)))
				{
					$isContain = strstr($file, ".app");
					if ($isContain)
					{
						$appPath = $payloadPath . "/" . $file . "/";
					}
				}
				closedir($handle);
			}
		}
		print("
");
		return $appPath;
	}

//如果bundleIdentifer对应的文件夹在Documents中不存在
//或文件夹中不含AppInfo.plist
//或AppInfo.plst中数据不正确
//则删除重建
	function CreateDirForBundleIdentifier($bundleIdentifier)
	{
		$pathForIdentifier = "Documents/" . $bundleIdentifier . "/";
		if (!file_exists($pathForIdentifier))
		{
			CreateDir($pathForIdentifier);
			$xmlArray = array('LastVersion' => "0");
			SaveArrayAsXMLToPath($xmlArray, $pathForIdentifier . "AppInfo.plist");
		}
		else if (file_exists($pathForIdentifier) && !file_exists($pathForIdentifier . "AppInfo.plist"))
		{
			DeleteDir($pathForIdentifier);
			CreateDir($pathForIdentifier);
			$xmlArray = array('LastVersion' => "0");
			SaveArrayAsXMLToPath($xmlArray, $pathForIdentifier . "AppInfo.plist");
		}
		else
		{
			$xmlArray = ArrayFromXMLPath($pathForIdentifier . "AppInfo.plist");
			if (!$xmlArray["LastVersion"])
			{
				DeleteDir($pathForIdentifier);
				CreateDir($pathForIdentifier);
				$xmlArray = array('LastVersion' => "0");
				SaveArrayAsXMLToPath($xmlArray, $pathForIdentifier . "AppInfo.plist");
			}
		}
	}

	function moveTempIpaToIdentifierDir(
		$bundleIdentifier, /*bundle identifier of app */
		$ipaPath, /*path of uploaded ipa file */
		$ipaFileName, /*file name of uploaded ipa file */
		$appPath, /*unziped dir of "*.app/"*/
		$infoArray, /*Info array of app */
		$changeLog /*Change Log of this release */
		)
	{
		//在"Documents/$bundleIdentifier"下新建文件夹$dir,文件夹名为内测版本号
		$identifierXMLPath = "Documents/". $bundleIdentifier . "/AppInfo.plist";
		$identifierInfoArray = ArrayFromXMLPath($identifierXMLPath);
		$betaVersion = $identifierInfoArray['LastVersion'];
		$betaVersion++;
		$identifierInfoArray['LastVersion'] = $betaVersion;
		SaveArrayAsXMLToPath($identifierInfoArray, $identifierXMLPath);
		$dir = "Documents/" . $bundleIdentifier . "/" . $betaVersion . "/";
		CreateDir($dir);

		//将ipaPath的文件移动进$dir
		MoveFile($ipaPath, $dir . $ipaFileName);

		//将$appPath中或Temp中的iTunesArtwork移动进$dir
		if (file_exists($appPath . "iTunesArtwork"))//对于开发者编译的ipa,iTunesArtwork在$appPath中
		{
			MoveFile($appPath . "iTunesArtwork", $dir . "iTunesArtwork.png");
		}
		else if (file_exists("Temp/iTunesArtwork"))//但是对于AppStore下载的ipa,iTunesArtwork在Temp中
		{
			MoveFile("Temp/iTunesArtwork",  $dir . "iTunesArtwork.png");
		}

		date_default_timezone_set('PRC'); //中华人民共和国时间
		$now = strtotime("0 day");
		echo date('F d, Y H:i:s', $now);

		//在$dir中创建VersionInfo.plist
		//储存如下信息
		//Title -- $infoArray["BundleDisplayName"]
		//Bundle Identifier -- $bundleIdentifier
		//Version -- $infoArray["Version"]
		//BetaVersion -- $betaVersion
		//ReleaseDate -- $now
		//ChangeLog -- $changeLog
		$versionInfoArray = array(
			'Title' => $infoArray["BundleDisplayName"],
			'BundleIdentifier' => $bundleIdentifier,
			'Version' => $infoArray["Version"],
			'BetaVersion' => $betaVersion,
			'ReleaseDate' => $now,
			'ChangeLog' => $changeLog
		);
		SaveArrayAsXMLToPath($versionInfoArray, $dir . "VersionInfo.plist");

		// function GenManifestXMLString(
		// $ipaURL,
		// $bundleIdentifier,
		// $bundleVersion,
		// $title)
	}

	function ArrayFromApkPath( $apkPath )
	{
		$returnArray = null;
		if (file_exists($apkPath))
		{
			$apk = new \ApkParser( $apkPath );
			$manifest = $apk->getManifest();

			$versionString     = $manifest->getVersionName();
			$bundleIdentifier  = $manifest->getPackageName();
			$minOSVersion      = $manifest->getMinSdkLevel();

			$ids = explode( ".", $bundleIdentifier );
			$idsCount = count( $ids );
			if( $idsCount >=4 )
				$bundleDisplayName = ucfirst( $ids[$idsCount - 2] ) . ' ' . ucfirst( $ids[$idsCount - 1] );
			else
				$bundleDisplayName = ucfirst( $ids[$idsCount - 1] );

			// print("
");
			// var_dump($plistArray);
			// print("
");

			$returnArray = array();

			$returnArray['Version'] = $versionString;
			$returnArray['BundleIdentifier'] = $bundleIdentifier;
			$returnArray['BundleDisplayName'] = $bundleDisplayName;
			$returnArray['MinOSVersion'] = $minOSVersion;

		}
		return $returnArray;
	}

	function main()
	{
		if (!$_FILES)//$_FILES中没有值,上传失败
		{
			echo "Upload failed
";
			return;
		}

		//change log为空或为"input change log here",上传失败
		$changeLog = $_POST["changelog"];
		if (!$changeLog || $changeLog === "input change log here")
		{
			echo "Change log is required.
";
			return;
		}

		//如果文件不符合要求,上传失败
		$isFileAvailabel = isTempFileAvailable($_FILES["file"]);
		if (!$isFileAvailabel)
		{
			return;
		}

		//上传成功,开始干些正事
		//先新建Documents用来存放ipa,版本信息等
		//再建个Temp文件夹用于暂时保存上传的ipa和解压ipa
		CreateDir("Documents");
		CreateDir("Temp");

		//将临时ipa文件从php临时文件夹移动到相对路径下的Temp文件夹
		$ipaFileName = moveTempFileToTempDir($_FILES["file"]);
		$ipaPath = "Temp/" . $ipaFileName;

		if( strtolower( substr( $_FILES["file"]["name"], -4 ) ) == ".apk" )
		{
			$appPath = $ipaPath;

			$infoArray = ArrayFromApkPath( $ipaPath );
		}
		else
		{
			//解压上传的ipa文件
			$unzipPath = unzipIpaFile($ipaPath);
			$appPath = appPathFromUnzipPath($unzipPath);

			//从解压出的文件中找到Info.plist,解析并找到我们感兴趣的信息放入$infoArray
			$infoArray = ArrayFromInfoPlistPath($appPath . "Info.plist");
		}

		//如果Info.plist解析失败,删掉Temp文件夹返回吧
		if (!$infoArray)
		{
			echo $appPath . "Info.plist" . " parse failed";
			DeleteDir("Temp");
			return;
		}

		//以bundle identifier为名称在Documents下建个文件夹
		CreateDirForBundleIdentifier($infoArray["BundleIdentifier"]);

		//将ipa移动进刚刚创建的文件夹。
		//此方法这么多参数当然不会只移动ipa了,同时移动的还有iTunesArtwork
		//顺便将此次提交的ipa的我们感兴趣的信息存成XML放到刚创建的文件夹
		moveTempIpaToIdentifierDir(
			$infoArray["BundleIdentifier"], //bundle identifier
			$ipaPath, //Temp文件夹中的ipa的路径
			$ipaFileName, //上传的文件名
			$appPath, //解压好的"xxx.app/"的路径,将从此路径读取iTunesArtwork
			$infoArray, //从Info.plist中解析好的数据
			$changeLog //此次提交的change log
		);

		//Remove temp file
		DeleteDir("Temp");
	}
	main();
?>


text:
[![Build Status](https://travis-ci.org/postmodern/gem_home.png)](https://travis-ci.org/postmodern/gem_home)

Changes your `$GEM_HOME`.

## Features

* Updates `$GEM_HOME`, `$GEM_PATH` and `$PATH`.
  * Switches `$GEM_HOME` by pushing and popping gem directories to `$GEM_PATH`.
    This allows the stacking of multiple gem directories.
  * Prepends the new `$GEM_HOME/bin` to `$PATH` so it takes precedence.
* Compartmentalizes gems into `.gem/$ruby_engine/$ruby_version`.
* Plays nicely with [RVM] and [chruby].
* Supports [bash] and [zsh].
* Small (~90 LOC).
* Has tests.

## Synopsis

Change the `$GEM_HOME`:

    $ gem_home /path/to/project

Revert the `$GEM_HOME`:

    $ gem_home -

Using with bundler:

    $ cd padrino-app/
    $ gem_home .
    $ bundle install
    Fetching gem metadata from https://rubygems.org/.........
    Resolving dependencies...
    Using rake 10.3.2
    Using i18n 0.6.11
    Using json 1.8.1
    Using minitest 5.4.0
    Using thread_safe 0.3.4
    Installing tzinfo 1.2.2
    Using activesupport 4.1.4
    Using addressable 2.3.6
    Installing builder 3.2.2
    Using bundler 1.6.2
    Using data_objects 0.10.14
    Using dm-core 1.2.1
    Using dm-aggregates 1.2.0
    Using dm-do-adapter 1.2.0
    Using dm-migrations 1.2.0
    ...
    $ padrino console # no `bundle exec` needed

* Notice how bundler re-used many of the gems from `~/.gem/...` but installed
  missing gems into `$PWD/.gem/...`.

## Install

    wget -O gem_home-0.1.0.tar.gz https://github.com/postmodern/gem_home/archive/v0.1.0.tar.gz
    tar -xzvf gem_home-0.1.0.tar.gz
    cd gem_home-0.1.0/
    sudo make install

### PGP

All releases are [PGP] signed for security. Instructions on how to import my
PGP key can be found on my [blog][1]. To verify that a release was not tampered
with:

    wget https://raw.github.com/postmodern/gem_home/master/pkg/gem_home-0.1.0.tar.gz.asc
    gpg --verify gem_home-0.1.0.tar.gz.asc gem_home-0.1.0.tar.gz

### Homebrew

gem_home can also be installed with [homebrew]:

    brew install --HEAD https://raw.github.com/postmodern/gem_home/master/homebrew/gem_home.rb

## Configuration

Add the following to the `~/.bashrc` or `~/.zshrc` file:

``` bash
source /usr/local/share/gem_home/gem_home.sh
```

### System Wide

If you wish to enable gem_home system-wide, add the following to
`/etc/profile.d/gem_home.sh`:

``` bash
if [ -n "$BASH_VERSION" ] || [ -n "$ZSH_VERSION" ]; then
  source /usr/local/share/gem_home/gem_home.sh
  ...
fi
```

This will prevent `gem_home` from accidentally being loaded by `/bin/sh`, which
is not always the same as `/bin/bash`.

## Uninstall

After removing the `gem_home` configuration:

    $ sudo make uninstall

## Alternatives

* [gs](https://github.com/inkel/gs#readme)
* [gst](https://github.com/tonchis/gst#readme)
* [ohmygems](http://blog.zenspider.com/blog/2012/09/ohmygems.html)
* [renv](https://github.com/fnichol/renv)

[RVM]: https://rvm.io/
[chruby]: https://github.com/postmodern/chruby#readme

[bash]: http://www.gnu.org/software/bash/
[zsh]: http://www.zsh.org/

[PGP]: http://en.wikipedia.org/wiki/Pretty_Good_Privacy
[homebrew]: http://brew.sh/

[1]: http://postmodern.github.com/contact.html#pgp


text:
<?php
$speed = intval(fgets(STDIN));
$area = trim(fgets(STDIN));

function setSpeedLimit($area) : int {
    $limit = 0;
    switch ($area){
        case 'motorway':
            $limit = 130;
            break;
        case 'interstate':
            $limit = 90;
            break;
        case 'city':
            $limit = 50;
            break;
        case 'residential':
            $limit = 20;
            break;
    }
    return $limit;
}

function upSpeedMessage($sp, $lim) {
    $speedDiff = $sp - $lim;
    if ($speedDiff >= 40) {
        return 'reckless driving';
    } elseif ($speedDiff >= 20) {
        return 'excessive speeding';
    } elseif ($speedDiff >= 0) {
        return 'speeding';
    }
    return 'error';
}

echo upSpeedMessage($speed, setSpeedLimit($area));


text:
module Gitlab
  module Email
    module Message
      class RepositoryPush
        attr_reader :author_id, :ref, :action

        include Gitlab::Routing.url_helpers
        include DiffHelper

        delegate :namespace, :name_with_namespace, to: :project, prefix: :project
        delegate :name, to: :author, prefix: :author
        delegate :username, to: :author, prefix: :author

        def initialize(notify, project_id, opts = {})
          raise ArgumentError, 'Missing options: author_id, ref, action' unless
            opts[:author_id] && opts[:ref] && opts[:action]

          @notify = notify
          @project_id = project_id
          @opts = opts.dup

          @author_id = @opts.delete(:author_id)
          @ref = @opts.delete(:ref)
          @action = @opts.delete(:action)
        end

        def project
          @project ||= Project.find(@project_id)
        end

        def author
          @author ||= User.find(@author_id)
        end

        def commits
          @commits ||= (Commit.decorate(compare.commits, project) if compare)
        end

        def diffs
          @diffs ||= (safe_diff_files(compare.diffs(max_files: 30), diff_refs) if compare)
        end

        def diffs_count
          diffs.count if diffs
        end

        def compare
          @opts[:compare]
        end

        def diff_refs
          @opts[:diff_refs]
        end

        def compare_timeout
          diffs.overflow? if diffs
        end

        def reverse_compare?
          @opts[:reverse_compare] || false
        end

        def disable_diffs?
          @opts[:disable_diffs] || false
        end

        def send_from_committer_email?
          @opts[:send_from_committer_email] || false
        end

        def action_name
          @action_name ||=
            case @action
            when :create
              'pushed new'
            when :delete
              'deleted'
            else
              'pushed to'
            end
        end

        def ref_name
          @ref_name ||= Gitlab::Git.ref_name(@ref)
        end

        def ref_type
          @ref_type ||= Gitlab::Git.tag_ref?(@ref) ? 'tag' : 'branch'
        end

        def target_url
          if @action == :push && commits
            if commits.length > 1
              namespace_project_compare_url(project_namespace,
                                            project,
                                            from: Commit.new(compare.base, project),
                                            to:   Commit.new(compare.head, project))
            else
              namespace_project_commit_url(project_namespace,
                                           project, commits.first)
            end
          else
            unless @action == :delete
              namespace_project_tree_url(project_namespace,
                                         project, ref_name)
            end
          end
        end

        def reply_to
          if send_from_committer_email? && @notify.can_send_from_user_email?(author)
            author.email
          else
            Gitlab.config.gitlab.email_reply_to
          end
        end

        def subject
          subject_text = '[Git]'
          subject_text << "[#{project.path_with_namespace}]"
          subject_text << "[#{ref_name}]" if @action == :push
          subject_text << ' '

          if @action == :push && commits
            if commits.length > 1
              subject_text << "Deleted " if reverse_compare?
              subject_text << "#{commits.length} commits: #{commits.first.title}"
            else
              subject_text << "Deleted 1 commit: " if reverse_compare?
              subject_text << commits.first.title
            end
          else
            subject_action = action_name.dup
            subject_action[0] = subject_action[0].capitalize
            subject_text << "#{subject_action} #{ref_type} #{ref_name}"
          end
        end
      end
    end
  end
end


text:
<?php
if (isset($_GET['part']))
    $part = $_GET['part'];
else
    $part = 1;
?>
<!DOCTYPE html>

    <title>DevFest Praha 2013 - Partneri</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/bootstrap-theme.min.css" rel="stylesheet">

    <link href="css/theme.css" rel="stylesheet">

    <img src="images/partners/wall<?php echo $part; ?>.png" class="fullimg">


text:
Home

Book

Part Three: Lisp So(u)rcery

Cross-Platform Desktop Applications

# Cross-Platform Desktop Applications

> "Relevant quote..."
> Source

Discuss Smoke/QT bindings, LTK, McCLIM, SDL + Dormouse, etc.

Favor LTK for developing rapid cross-platform guis.

Develop a cross-platform LTK app for OS X, Windows, and Linux, package it for each OS appropriately.

Note: consider a wrapper around Atom-Shell, for writing rapid web technology based cross-platform applications.

« Previous

Table of Contents

Next »