text:
layout: article
title: Python Requests And Proxies
---

One of [Requests](http://docs.python-requests.org/en/latest/)' most popular
features is its simple proxying support. HTTP as a protocol has very
well-defined semantics for dealing with proxies, and this has lead to
widespread deployment of HTTP proxies.

The vast majority of these proxies are 'transparent': that is, they sit on the
message path and quietly capture HTTP messages before forwarding them on. These
proxies are not a problem for people interacting with HTTP exactly because of
their transparency: you don't need to know anything about them to get your
messages through.

Many proxies however are non-transparent. The most prevalent use of this kind
of HTTP proxy is at the border between a controlled LAN and the wider internet.
In particular, companies and state institutions (e.g. schools) deploy HTTP
proxies _very_ widely. These proxies require explicit configuration on HTTP
clients because all HTTP traffic must pass through them.

The widespread nature of this kind of deployment means that Requests is
essentially obligated to support routing HTTP requests through proxies. Today
I'm going briefly to talk about how this is done, and some particular problems
we've had with the implementation.

### The Good: The API

From the perspective of the Requests user, the configuration of proxies is the
perfect combination of simple and powerful. You simply build a dictionary,
mapping URL schemes to the URL to the proxy. A proxy dictionary could look
like this:

{% highlight python %}
proxies = {'http' : 'http://10.0.0.1:8080',
           'https': 'https://10.0.0.1:4444'}
{% endhighlight %}

This dictionary would then get passed into the standard Requests call:

{% highlight python %}
r = requests.get('http://www.google.com/', proxies=proxies)
{% endhighlight %}

Voila! Your HTTP messages are now being routed through the proxy at `10.0.0.1`.
If you were using a `Session` object then you'd just configure the proxy
dictionary on the `Session`:

{% highlight python %}
s = requests.Session()
s.proxies = proxies
{% endhighlight %}

No big deal, right?

### Also Good: The Requests Internals

Happily, inside Requests everything also looks pretty good. The `proxies`
parameter isn't used until it reaches
[the Transport Adapter](//lukasa.co.uk/2012/12/Writing_A_Transport_Adapter/) at
the bottom of the Requests stack. Here, it is used for three things. The first
two are simple: it can affect the URL that Requests passes to urllib3 and we
can potentially add a `Proxy-Authorization` header (in an ugly hack I'm not
entirely proud of writing). The third thing, however, is the most complex: it
affects what connection pool we use.

This is the the bit that matters most. We take great advantage of the urllib3
connection pools, and obviously all requests that pass through a proxy should
use the same connection pool: after all, they're all going to the same place.
The urllib3 connection pool used for proxies is basically the same as the
standard kind, but it'll put on a few extra headers and does a bit less sanity
checking. No big deal. Another win for code sanity!

### The Bad: HTTPS

So far so good, right? Unfortunately, this is where I tell you that the
idealised view of proxies provided above is only half the story. You see, with
the above steps, HTTP over proxies works like a charm. In fact, Requests has
had functioning proxy support over HTTP for a very long time, and it has almost
never broken. It's one of the stablest parts of the library.

However, proxying and HTTPS is a totally different story. To explain why I'm
going to walk you through a little bit of proxying in Requests.

To do that, we're going to use a tool that I consider to be a vital weapon in
the arsenal of the network programmer: [mitmproxy](http://mitmproxy.org/). The
list of sweet features in mitmproxy is as long as my arm, so I'll just direct
you to their website. In this case, we're going to abuse it as a cheap, easy to
run proxy.

We crack it out, and then get to work. First, let's pass a simple HTTP request
through it:

{% highlight pycon %}
>>> proxies = {'http': 'http://127.0.0.1:8080'}
>>> r = requests.get('http://www.google.com/')
{% endhighlight %}

In the mitmproxy window we can see the request and response come through, no
big deal:

    GET http://www.google.com/
        <- 200 text/html 10.58kB

Awesome, so we know it works. Now, let's try to pass an HTTPS request through
it:

{% highlight pycon %}
>>> proxies = {'https': 'https://127.0.0.1:8080'}
>>> r = requests.get('https://www.google.com/')
requests.exceptions.SSLError: [Errno 1] _ssl.c:503: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
{% endhighlight %}

Uh-oh. What the hell happened there?

The short answer is that everything went to hell in a hand-basket, and to
understand why you need to understand what happens when you try to proxy a
HTTPS request.

#### Proxying HTTPS

The thing about HTTPS is that it relies on secure connections created using
public key cryptography. The keys for the connection are established using
cryptographically signed certificates, which are handed out by certificate
authorities (by 'handed out' I mean 'exorbitantly charged for'). In principle
these authorities (also called 'CA's) should verify the person applying for the
certificate owns the domain in question: in practice if a government comes to
them and asks really nicely, they'll usually hand over a new set of keys.

When your computer establishes an SSL connection, it begins by performing the
SSL handshake, which involves handing certificates over. This certificate is
only valid for a single domain, and _nothing else_. If your User-Agent verifies
SSL certificates (like Requests does by default), your connection will fail if
the machine you're connecting to hands over a certificate that isn't correct
for the domain.

This poses a problem for proxying HTTPS traffic. To send the message on the
proxy needs to know where it's going, but it can't find out without performing
the SSL handshake. It can't do _that_ because it doesn't have the right
certificate for the connection, so the User-Agent will terminate the
connection attempt. (Those _au fait_ with SSL/TLS will note I've simplified a
lot here, but we don't have time for the full discussion.)

The solution has been to use the HTTP CONNECT verb. The CONNECT verb
essentially turns HTTP into a tunnel over which you can send raw TCP data. This
means the proxy can pass your handshake (and then the subsequent encrypted
messages) along without needing to be able to read them.

So what's the problem?

#### Yeah, We Don't Do That

Requests does _not_ support the CONNECT verb. At all. This is because our
underlying HTTP connection library, urllib3, also doesn't support it. There has
been an [open Pull Request](https://github.com/shazow/urllib3/pull/139) on
urllib3 for some time, but it has been essentially abandoned by its original
author and there's not been a sufficient push to get the
[rebased version](https://github.com/shazow/urllib3/pull/170) up to standards.
This is, in my opinion, the single biggest problem Requests has as a library at
the moment.

### How Do I Get HTTPS Working?

It depends. If you want HTTPS proxying without the proxy being able to read it,
I'm afraid you can't use Requests right now. This is unfortunate, but until we
can get the other Pull Request to move forward that's just where we are.

However, if you want to be able to connect to HTTPS URLs and don't care if the
proxy can read it (more fool you!), you can set up your proxies argument like
this:

    proxies = {'https': 'http://127.0.0.1:8080'}

This establishes an HTTP connection to your proxy, which should then establish
an HTTPS connection upstream. This isn't secure, but should work if you
desperately need it. Otherwise, you'll just have to wait until this gets sorted
out. Or take the initiative and sort it out yourself!


text:
'use strict';

const qs = require('querystring');

exports.readPostData = request => {
  return new Promise(resolve => {
    let body = '';

    request.on('data', function (data) {
      body += data;

      // Too much POST data, kill the connection!
      // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
      if (body.length > 1e6) {
        request.connection.destroy();
      }
    });

    request.on('end', () => {
      resolve(qs.parse(body));
    });
  });
}

exports.isPOST = req => req.method == 'POST';

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 15.2.3.8-2-c-1
description: Object.seal - 'O' is a Function object
includes: [runTestCase.js]
---*/

function testcase() {

        var fun = function () { };
        var preCheck = Object.isExtensible(fun);
        Object.seal(fun);

        return preCheck && Object.isSealed(fun);

    }
runTestCase(testcase);


text:
<?xml version="1.0"?>
<sweep runs="800">
	<parameter name="sweepRuns" type="constant" constant_type="int" value="800" />
	<parameter name="evolutionEnabled" type="constant" constant_type="int" value="1" />
	<parameter name="planNumber" type="constant" constant_type="int" value="1" />
	<parameter name="utilityFunction" type="constant" constant_type="java.lang.String" value="LearningSkills" />
	<parameter name="utilityLeftEval" type="constant" constant_type="java.lang.String" value="max" />
	<parameter name="numTasks" type="constant" constant_type="int" value="100" />
	<parameter name="iterationCount" type="constant" constant_type="java.lang.String" value="100" />
	<parameter name="equilibriumDetectionSensitivity" type="constant" constant_type="int" value="7" />
	<parameter name="mutateChances" type="constant" constant_type="int" value="1" />
	<parameter name="taskChoiceAlgorithm" type="constant" constant_type="java.lang.String" value="heterophyly" />
	<parameter name="skillChoiceAlgorithm" type="constant" constant_type="java.lang.String" value="choice" />
	<parameter name="agentCount" type="constant" constant_type="java.lang.String" value="100" />
	<parameter name="experienceCutPoint" type="constant" constant_type="java.lang.Boolean" value="false" />
	<parameter name="experienceDecay" type="constant" constant_type="java.lang.String" value="true false" />
	<parameter name="granularity" type="constant" constant_type="java.lang.Boolean" value="false" />
	<parameter name="granularityObstinacy" type="constant" constant_type="int" value="20" />
	<parameter name="granularityType" type="constant" constant_type="java.lang.String" value="TASKONLY" />
	<parameter name="allowSkillDeath" type="constant" constant_type="java.lang.Boolean" value="true" />
	<parameter name="allwaysChooseTask" type="constant" constant_type="java.lang.Boolean" value="true" />
</sweep>


text:
from django.contrib.gis.db import models
from lingcod.features import register
from lingcod.features.models import PointFeature, LineFeature, PolygonFeature, FeatureCollection
from lingcod.layers.models import PrivateLayerList
from lingcod.features.forms import FeatureForm, SpatialFeatureForm

DESIGNATION_CHOICES = (
    ('R', 'Reserve'),
    ('P', 'Park'),
    ('C', 'Conservation Area')
)

###########################
@register
class Mpa(PolygonFeature):
    designation = models.CharField(max_length=1, choices=DESIGNATION_CHOICES)
    class Options:
        verbose_name = 'Marine Protected Area'
        form = 'mlpa.models.MpaForm'
        manipulators = []

class MpaForm(SpatialFeatureForm):
    class Meta(SpatialFeatureForm.Meta):
        model = Mpa

###########################
@register
class Array(FeatureCollection):
    class Options:
        form = 'mlpa.models.ArrayForm'
        valid_children = ( 'mlpa.models.Mpa', )

class ArrayForm(FeatureForm):
    class Meta(FeatureForm.Meta):
        model = Array

###########################
@register
class Shipwreck(PointFeature):
    incident = models.CharField(max_length=100,default='')
    class Options:
        verbose_name = 'Shipwreck'
        form = 'mlpa.models.ShipwreckForm'

class ShipwreckForm(SpatialFeatureForm):
    class Meta(SpatialFeatureForm.Meta):
        model = Shipwreck

###########################
@register
class Pipeline(LineFeature):
    type = models.CharField(max_length=30,default='')
    diameter = models.FloatField(null=True)
    class Options:
        verbose_name = 'Pipeline'
        form = 'mlpa.models.PipelineForm'

class PipelineForm(SpatialFeatureForm):
    class Meta(SpatialFeatureForm.Meta):
        model = Pipeline

###########################
@register
class Folder(FeatureCollection):
    class Options:
        form = 'mlpa.models.FolderForm'
        valid_children = (
                'mlpa.models.Mpa',
                'mlpa.models.Array',
                'mlpa.models.Pipeline',
                'mlpa.models.Shipwreck',
                'mlpa.models.Folder'
        )

class FolderForm(FeatureForm):
    class Meta(FeatureForm.Meta):
        model = Folder

###########################
@register
class UserKml(PrivateLayerList):
    class Options:
        form = 'mlpa.models.UserKmlForm'

class UserKmlForm(FeatureForm):
    class Meta(FeatureForm.Meta):
        model = UserKml


text:
typedef NS_ENUM(NSUInteger, SCDataObjectArrayOperator) {
    SCDataObjectArrayOperatorAdd,
    SCDataObjectArrayOperatorAddUnique,
    SCDataObjectArrayOperatorRemove,
};

@implementation SCDataObject (ArrayOperators)

- (void)addArrayOfObjects:(NSArray*)array forArrayWithKey:(NSString *)key withCompletion:(nullable SCCompletionBlock)completion {
    [self addArrayOfObjects:array forArrayWithKey:key withCompletion:completion revisionMismatchValidationBlock:nil];
}

- (void)addUniqueArrayOfObjects:(NSArray*)array forArrayWithKey:(NSString *)key withCompletion:(nullable SCCompletionBlock)completion {
    [self addUniqueArrayOfObjects:array forArrayWithKey:key withCompletion:completion revisionMismatchValidationBlock:nil];
}

- (void)removeArrayOfObjects:(NSArray *)array fromArrayWithKey:(NSString *)key withCompletion:(nullable SCCompletionBlock)completion {
    [self removeArrayOfObjects:array fromArrayWithKey:key withCompletion:completion revisionMismatchValidationBlock:nil];
}

- (void)addArrayOfObjects:(NSArray*)array forArrayWithKey:(NSString *)key forSyncano:(Syncano *)syncano withCompletion:(nullable SCCompletionBlock)completion {
    [self addArrayOfObjects:array forArrayWithKey:key forSyncano:syncano withCompletion:completion revisionMismatchValidationBlock:nil];
}

- (void)addUniqueArrayOfObjects:(NSArray*)array forArrayWithKey:(NSString *)key forSyncano:(Syncano *)syncano withCompletion:(nullable SCCompletionBlock)completion {
    [self addUniqueArrayOfObjects:array forArrayWithKey:key forSyncano:syncano withCompletion:completion revisionMismatchValidationBlock:nil];
}

- (void)removeArrayOfObjects:(NSArray *)array fromArrayWithKey:(NSString *)key forSyncano:(Syncano *)syncano withCompletion:(nullable SCCompletionBlock)completion {
    [self removeArrayOfObjects:array fromArrayWithKey:key forSyncano:syncano withCompletion:completion revisionMismatchValidationBlock:nil];
}

- (void)addArrayOfObjects:(NSArray*)array forArrayWithKey:(NSString *)key usingAPIClient:(SCAPIClient *)apiClient withCompletion:(nullable SCCompletionBlock)completion {
    [self addArrayOfObjects:array forArrayWithKey:key usingAPIClient:apiClient withCompletion:completion revisionMismatchValidationBlock:nil];
}

- (void)addUniqueArrayOfObjects:(NSArray*)array forArrayWithKey:(NSString *)key usingAPIClient:(SCAPIClient *)apiClient withCompletion:(nullable SCCompletionBlock)completion {
    [self addUniqueArrayOfObjects:array forArrayWithKey:key usingAPIClient:apiClient withCompletion:completion revisionMismatchValidationBlock:nil];
}

- (void)removeArrayOfObjects:(NSArray *)array fromArrayWithKey:(NSString *)key usingAPIClient:(SCAPIClient *)apiClient withCompletion:(nullable SCCompletionBlock)completion {
    [self removeArrayOfObjects:array fromArrayWithKey:key usingAPIClient:apiClient withCompletion:completion revisionMismatchValidationBlock:nil];
}

- (void)addArrayOfObjects:(NSArray*)array forArrayWithKey:(NSString *)key withCompletion:(nullable SCCompletionBlock)completion revisionMismatchValidationBlock:(nullable SCDataObjectRevisionMismatchCompletionBlock)revisionMismatchBlock {
    [self addArrayOfObjects:array forArrayWithKey:key usingAPIClient:[Syncano sharedAPIClient] withCompletion:completion revisionMismatchValidationBlock:revisionMismatchBlock];
}
- (void)addUniqueArrayOfObjects:(NSArray*)array forArrayWithKey:(NSString *)key withCompletion:(nullable SCCompletionBlock)completion revisionMismatchValidationBlock:(nullable SCDataObjectRevisionMismatchCompletionBlock)revisionMismatchBlock {
    [self addUniqueArrayOfObjects:array forArrayWithKey:key usingAPIClient:[Syncano sharedAPIClient] withCompletion:completion revisionMismatchValidationBlock:revisionMismatchBlock];
}
- (void)removeArrayOfObjects:(NSArray *)array fromArrayWithKey:(NSString *)key withCompletion:(nullable SCCompletionBlock)completion revisionMismatchValidationBlock:(nullable SCDataObjectRevisionMismatchCompletionBlock)revisionMismatchBlock {
    [self removeArrayOfObjects:array fromArrayWithKey:key usingAPIClient:[Syncano sharedAPIClient] withCompletion:completion revisionMismatchValidationBlock:revisionMismatchBlock];
}

- (void)addArrayOfObjects:(NSArray*)array forArrayWithKey:(NSString *)key forSyncano:(Syncano *)syncano withCompletion:(nullable SCCompletionBlock)completion revisionMismatchValidationBlock:(nullable SCDataObjectRevisionMismatchCompletionBlock)revisionMismatchBlock {
    [self addArrayOfObjects:array forArrayWithKey:key usingAPIClient:syncano.apiClient withCompletion:completion revisionMismatchValidationBlock:revisionMismatchBlock];
}
- (void)addUniqueArrayOfObjects:(NSArray*)array forArrayWithKey:(NSString *)key forSyncano:(Syncano *)syncano withCompletion:(nullable SCCompletionBlock)completion revisionMismatchValidationBlock:(nullable SCDataObjectRevisionMismatchCompletionBlock)revisionMismatchBlock {
    [self addUniqueArrayOfObjects:array forArrayWithKey:key usingAPIClient:syncano.apiClient withCompletion:completion revisionMismatchValidationBlock:revisionMismatchBlock];
}
- (void)removeArrayOfObjects:(NSArray *)array fromArrayWithKey:(NSString *)key forSyncano:(Syncano *)syncano withCompletion:(nullable SCCompletionBlock)completion revisionMismatchValidationBlock:(nullable SCDataObjectRevisionMismatchCompletionBlock)revisionMismatchBlock {
    [self removeArrayOfObjects:array fromArrayWithKey:key usingAPIClient:syncano.apiClient withCompletion:completion revisionMismatchValidationBlock:revisionMismatchBlock];
}

- (void)addArrayOfObjects:(NSArray*)array forArrayWithKey:(NSString *)key usingAPIClient:(SCAPIClient *)apiClient withCompletion:(nullable SCCompletionBlock)completion revisionMismatchValidationBlock:(nullable SCDataObjectRevisionMismatchCompletionBlock)revisionMismatchBlock {
    NSError *error = nil;
    NSDictionary* params = [self buildParametersForOperator:SCDataObjectArrayOperatorAdd withArrayOfObjects:array forKey:key withRevisionMismatchCheck:(revisionMismatchBlock != nil) withError:&error];

    if(error) {
        if(completion) {
            completion(error);
        }
        return;
    }

    [self saveArrayForKey:key params:params apiClient:apiClient withCompletion:completion revisionMismatchValidationBlock:revisionMismatchBlock];

}
- (void)addUniqueArrayOfObjects:(NSArray*)array forArrayWithKey:(NSString *)key usingAPIClient:(SCAPIClient *)apiClient withCompletion:(nullable SCCompletionBlock)completion revisionMismatchValidationBlock:(nullable SCDataObjectRevisionMismatchCompletionBlock)revisionMismatchBlock{
    NSError *error = nil;
    NSDictionary* params = [self buildParametersForOperator:SCDataObjectArrayOperatorAddUnique withArrayOfObjects:array forKey:key withRevisionMismatchCheck:(revisionMismatchBlock != nil) withError:&error];

    if(error) {
        if(completion) {
            completion(error);
        }
        return;
    }

    [self saveArrayForKey:key params:params apiClient:apiClient withCompletion:completion revisionMismatchValidationBlock:revisionMismatchBlock];
}
- (void)removeArrayOfObjects:(NSArray *)array fromArrayWithKey:(NSString *)key usingAPIClient:(SCAPIClient *)apiClient withCompletion:(nullable SCCompletionBlock)completion revisionMismatchValidationBlock:(nullable SCDataObjectRevisionMismatchCompletionBlock)revisionMismatchBlock {
    NSError *error = nil;
    NSDictionary* params = [self buildParametersForOperator:SCDataObjectArrayOperatorRemove withArrayOfObjects:array forKey:key withRevisionMismatchCheck:(revisionMismatchBlock != nil) withError:&error];

    if(error) {
        if(completion) {
            completion(error);
        }
        return;
    }

    [self saveArrayForKey:key params:params apiClient:apiClient withCompletion:completion revisionMismatchValidationBlock:revisionMismatchBlock];
}

- (NSDictionary *)buildParametersForOperator:(SCDataObjectArrayOperator)operator withArrayOfObjects:(NSArray *)array forKey:(NSString *)key withRevisionMismatchCheck:(BOOL)revisionMismatchCheck withError:(NSError **)error {
    __block NSError* internalError;
    NSMutableDictionary* params = [NSMutableDictionary dictionaryWithCapacity:1];
    if ([[[self class] propertyKeys] containsObject:key]) {
        params[key] = @{[self stringRepresentationForArrayOperator:operator]:array};
    } else {
        internalError = [NSError errorForUnknownProperty:key];
    }
    if (revisionMismatchCheck && self.revision) {
        params[kExpectedRevisionRequestParam] = self.revision;
    }

    if(internalError) {
        *error = internalError;
        return nil;
    }
    return params;
}

- (NSString *)stringRepresentationForArrayOperator:(SCDataObjectArrayOperator)operator {
    switch (operator) {
        case SCDataObjectArrayOperatorAdd:
            return @"_add";
            break;
        case SCDataObjectArrayOperatorAddUnique:
            return @"_addunique";
            break;
        case SCDataObjectArrayOperatorRemove:
            return @"_remove";
            break;
        default:
            return nil;
            break;
    }
}

- (void)fillKey:(NSString *)key fromResponseObject:(id)responseObject {
    [self setValue:[responseObject valueForKey:key] forKey:key];
    self.updated_at = [[SCConstants SCDataObjectDatesTransformer] transformedValue:responseObject[@"updated_at"]];
    self.revision = responseObject[@"revision"];
}

- (void)saveArrayForKey:(NSString *)key params:(NSDictionary *)params apiClient:(SCAPIClient *)apiClient withCompletion:(nullable SCCompletionBlock)completion revisionMismatchValidationBlock:(nullable SCDataObjectRevisionMismatchCompletionBlock)revisionMismatchBlock {
    typeof(self) __weak selfWeak = self;
    [self saveObjectAfterManipulationOfKey:key params:params apiClient:apiClient withCompletion:^(NSString * _Nonnull key, id  _Nullable responseObject, NSError * _Nullable error) {
        [selfWeak fillKey:key fromResponseObject:responseObject];
        if (completion) {
            completion(error);
        }
    } revisionMismatchValidationBlock:revisionMismatchBlock];
}
@end


text:
std::string execute_js(std::string scriptString)
{
	std::string returnResult;

	// Create a new context.
	JSGlobalContextRef context = JSGlobalContextCreate(NULL);

	// Create a string containing the JavaScript source code.
	JSStringRef source = JSStringCreateWithUTF8CString(scriptString.c_str());

	// Run the script source to get the result.
	JSValueRef result = JSEvaluateScript(context, source, NULL, NULL, 1, NULL);

	// Convert the result to an UTF8 string.
	JSStringRef string = JSValueToStringCopy(context, result, NULL);
	size_t cStrSize = JSStringGetMaximumUTF8CStringSize(string);
	returnResult.reserve(cStrSize);

	JSStringGetUTF8CString(string, &returnResult[0], cStrSize);
	JSStringRelease(string);

	// Dispose of the string and context
	JSStringRelease(source);
	JSGlobalContextRelease(context);

	// Return the resulting string
	return returnResult;
}


text:
title: Building APKs for Android emulators and devices
---

The default file format used when building Android apps with EAS Build is an [Android App Bundle](https://developer.android.com/platform/technology/app-bundle) (AAB / **.aab**). This format is optimized for distributing to the Google Play Store, but AABs can't be installed directly to your device. To install a build directly to your Android device or emulator, you need to build an [Android Package](https://en.wikipedia.org/wiki/Android_application_package) (APK / **.apk**) instead.

## Configuring a profile to build APKs

### Managed projects

By default, EAS Build produces Android App Bundle, you can change it by:

- setting `buildType` to `apk`
- setting `developmentClient` to true
- setting `gradleCommand` to `:app:assembleRelease`, `:app:assembleDebug` or any other gradle command that produces APK

```json
{
  "build": {
    "preview": {
      "android": {
        "buildType": "apk"
      }
    },
    "preview2": {
      "android": {
        "gradleCommand": ":app:assembleRelease"
      }
    },
    "preview3": {
      "developmentClient": true
    },
    "production": {}
  }
}
```

Now, to run your build run `eas build -p android --profile preview`. Remember that you can name the profile whatever you like; we named the profile "preview", but you could call it "local" or "simulator", whatever makes most sense for you.

## Installing your build

### Emulator ("Virtual device")

> If you haven't installed or run an Android emulator before, follow the [Android Studio emulator guide](/workflow/android-studio-emulator.md) before proceeding.

- Once your build is completed, download the APK from the build details page or the link provided when `eas build` is done.
- Open up your emulator.
- Drag the APK file into the emulator.
- The app will be installed in a few seconds. When it's complete, navigate to the app launcher, find the app icon and open it.
- You can share this build, it will run on any Android emulator or device.

### Physical device

#### Download directly to the device

- Once your build is completed, copy the URL to the APK from the build details page or the link provided when `eas build` is done.
- Send that URL to your device. Maybe by email? Up to you.
- Open the URL on your device, install the APK and run it.

#### Install with `adb`

- [Install adb](https://developer.android.com/studio/command-line/adb) if you don't have it installed already.
- Connect your device to your computer and [enable adb debugging on your device](https://developer.android.com/studio/command-line/adb#Enabling) if you haven't already.
- Once your build is completed, download the APK from the build details page or the link provided when `eas build` is done.
- Run `adb install path/to/the/file.apk`.
- Run the app on your device.


text:
<!DOCTYPE HTML>

    <link href="text-align-last.css" rel="stylesheet" type="text/css">

text-align-last: center

This test checks that text-align-last property works properly.

The last line of each case should be aligned to center side.

LTR align is start align-last is center.

LTR align is end align-last is center.

LTR align is right align-last is center.

LTR align is left align-last is center.

RTL align is start align-last is center.

RTL align is end align-last is center.


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

describe OrdersController do
  before(:each) do
    Variant.stub!(:find).with(any_args).and_return(@variant = mock_model(Variant, :price => 10, :on_hand => 50))
    controller.stub!(:find_order).and_return(@order = Order.new)
  end

  describe "create" do
    # it "should add the variant to the order" do
    #   @order.should_receive(:add_variant).with(@variant)
    #   post :create, :id => "123"
    # end

    # it "should not set the state" do
    #   @order.should_not_receive(:state=)
    #   post :create, :id => "123", :order => {:state => "paid"}
    # end
  end

  describe "update" do
    %w{ship_amount tax_amount item_total total user number ip_address checkout_complete state}.each do |attribute|
      it "should not set #{attribute} with mass assignment" do
        #@order.send(attribute).should_not == "naughty"
        @order.should_not_receive("#{attribute}=".to_sym).with("naughty")
        put :update, "id" => "123", "order" => {attribute => "naughty"}
      end
    end
  end
end


text:
module AWS
  module Core

    # = Response
    #
    # Each Service has a Client class.  There is one method per service
    # operation defined on the client.  These methods all return a {Response}
    # object.
    #
    # In addition to the response data, these responses provide metadata
    # about the HTTP request made and the HTTP response received.
    #
    # == Response Data
    #
    # You can access the response data for a client request using the {#data}
    # method or the {#[]} method.  Response data is a hash and {#[]} is
    # a shortcut for accessing this hash.
    #
    #   # make a request to describe one instance
    #   ec2 = AWS::EC2.new
    #   response = ec2.client.describe_instances(:instance_ids => ['i-12345678'])
    #
    #   # find the instance in the response data (2 ways to get the data)
    #   instance = response[:reservation_set].first[:instance_set].first
    #   instance = response.data[:reservation_set].first[:instance_set].first
    #
    #   instance[:status] #=> 'running'
    #
    # == Response Metadata
    #
    # In addition to the response data, there is additional information
    # available with the response, including:
    #
    # * {#request_type} - the name of the client request method
    # * {#request_options} - the hash of options passed to the client method
    # * {#http_request} - The HTTP request made
    # * {#http_response} - the HTTP response received
    #
    # Given the example and response object from above:
    #
    #   response.request_type #=> :describe_instances
    #   response.request_options #=> { :instance_ids => ['i-12345678'] }
    #   response.http_request #=> #<AWS::Core::Http::Request>
    #   response.http_response #=> #<AWS::Core::Http::Response>
    #
    class Response

      include AsyncHandle

      # @return [Hash] Returns the response data as a hash.
      attr_accessor :data

      # @return [Symbol] The name of the client request method that
      #   returned this response.
      attr_accessor :request_type

      # @return [Hash] Returns the hash of options passed to the client
      #   request method that generated this response.
      attr_accessor :request_options

      # @return [Core::Http::Request]
      attr_accessor :http_request

      # @return [Core::Http::Response]
      attr_accessor :http_response

      # @return [Boolean] true if the response was generated from a
      #   another cached response.
      attr_accessor :cached

      alias_method :cached?, :cached

      # @return [AWS::Error,nil] Returns nil unless the request failed.
      #   Normally this will be nil unless you are using the Asynchronous
      #   interface.
      attr_accessor :error

      # @return [Integer] Returns the number of times the request
      #   was retried.
      attr_accessor :retry_count

      # @return [Float] The total number of seconds taken to make the
      #   request and return the response.
      attr_accessor :duration

      # @param [Http::Request] http_request
      # @param [Http::Response] http_response
      def initialize http_request = nil, http_response = nil, &block
        @http_request = http_request
        @http_response = http_response
        @request_builder = block
        @data = {}
        @retry_count = 0
        @duration = 0
        build_request if @request_builder && !http_request
      end

      # Provides access to the response data.  This is a short-cut
      # for calling +response.data[key]+.
      #
      # @param [Symbol,String] key
      # @return [Hash,nil]
      def [] key
        data[key]
      end

      # @return [Boolean] Returns true if there is no response error.
      def successful?
        error.nil?
      end

      # @return [Boolean] Returns true if the http request was throttled
      #   by AWS.
      def throttled?
        if !successful? and http_response.body
          error = XML::Parser.new.parse(http_response.body)
          error = error[:error] if error[:error]
          error[:code] == "Throttling"
        else
          false
        end
      end

      # @return [Boolean] Returns +true+ if the http request failed due to
      #   a networking issue.
      def network_error?
        http_response.network_error?
      end

      # @return [String]
      # @private
      def inspect
        data.inspect
      end

      # @return [String]
      # @private
      def cache_key
        [
          http_request.access_key_id,
          http_request.host,
          request_type,
          serialized_options
        ].join(":")
      end

      # Rebuilds the HTTP request using the block passed to the initializer.
      # This is primarily used by the client when a request must be retried
      # (throttling, server errors, socket errors, etc).
      # @private
      def rebuild_request
        build_request
        @http_request.body_stream.rewind if @http_request.body_stream
      end

      # @return [Boolean] Returns +false+ if it is not safe to retry a
      #   request.  This happens when the http request body is an IO
      #   object that can not be rewound and re-streamed.
      def safe_to_retry?
        @http_request.body_stream.nil? or
        @http_request.body_stream.respond_to?(:rewind)
      end

      protected

      def build_request
        @http_request = @request_builder.call
      end

      # @note The prefered method to get as response data is to use {#[]}.
      #
      # This provides a backwards-compat layer to the old response objects
      # where each response value had a method extended onto this object.
      # Now all response data is accessible as a hash.
      #
      # @see #[]
      # @see #data
      #
      def method_missing *args, &block
        Core::Data.new(data).send(*args, &block)
      end

      def serialized_options
        serialize_options_hash(request_options)
      end

      def serialize_options_hash(hash)
        "(" + hash.keys.sort_by(&:to_s).map do |key|
          "#{key}=#{serialize_options_value(hash[key])}"
        end.join(" ") + ")"
      end

      def serialize_options_value(value)
        case value
        when Hash  then serialize_options_hash(value)
        when Array then serialize_options_array(value)
        else value.inspect
        end
      end

      def serialize_options_array array
        "[" + array.map{|v| serialize_options_value(v) }.join(" ") + "]"
      end

    end
  end
end


text:
import sys

from numpy import *
from PyQt4 import QtGui
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg \
    import FigureCanvasQTAgg as FigureCanvas

import src.quadrature as quad
from gui.main_window import Ui_main_window
from src.utils import MethodNames, parse_function

class QuadMethod:
    """Holds a Quadrature object, references to the inputs
    used to change it, and the name of the object's class,
    and is responsible for updating the object.

    Attributes
    ----------
    quadrature: the Quadrature object
    method: a reference to the class constructor, used
        to create a new value for quadrature
    lx_input: QLineEdit used to define the lower-x bound (a)
    rx_input: QLineEdit used to define the upper-x bound (b)
    n_input: QLineEdit used to define n, the number of polygons
        to use in quadrature
    def_n: the default n value that the Quadrature object should use
    max_n: the maximum n value that the Quadrature object can use
    needs_even: boolean representing whether the Quadrature object
        can only use even values of n

    Notes
    -----
    The update function is actually called by QuadUpdater, which holds
    references to numerous QuadMethods
    """
    def __init__(self, ui, class_name, n_input,
                 def_n=20, max_n=5000000, needs_even=False):
        """Creates a new QuadMethod

        Parameters
        ----------
        ui: the application's UI
        class_name: the name of the quadrature method's class
        n_input: the QLineEdit used to input the 'n' value for
            this method
        def_n: the default value for n that the quadrature method
            should use
        max_n: the maximum value for n that the quadrature method
            can use
        needs_even: boolean representing whether the Quadrature object
            can only use even values of n

        Returns
        -------
        a new QuadMethod
        """
        self.lx_input = ui.x_Left_Line_Edit
        self.rx_input = ui.x_Right_Line_Edit
        self.n_input = n_input
        self.class_name = class_name
        self.def_n = def_n
        self.max_n = max_n
        self.needs_even = needs_even

        # Grab the class and constructor for this
        # QuadMethod from quadrature.py
        self.method = getattr(quad, class_name)

        # Call update for the first time to initialize values
        self.update()

    def update(self):
        """Updates the Quadrature object for this QuadMethod."""
        # Parse lx
        try:
            lx = float(self.lx_input.text())
        except ValueError:
            # If the input is invalid, set the default rx value
            lx = -7.0
            self.lx_input.setText('-7.0')

        # Parse rx
        try:
            rx = float(self.rx_input.text())
        except ValueError:
            # If the input is invalid, set the default rx value
            rx = 7.0
            self.rx_input.setText('7.0')

        # Parse n
        try:
            n = int(self.n_input.text())
        except ValueError:
            # If the input is valid, set the default n value
            n = self.def_n
            self.n_input.setText(str(self.def_n))

        # Certain methods will need special validation for n
        # If n > the max value it can handle, we set the value
        # to the method's maximum value
        if n > self.max_n:
            n = self.max_n
            self.n_input.setText(str(self.max_n))

        # Ensure n >= 1
        if n < 1:
            n = 1
            self.n_input.setText(str(1))

        # If the method needs an even n and if n is odd,
        # set the default n
        if self.needs_even and n % 2 == 1:
            n = n - 1
            self.n_input.setText(str(n))

        # Finally, we create the Quadrature object
        # using the parsed values and the reference to the
        # class constructor
        self.quadrature = self.method(lx, rx, n)

class QuadUpdater:
    """Holds a dictionary of QuadMethods and is responsible
    for updating them

    Attributes
    ----------
    quad_methods: a dictionary of QuadMethods
    quad_check_buttons: a list of tuples matching method names
        and matching checkboxes
    active_quad_method: the current quadrature method being graphed
    result: QLabel used to display the result of the integration
    error: QLabel used to display the error of the integration
    method_group: QButtonGroup used to select the currently
        active quadrature method
    function_updater: FunctionUpdater used to grab f(x)
        and F(x)

    Notes
    -----
    This class is configured to update the QuadMethods when the
    'Update' button is clicked
    """
    def __init__(self, ui, function_updater):
        """Creates a new QuadUpdater

        Parameters
        ----------
        ui: the application's UI

        Returns
        -------
        a new QuadUpdater, configured to update on the press
        of the 'Update button'
        """
        # Create the QuadMethod dictionary
        self.quad_methods = self.create_method_dict(ui)
        self.quad_check_buttons = self.create_button_list(ui)
        self.result = ui.calculated_result
        self.error = ui.error_calculated
        self.method_group = ui.method_group
        self.quad_table = ui.quad_method_table
        self.function_updater = function_updater

        # Register the update function with the update button
        update_button = ui.update_button
        update_button.clicked.connect(self.update)

        # Call update for the first time to initialize the QuadMethods
        self.update()

    def update(self):
        """Updates each QuadMethod tracked by this QuadUpdater,
        determines the currently active quadrature method
        from the method_group, and displays the result/
        error of integration
        """
        for quad_method in self.quad_methods.values():
            quad_method.update()

        # Grab the checked id of the button group
        # to determine which quadrature method to graph.
        # Grab the corresponding Quadrature object from
        # the quad_methods dictionary
        m_i = -2 - self.method_group.checkedId()

        if m_i == MethodNames.LEFT_POINT_RIEMMAN:
            Q = self.quad_methods['lpr']
        elif m_i == MethodNames.RIGHT_POINT_RIEMMAN:
            Q = self.quad_methods['rpr']
        elif m_i == MethodNames.MID_POINT_RIEMMAN:
            Q = self.quad_methods['mpr']
        elif m_i == MethodNames.TRAPEZOIDAL:
            Q = self.quad_methods['trap']
        elif m_i == MethodNames.SIMPSONS:
            Q = self.quad_methods['simp']
        elif m_i == MethodNames.GAUSSIAN:
            Q = self.quad_methods['gauss']
        elif m_i == MethodNames.MONTE_CARLO:
            Q = self.quad_methods['monte']
        else:
            raise IndexError('checkedId did not correspond ' +
                             'to a valid method')

        # Set the active quadrature method
        self.active_quad_method = Q

        # Loop through each check button to determine
        # which methods to show on the table
        # i keeps track of the row number for each method
        row_number = 0
        for qm_name, qm_check in self.quad_check_buttons:
            q_m = self.quad_methods[qm_name]

            # If this method is checked for the table or if it's
            # the one we're graphing, we're going to need to grab
            # integration results
            #
            # Note: this seems a little convulted to check both
            # conditions up top and then again within the if statement,
            # but by doing this, if the method is checked and is the
            # one being graphed, we can share integration values
            # between the two rather than integrating twice. This was
            # especially noticable with Monte Carlo, where the results
            # under the graph and in the table were different (because
            # Monte Carlo is random). It also saves time!
            if qm_check.isChecked() or q_m == self.active_quad_method:
                # Display results of integration and calculated error
                # If we hit a syntax error, then we failed to
                # parse the function and we just display 'N/A'
                # Note that the error is optional because F(x) is
                # optional: therefore,the second try statement is
                # nested in the first so that we can display the result
                # (which we should always have) but not the optional
                # error
                try:
                    integrate_value = str(q_m.quadrature.
                                          integrate(self.function_updater.f))
                    time_value = q_m.quadrature.time_taken
                    time_value = '{:g}'.format(time_value)
                    try:
                        error_value = q_m.quadrature.error(self.
                                                           function_updater.F)
                        error_value = '{:g}'.format(error_value)
                    except SyntaxError:
                        error_value = ''
                except SyntaxError:
                    integrate_value = ''
                    error_value = ''
                    time_value = ''

                # If q_m is the active method, then show the result and error
                # under the graph
                if q_m == self.active_quad_method:
                    if integrate_value == '':
                        self.result.setText('N/A')
                    else:
                        self.result.setText(integrate_value)

                    if error_value == '':
                        self.error.setText('N/A')
                    else:
                        self.error.setText(error_value)

                # Get the values to display on the table. If this method
                # isn't checked, just set the values to a blank string
                if not qm_check.isChecked():
                    table_i_value = ''
                    table_e_value = ''
                    table_t_value = ''
                else:
                    table_i_value = integrate_value
                    table_e_value = error_value
                    table_t_value = time_value
            else:
                # The method isn't checked or the active method, so
                # no integration is necessary:
                # We only need to set table values, so just set the
                # values to blank strings
                table_i_value = ''
                table_e_value = ''
                table_t_value = ''

            self.quad_table.setItem(row_number, 0,
                                    QtGui.QTableWidgetItem(table_i_value))
            self.quad_table.setItem(row_number, 1,
                                    QtGui.QTableWidgetItem(table_e_value))
            self.quad_table.setItem(row_number, 2,
                                    QtGui.QTableWidgetItem(table_t_value))

            # Increment the row number
            row_number += 1

    def create_button_list(self, ui):
        """Creates a list of tuples matching quad methods with
        their corresponding checkboxes on the GUI.

        Parameters
        ----------
        ui: the application's UI

        Returns
        -------
        a list of tuples matching quad methods with
        their corresponding checkboxes on the GUI.
        """
        # Create kvp tuples for each QuadMethod and its checkbox
        # This doesn't create a real dictionary, but instead
        # a list of tuples because the order of the elements
        # will be important (dictionaries can have an order that
        # differs from how you defined it)
        kvp = []

        kvp.append(('lpr', ui.rl_check))

        kvp.append(('rpr', ui.rr_check))

        kvp.append(('mpr', ui.rm_check))

        kvp.append(('trap', ui.trap_check))

        kvp.append(('simp', ui.simp_check))

        kvp.append(('gauss', ui.gauss_check))

        kvp.append(('monte', ui.monte_check))

        # Return the list
        return kvp

    def create_method_dict(self, ui):
        """Creates the QuadMethod dictionary

        Parameters
        ----------
        ui: the application's UI

        Returns
        -------
        a dictionary holding a QuadMethod for each quadrature method
        defined in quadrature.py
        """
        # Create kvp tuples for each QuadMethod and its key
        kvp = []

        kvp.append(('lpr', QuadMethod(ui, 'LeftPointRiemman', ui.rl_n)))

        kvp.append(('rpr', QuadMethod(ui, 'RightPointRiemman', ui.rr_n)))

        kvp.append(('mpr', QuadMethod(ui, 'MidPointRiemman', ui.rm_n)))

        kvp.append(('trap', QuadMethod(ui, 'Trapezoidal', ui.trap_n)))

        kvp.append(('simp', QuadMethod(ui, 'Simpsons', ui.simp_n,
                                       needs_even=True)))

        kvp.append(('gauss', QuadMethod(ui, 'Gaussian', ui.gauss_n,
                                        def_n=5, max_n=16)))

        kvp.append(('monte', QuadMethod(ui, 'MonteCarlo', ui.monte_n,
                                        def_n=500)))

        # Create the dictionary from the list of kvp tuples
        return dict(kvp)

class FunctionUpdater:
    """Holds references to the inputs for f(x) (the main function) and
    F(x) (the anti-derivative) and is responsible for parsing their
    inputs and updating them in accordance with the input

    Attributes
    ----------
    f: f(x), the main function to graph and integrate
    F: F(x), the anti-derivative of f(x), used for error analysis
    f_input: QLineEdit used to input f(x)
    F_input: QLineEdit used to input F(x)

    Notes
    -----
    this class is configured to update when the 'Update' button
    is pressed
    """
    def __init__(self, ui):
        """Creates a new FunctionUpdater

        Parameters
        ----------
        ui: the application's UI

        Returns
        -------
        a new FunctionUpdater
        """
        self.f_input = ui.f_input
        self.F_input = ui.F_input

        self.tw = ui.quad_method_table
        # Register the update function with the update button
        update_button = ui.update_button
        update_button.clicked.connect(self.update)

        # Call update for the first time to initialize f and F
        self.update()

    def update(self):
        """Updates the functions f and F by parsing their respective
        inputs"""

        # To parse the functions, we first need to define global
        # variables to hold the strings from the QLineEdit's so that
        # the exec statement can access them.
        # We then use parse_function to turn the strings into python
        # compliant expressions.
        # Finally, we use exec to define python functions and use eval
        # to evaluate the function string as a mathematical expression.
        global f_str
        f_str = parse_function(str(self.f_input.text()))

        exec """def f(x):
            return eval(f_str)"""

        global F_str
        F_str = parse_function(str(self.F_input.text()))

        exec """def F(x):
            return eval(F_str)"""

        self.f = f
        self.F = F

class MplCanvas(FigureCanvas):
    """Represents a matplotlib figure as a Qt4 widget that can
    be drawn.

    Attributes
    ----------
    fig: the matplotlib figure
    quad_updater: instance of QuadUpdater used to grab
            currently active quadrature
    function_updater: instance of FunctionUpdater used to
            graph f(x)

    Notes
    -----
    this class re-computes the figure every time the 'Update'
    button is pressed
    """
    def __init__(self, ui, parent=None, width=5,
                 height=4, dpi=100):
        """Creates a new MplCanvas

        Parameters
        ----------
        ui: the application's ui

        Returns
        -------
        a new MplCanvas
        """
        self.function_updater = FunctionUpdater(ui)
        self.quad_updater = QuadUpdater(ui, self.function_updater)

        # Create a matplotlib figure
        self.fig = Figure(figsize=(width, height), dpi=dpi)

        # Initialize the parent class
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        # Register the update_figure function with the update button
        update_button = ui.update_button
        update_button.clicked.connect(self.update_figure)

        # Call update_figure for the first time to initialize
        # the graph
        self.update_figure()

    def update_figure(self):
        """Updates and draws the figure"""
        # Clear out all the axes of the figure
        for axis in self.fig.axes:
            axis.cla()

        # Grab the currently active quadrature method for
        # graphing
        Q = self.quad_updater.active_quad_method.quadrature

        # Attempt to graph the function and the quadrature polygons
        # If we get a SyntaxError, then we weren't able to parse
        # a valid function: then, just clear the figure and display
        # nothing
        try:
            Q.shade_under_curve(self.fig, self.function_updater.f)
        except SyntaxError:
            self.fig.clf()

        self.draw()

class Application(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_main_window()
        self.ui.setupUi(self)

        graph = MplCanvas(self.ui)
        self.ui.graph_layout.addWidget(graph)

# Entry point for the application
if __name__ == '__main__':
    # Create the application and its window
    app = QtGui.QApplication(sys.argv)
    window = Application()
    window.show()
    sys.exit(app.exec_())


text:
<?php namespace Zizaco\Confide;

/**
 * The LoginThrottle is a service that Throttles login after
 * too many failed attempts. This is a secure measure in
 * order to avoid brute force attacks.
 *
 * @license MIT
 * @package Zizaco\Confide
 */
class CacheLoginThrottleService implements LoginThrottleServiceInterface
{
    /**
     * Laravel application.
     *
     * @var \Illuminate\Foundation\Application
     */
    public $app;

    /**
     * Create a new PasswordService.
     *
     * @param \Illuminate\Foundation\Application $app Laravel application object.
     */
    public function __construct($app = null)
    {
        $this->app = $app ?: app();
    }

    /**
     * Increments the count for the given identity by one and
     * also returns the current value for that identity.
     *
     * @param mixed $identity The login identity.
     *
     * @return int How many times that same identity was used.
     */
    public function throttleIdentity($identity)
    {
        $identity = $this->parseIdentity($identity);

        // Increments and also retuns the current count
        return $this->countThrottle($identity);
    }

    /**
     * Tells if the given identity has reached the throttle_limit.
     *
     * @param mixed $identity The login identity.
     *
     * @return bool True if the identity has reached the throttle_limit.
     */
    public function isThrottled($identity)
    {
        $identity = $this->parseIdentity($identity);

        // Retuns the current count
        $count = $this->countThrottle($identity, 0);

        return $count >= $this->app['config']->get('confide::throttle_limit');
    }

    /**
     * Parse the given identity in order to return a string with
     * the relevant fields. I.E: if the attacker tries to use a
     * bunch of different passwords, the identity will still be the
     * same.
     *
     * @param mixed $identity
     *
     * @return string $identityString.
     */
    protected function parseIdentity($identity)
    {
        if (is_array($identity)) {
            if (isset($identity['email'])) {
                return $identity['email'];
            } elseif (isset($identity['username'])) {
                return $identity['username'];
            } else {
                return serialize($identity);
            }
        }

        return $identity;
    }

    /**
     * Increments the count for the given string by one stores
     * it into cache and returns the current value for that
     * identity.
     *
     * @param string $identityString
     * @param int    $increments     Amount that is going to be added to the throttling attemps for the given identity.
     *
     * @return int How many times that same string was used.
     */
    protected function countThrottle($identityString, $increments = 1)
    {
        $count = $this->app['cache']
            ->get('login_throttling:'.md5($identityString), 0);

        $count = $count + $increments;

        $ttl = $this->app['config']->get('confide::throttle_time_period');

        $this->app['cache']
            ->put('login_throttling:'.md5($identityString), $count, $ttl);

        return $count;
    }
}


text: RealEx Payment Method Integration for Realauth Redirect


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.HeaderCell = void 0;

var _react = _interopRequireWildcard(require("react"));

var _InputText = require("../inputtext/InputText");

var _classnames = _interopRequireDefault(require("classnames"));

var _RowCheckbox = require("./RowCheckbox");

var _DomHandler = _interopRequireDefault(require("../utils/DomHandler"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

var HeaderCell =
/*#__PURE__*/
function (_Component) {
  _inherits(HeaderCell, _Component);

  function HeaderCell(props) {
    var _this;

    _classCallCheck(this, HeaderCell);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(HeaderCell).call(this, props));
    _this.onClick = _this.onClick.bind(_assertThisInitialized(_this));
    _this.onFilterInput = _this.onFilterInput.bind(_assertThisInitialized(_this));
    _this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this));
    _this.onResizerMouseDown = _this.onResizerMouseDown.bind(_assertThisInitialized(_this));
    _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this));
    return _this;
  }

  _createClass(HeaderCell, [{
    key: "onClick",
    value: function onClick(event) {
      if (this.props.sortable) {
        var targetNode = event.target;

        if (_DomHandler.default.hasClass(targetNode, 'p-sortable-column') || _DomHandler.default.hasClass(targetNode, 'p-column-title') || _DomHandler.default.hasClass(targetNode, 'p-sortable-column-icon') || _DomHandler.default.hasClass(targetNode.parentElement, 'p-sortable-column-icon')) {
          this.props.onSort({
            originalEvent: event,
            sortField: this.props.columnSortField || this.props.field,
            sortFunction: this.props.sortFunction,
            sortable: this.props.sortable
          });

          _DomHandler.default.clearSelection();
        }
      }
    }
  }, {
    key: "onFilterInput",
    value: function onFilterInput(e) {
      var _this2 = this;

      if (this.props.filter && this.props.onFilter) {
        if (this.filterTimeout) {
          clearTimeout(this.filterTimeout);
        }

        var filterValue = e.target.value;
        this.filterTimeout = setTimeout(function () {
          _this2.props.onFilter({
            value: filterValue,
            field: _this2.props.field,
            matchMode: _this2.props.filterMatchMode
          });

          _this2.filterTimeout = null;
        }, this.filterDelay);
      }
    }
  }, {
    key: "onResizerMouseDown",
    value: function onResizerMouseDown(event) {
      if (this.props.resizableColumns && this.props.onColumnResizeStart) {
        this.props.onColumnResizeStart({
          originalEvent: event,
          columnEl: event.target.parentElement,
          columnProps: this.props
        });
        event.preventDefault();
      }
    }
  }, {
    key: "onMouseDown",
    value: function onMouseDown(event) {
      if (this.props.reorderableColumns) {
        if (event.target.nodeName !== 'INPUT') this.el.draggable = true;else if (event.target.nodeName === 'INPUT') this.el.draggable = false;
      }
    }
  }, {
    key: "onKeyDown",
    value: function onKeyDown(event) {
      if (event.key === 'Enter' && event.currentTarget === this.el) {
        this.onClick(event);
        event.preventDefault();
      }
    }
  }, {
    key: "getMultiSortMetaData",
    value: function getMultiSortMetaData() {
      if (this.props.multiSortMeta) {
        for (var i = 0; i < this.props.multiSortMeta.length; i++) {
          if (this.props.multiSortMeta[i].field === this.props.field) {
            return this.props.multiSortMeta[i];
          }
        }
      }

      return null;
    }
  }, {
    key: "renderSortIcon",
    value: function renderSortIcon(sorted, sortOrder) {
      if (this.props.sortable) {
        var sortIcon = sorted ? sortOrder < 0 ? 'pi-sort-down' : 'pi-sort-up' : 'pi-sort';
        var sortIconClassName = (0, _classnames.default)('p-sortable-column-icon pi pi-fw', sortIcon);
        return _react.default.createElement("span", {
          className: sortIconClassName
        });
      } else {
        return null;
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var multiSortMetaData = this.getMultiSortMetaData();
      var singleSorted = this.props.field === this.props.sortField || this.props.columnSortField != null && this.props.columnSortField === this.props.sortField;
      var multipleSorted = multiSortMetaData !== null;
      var sortOrder = 0;

      var resizer = this.props.resizableColumns && _react.default.createElement("span", {
        className: "p-column-resizer p-clickable",
        onMouseDown: this.onResizerMouseDown
      });

      var filterElement, headerCheckbox;
      if (singleSorted) sortOrder = this.props.sortOrder;else if (multipleSorted) sortOrder = multiSortMetaData.order;
      var sorted = this.props.sortable && (singleSorted || multipleSorted);
      var className = (0, _classnames.default)({
        'p-sortable-column': this.props.sortable,
        'p-highlight': sorted,
        'p-resizable-column': this.props.resizableColumns,
        'p-selection-column': this.props.selectionMode
      }, this.props.headerClassName || this.props.className);
      var sortIconElement = this.renderSortIcon(sorted, sortOrder);

      if (this.props.filter) {
        filterElement = this.props.filterElement || _react.default.createElement(_InputText.InputText, {
          onInput: this.onFilterInput,
          type: this.props.filterType,
          defaultValue: this.props.filters && this.props.filters[this.props.field] ? this.props.filters[this.props.field].value : null,
          className: "p-column-filter",
          placeholder: this.props.filterPlaceholder,
          maxLength: this.props.filterMaxLength
        });
      }

      if (this.props.selectionMode === 'multiple') {
        headerCheckbox = _react.default.createElement(_RowCheckbox.RowCheckbox, {
          onClick: this.props.onHeaderCheckboxClick,
          selected: this.props.headerCheckboxSelected,
          disabled: !this.props.value || this.props.value.length === 0
        });
      }

      return _react.default.createElement("th", {
        ref: function ref(el) {
          return _this3.el = el;
        },
        tabIndex: this.props.sortable ? this.props.tabIndex : null,
        className: className,
        style: this.props.headerStyle || this.props.style,
        onClick: this.onClick,
        onMouseDown: this.onMouseDown,
        onKeyDown: this.onKeyDown,
        colSpan: this.props.colSpan,
        rowSpan: this.props.rowSpan,
        onDragStart: this.props.onDragStart,
        onDragOver: this.props.onDragOver,
        onDragLeave: this.props.onDragLeave,
        onDrop: this.props.onDrop
      }, resizer, _react.default.createElement("span", {
        className: "p-column-title"
      }, this.props.header), sortIconElement, filterElement, headerCheckbox);
    }
  }]);

  return HeaderCell;
}(_react.Component);

exports.HeaderCell = HeaderCell;


text:
function TweetObservable() {
  var connection = initWebsocket();

  connection.onopen = function () {
    console.log("Connection successfully opened");
  }

  function topicOnNext(tuple) {
    var message = {};

    if(tuple.current!==""){
      message.action = "subscribe_topic";
      message.payload = tuple.current;
      connection.send(JSON.stringify(message))
    }
    message.action = "unsubscribe_topic";
    message.payload = tuple.last;
    connection.send(JSON.stringify(message))

  }

  inputObservables.topic1
  .subscribe(topicOnNext,
    function (err) {
      console.log('error: ' + err);
    },
    function () {
      console.log("Topic update stream completed.");
    }
  );
  inputObservables.topic2
    .subscribe(topicOnNext,
    function (err) {
      console.log('error: ' + err);
    },
    function () {
      console.log("Topic update stream completed.");
    }
  );
  inputObservables.topic3
    .subscribe(topicOnNext,
    function (err) {
      console.log('error: ' + err);
    },
    function () {
      console.log("Topic update stream completed.");
    }
  );
  inputObservables.topic4
    .subscribe(topicOnNext,
    function (err) {
      console.log('error: ' + err);
    },
    function () {
      console.log("Topic update stream completed.");
    }
  );

  //The function given as parameter to create will only get executed when subscribe is called on tweetObservable.
  return Rx.Observable.create(function (observer) {
    connection.onmessage = function (message) {
      observer.onNext(message);
    }

    connection.onerror = function (error) {
      observer.onError(error);
    }

    connection.onclose = function () {
      observer.onCompleted();
    }
  });
}

var initWebsocket = function () {
  window.WebSocket = window.WebSocket || window.MozWebSocket;

  var connection = new WebSocket('ws://127.0.0.1:3000/', 'twitter-protocol');

  if (!window.WebSocket) {
    console.log("Your browser does not support websockets");
    return;
  }
  return connection;
}


text:
import * as React from 'react';
import Box from '@material-ui/core/Box';
import Slider from '@material-ui/core/Slider';

export default function VerticalSlider() {
  function preventHorizontalKeyboardNavigation(event) {
    if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
      event.preventDefault();
    }
  }

  return (
    <Box sx={{ height: 300 }}>
      <Slider
        sx={{
          '& input[type="range"]': {
            WebkitAppearance: 'slider-vertical',
          },
        }}
        orientation="vertical"
        defaultValue={30}
        aria-label="Temperature"
        onKeyDown={preventHorizontalKeyboardNavigation}
      />
    </Box>
  );
}


text:
cask 'font-doppio-one' do
  version '1.002'
  sha256 '2686a4eadfad03961f63e8474798a8b591d531aaa1bde6923481565830b19d9e'

  # googlefontdirectory.googlecode.com was verified as official when first introduced to the cask
  url 'https://googlefontdirectory.googlecode.com/hg-history/67342bc472599b4c32201ee4a002fe59a6447a42/ofl/doppioone/DoppioOne-Regular.ttf'
  name 'Doppio One'
  homepage 'http://www.google.com/fonts/specimen/Doppio%20One'

  font 'DoppioOne-Regular.ttf'
end


text:
package agni

import com.datastax.oss.driver.api.core.ProtocolVersion
import com.datastax.oss.driver.api.core.`type`.codec.TypeCodecs
import com.datastax.oss.driver.api.core.cql.BoundStatement
import org.mockito.Mockito._
import org.mockito.ArgumentMatchers.{`eq` => eqTo}
import org.scalatest.Assertion
import org.scalatestplus.mockito.MockitoSugar

class BinderSpec extends TypedSuite with MockitoSugar {

  def checkType[A: Binder]: Assertion =
    assertCompiles("Binder.apply[A]")

  test("Binder[T1]")(checkType[T1])
  test("Binder[T2]")(checkType[T2])
  test("Binder[T3]")(checkType[T3])
  test("Binder[T4]")(checkType[T4])
  test("Binder[T5]")(checkType[T5])
  test("Binder[T6]")(checkType[T6])
  test("Binder[T7]")(checkType[T7])
  test("Binder[T8]")(checkType[T8])
  test("Binder[T9]")(checkType[T9])
  test("Binder[T10]")(checkType[T10])
  test("Binder[T11]")(checkType[T11])
  test("Binder[T12]")(checkType[T12])
  test("Binder[T13]")(checkType[T13])
  test("Binder[T14]")(checkType[T14])
  test("Binder[T15]")(checkType[T15])
  test("Binder[T16]")(checkType[T16])
  test("Binder[T17]")(checkType[T17])
  test("Binder[T18]")(checkType[T18])
  test("Binder[T19]")(checkType[T19])
  test("Binder[T20]")(checkType[T20])
  test("Binder[T21]")(checkType[T21])
  test("Binder[T22]")(checkType[T22])
  test("Binder[T22_2]")(checkType[T22_2])

  test("binding values as a tuple") {
    val a = mock[BoundStatement]
    val b = mock[BoundStatement]
    val c = mock[BoundStatement]
    val d = mock[BoundStatement]
    val e = mock[BoundStatement]

    val v = ProtocolVersion.DEFAULT

    when(a.setBytesUnsafe(eqTo(0), eqTo(TypeCodecs.ASCII.encode("a", v)))).thenReturn(b)
    when(b.setBytesUnsafe(eqTo(1), eqTo(TypeCodecs.INT.encode(1, v)))).thenReturn(c)
    when(c.setBytesUnsafe(eqTo(2), eqTo(TypeCodecs.BIGINT.encode(2L, v)))).thenReturn(d)
    when(d.setBytesUnsafe(eqTo(3), eqTo(TypeCodecs.ASCII.encode("z", v)))).thenReturn(e)

    val s = Binder[(String, Int, Long, String)].apply(a, v, ("a", 1, 2L, "z"))

    assert(s === Right(e))
  }
}


text:
/*
  margin
*/
var phantom = require('phantom'),
  fs = require('fs'),
  path = require('path'),
  handlebars = require('handlebars'),
  marked = require('marked'),
  readOptions = { "encoding": "utf-8" };

var createPdfFromHTML = function(pdfPath, html, callback) {
  var tempFilename = path.join(__dirname,"marginTemporaryHTMLFile.html");
  if(!pdfPath) {
    pdfPath = path.join(".","document.pdf");
  }
  if(!html) {
    html = '';
  }
  // write the HTML to a temporary file
  fs.writeFile(tempFilename, html, function() {
    phantom.create(function(ph){
      ph.createPage(function(page) {
        // open the temp file in phantom
        page.open(tempFilename, function(status) {
          page.set('viewportSize', {width:1280,height:1800}, function(result) {
            // create the PDF
            page.render(pdfPath, function(){
              ph.exit();
              fs.unlink(tempFilename, function(err) {
                if(callback) {
                  callback(err, pdfPath);
                }
              });
            });
          });
        });
      });
    });
  });
};

/*
 * Create a multi-page PDF with a cover template
 *
 * Read in cover template
 * Render cover + data JSON through handlebars
 * Turn pages.md into HTML
 * Add pages.md to end of cover.html
 * Convert HTML into PDF
 */
var createPdfFromFolder = function(folderPath, pdfPath, callback) {
  if(!folderPath) {
    folderPath = __dirname;
  }
  var coverTemplateFilename = path.join(folderPath,"template/cover.html"),
    dataJSONFileName = path.join(folderPath,"data.json"),
    pagesFileName = path.join(folderPath,"pages.md");

    // read in the cover template
    fs.readFile(coverTemplateFilename, readOptions, function(err, source) {
      var template = handlebars.compile(source);
      // read in the JSON data for the cover
      fs.readFile(dataJSONFileName, readOptions, function(err, data) {
        var jsonData = JSON.parse(data),
          result = template(jsonData);
        // read in the markdown document
        fs.readFile(pagesFileName, readOptions, function(err, data) {
          // convert markdown to HTML
          var pagesHTML = marked(data),
            bits = result.split(''),
            htmlForRenderingToPDF;
          // wrap pages HTML in a wrapper and insert before the end of the body
          bits.splice(1,0,'
',pagesHTML,'
');
          htmlForRenderingToPDF = bits.join("");
          // create the PDF
          createPdfFromHTML(pdfPath, htmlForRenderingToPDF, callback);
        });
      });
    });
};

module.exports = {
  createPdfFromHTML: createPdfFromHTML,
  createPdfFromFolder: createPdfFromFolder
};


text:
<?php

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 *
 * @api
 */
class FalseValidator extends ConstraintValidator
{
    /**
     * {@inheritdoc}
     */
    public function validate($value, Constraint $constraint)
    {
        if (!$constraint instanceof False) {
            throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\False');
        }

        if (null === $value || false === $value || 0 === $value || '0' === $value) {
            return;
        }

        $this->buildViolation($constraint->message)
            ->setParameter('{{ value }}', $this->formatValue($value))
            ->addViolation();
    }
}


text:
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>CHOWTIME</title>

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

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" type="text/css">

    <link rel="stylesheet" href="css/animate.min.css" type="text/css">

    <link rel="stylesheet" href="css/adminf.css" type="text/css">
    <link rel="stylesheet" href="css/admine.css" type="text/css">

ChowtimeAdmin

Dashboard

Manage Events

Manage Exhibitions

Manage Members

Manage Reservations

Manage Subscriptions

Manage Quizzes

Go to Website Statistics

Settings

Log Out

<?php
$servername = "localhost";
$username = "root";
$password = "00000000";
$dbname = "chowtime";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);}

$sql="INSERT INTO events (event_id, ename, start_date, end_date, organizer, type, description)
VALUES
('$_POST[event_id]',
'$_POST[ename]',
'$_POST[start_date]',
'$_POST[end_date]',
'$_POST[organizer]',
'$_POST[type]',
'$_POST[description]')";

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully.";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

Go Back to Previous Page

           Click here to go back to Previous Page


text:
import QUnit from 'qunit';
import MockServer from '../src/mock-server';
import MockSocket from '../src/mock-socket';

QUnit.module('Issue #19: Mock Server on(message) argument should be a string and not an object.');

QUnit.test('Mock Server on(message) argument should be a string and not an object.', function(assert) {
  var socketUrl             = 'ws://localhost:8080';
  var mockServer            = new MockServer(socketUrl);
  var mockSocket            = new MockSocket(socketUrl);
  var done                  = assert.async();

  assert.expect(1);

  mockServer.on('connection', function (socket) {
      socket.on('message', function (message) {
          assert.equal(typeof message, 'string', 'message should be a string and not an object');
          done();
      });
  });

  mockSocket.onopen = function () {
      mockSocket.send('1');
  };
});


text:
maintainer        "Opscode, Inc."
maintainer_email  "cookbooks@opscode.com"
license           "Apache 2.0"
description       "Installs and configures ntp as a client or server"
long_description  IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version           "1.1.0"

recipe "ntp", "Installs and configures ntp either as a server or client"

%w{ ubuntu debian redhat centos fedora scientific }.each do |os|
  supports os
end

attribute "ntp",
  :display_name => "NTP",
  :description => "Hash of NTP attributes",
  :type => "hash"

attribute "ntp/service",
  :display_name => "NTP Service",
  :description => "Name of the NTP service",
  :default => "ntp"

attribute "ntp/is_server",
  :display_name => "NTP Is Server?",
  :description => "Set to true if this is an NTP server",
  :default => "false"

attribute "ntp/servers",
  :display_name => "NTP Servers",
  :description => "Array of servers we should talk to",
  :type => "array",
  :default => ["0.pool.ntp.org", "1.pool.ntp.org", "2.pool.ntp.org", "3.pool.ntp.org" ]

attribute "ntp/peers",
  :display_name => "NTP Peers",
  :description => "Array of local NTP servers, we should peer with",
  :type => "array",
  :default => []

attribute "ntp/restrictions",
  :display_name => "Restriction lines",
  :description => "Array of restriction lines to apply to NTP servers",
  :type => "array",
  :default => []


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;

internal partial class Interop
{
    internal partial class mincore
    {
        [DllImport(Libraries.ProcessThread_L1, SetLastError = true)]
        internal static extern bool GetExitCodeProcess(SafeProcessHandle processHandle, out int exitCode);
    }
}


text:
import argparse
import json

from pipeline.backend.pipeline import PipeLine
from pipeline.component import DataTransform
from pipeline.component import Evaluation
from pipeline.component import HomoLR
from pipeline.component import Reader
from pipeline.component import FeatureScale
from pipeline.interface import Data
from pipeline.interface import Model
from pipeline.utils.tools import load_job_config

def main(config="../../config.yaml", namespace=""):
    # obtain config
    if isinstance(config, str):
        config = load_job_config(config)
    parties = config.parties
    guest = parties.guest[0]
    host = parties.host[0]
    arbiter = parties.arbiter[0]

    guest_train_data = {"name": "breast_homo_guest", "namespace": f"experiment{namespace}"}
    host_train_data = {"name": "breast_homo_host", "namespace": f"experiment{namespace}"}

    guest_eval_data = {"name": "breast_homo_guest", "namespace": f"experiment{namespace}"}
    host_eval_data = {"name": "breast_homo_host", "namespace": f"experiment{namespace}"}

    # initialize pipeline
    pipeline = PipeLine()
    # set job initiator
    pipeline.set_initiator(role='guest', party_id=guest)
    # set participants information
    pipeline.set_roles(guest=guest, host=host, arbiter=arbiter)

    # define Reader components to read in data
    reader_0 = Reader(name="reader_0")
    # configure Reader for guest
    reader_0.get_party_instance(role='guest', party_id=guest).component_param(table=guest_train_data)
    # configure Reader for host
    reader_0.get_party_instance(role='host', party_id=host).component_param(table=host_train_data)

    reader_1 = Reader(name="reader_1")
    reader_1.get_party_instance(role='guest', party_id=guest).component_param(table=guest_eval_data)
    reader_1.get_party_instance(role='host', party_id=host).component_param(table=host_eval_data)
    # define DataTransform components
    data_transform_0 = DataTransform(
        name="data_transform_0",
        with_label=True,
        output_format="dense")  # start component numbering at 0
    data_transform_1 = DataTransform(name="data_transform_1")  # start component numbering at 0

    scale_0 = FeatureScale(name='scale_0')
    scale_1 = FeatureScale(name='scale_1')

    param = {
        "penalty": "L2",
        "optimizer": "sgd",
        "tol": 1e-05,
        "alpha": 0.01,
        "max_iter": 3,
        "early_stop": "diff",
        "batch_size": 320,
        "learning_rate": 0.15,
        "validation_freqs": 1,
        "init_param": {
            "init_method": "zeros"
        },
        "encrypt_param": {
            "method": None
        },
        "cv_param": {
            "n_splits": 4,
            "shuffle": True,
            "random_seed": 33,
            "need_cv": False
        }
    }

    homo_lr_0 = HomoLR(name='homo_lr_0', **param)
    homo_lr_1 = HomoLR(name='homo_lr_1')

    # add components to pipeline, in order of task execution
    pipeline.add_component(reader_0)
    pipeline.add_component(reader_1)

    pipeline.add_component(data_transform_0, data=Data(data=reader_0.output.data))
    pipeline.add_component(data_transform_1, data=Data(data=reader_1.output.data),
                           model=Model(data_transform_0.output.model))

    # set data input sources of intersection components
    pipeline.add_component(scale_0, data=Data(data=data_transform_0.output.data))
    pipeline.add_component(scale_1, data=Data(data=data_transform_1.output.data),
                           model=Model(scale_0.output.model))

    pipeline.add_component(homo_lr_0, data=Data(train_data=scale_0.output.data,
                                                validate_data=scale_1.output.data))
    pipeline.add_component(homo_lr_1, data=Data(test_data=scale_1.output.data),
                           model=Model(homo_lr_0.output.model))
    evaluation_0 = Evaluation(name="evaluation_0", eval_type="binary")
    evaluation_0.get_party_instance(role='host', party_id=host).component_param(need_run=False)
    pipeline.add_component(evaluation_0, data=Data(data=[homo_lr_0.output.data,
                                                         homo_lr_1.output.data]))

    # compile pipeline once finished adding modules, this step will form conf and dsl files for running job
    pipeline.compile()

    # fit model
    pipeline.fit()
    # query component summary
    print(json.dumps(pipeline.get_component("homo_lr_0").get_summary(), indent=4, ensure_ascii=False))
    print(json.dumps(pipeline.get_component("evaluation_0").get_summary(), indent=4, ensure_ascii=False))

if __name__ == "__main__":
    parser = argparse.ArgumentParser("PIPELINE DEMO")
    parser.add_argument("-config", type=str,
                        help="config file")
    args = parser.parse_args()
    if args.config is not None:
        main(args.config)
    else:
        main()


text:
<form name="signup_form" novalidate ng-submit="submitSignUpForm()" role="form">
	<legend>Simple Sign_Up Form</legend>

		{{astri}} Name:
		<input type="text" class="form-control" name="name" id="signup_name" placeholder="Name..." ng-model="signup.name" ng-minlength=3 ng-maxlength=10 required />

			(small tag) Your name is required...
			<dfn ng-show="signup_form.name.$error.minlength">(dfn tag) At least 3 letters</dfn>
			(code tag) Not more than 10 letters...

		<s>s Tag</s>

		del Tag
		em tag
		strong tag
		{{astri}}(kbd tag) Email With Pattern:
		<input type="email" class="form-control" id="signup_email" placeholder="Email..."
			name="email"
			ng-model="signup.email"
			ng-minlength=3 ng-maxlength=16
			ng-pattern="EMAIL_REGEX"
			required />

			(ins tag) Your email is required...
			<legend ng-show="signup_form.email.$error.minlength">(legend tag) At least 3 letters</legend>
			(mark tag) Not more than 16 letters...
			<samp ng-show="signup_form.email.$error.pattern">(samp tag) Not match the pattern...</samp>

		(sub tag) {{astri}}(sup tag) unique Username:
		<input type="text" class="form-control" id="signup_username" placeholder="UserName..."
			name="username"
			ng-model="signup.username"
			ng-minlength=3 ng-maxlength=20
			ensure-unique="username"
			required />

			(summary tag) Your username is required...
			<var ng-show="signup_form.username.$error.minlength">(var tag) At least 3 letters</var>
			(span tag) Not more<wbr> (wbr tag) than 20 letters</wbr>...
			(ins tag) Not more than 20 letters...

	<button type="submit" class="btn btn-primary" ng-disabled="signup_form.$invalid">Submit</button>

</form>


text:
package org.codehaus.griffon.runtime.javafx.controller;

import griffon.annotations.core.Nonnull;
import griffon.core.artifact.GriffonController;
import griffon.core.controller.Action;
import griffon.core.controller.ActionFactory;
import griffon.core.controller.ActionManager;
import griffon.core.controller.ActionMetadata;
import griffon.core.threading.UIThreadManager;

import javax.inject.Inject;

/**
 * @author Andres Almiray
 * @since 2.11.0
 */
public class JavaFXActionFactory implements ActionFactory {
    @Inject
    private UIThreadManager uiThreadManager;

    @Inject
    private ActionManager actionManager;

    @Nonnull
    @Override
    public Action create(@Nonnull GriffonController controller, @Nonnull ActionMetadata actionMetadata) {
        return new JavaFXGriffonControllerAction(uiThreadManager, actionManager, controller, actionMetadata);
    }
}


text:
__author__ = 'rberman'

"""
This program takes all the JSON formatted data
and compiles one big document containing just all text from reviews.
Text is stored in file review_text.txt in the same location as this program.
"""

import json

def get_reviews(file):
    reviews = json.load(open("reviews_data.json"))
    for review in reviews:
      file.write(review["review"] + "\n")

def main():
    review_text = open("review_text.txt", "w")
    get_reviews(review_text)
    review_text.close()

main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.xcesys.extras</groupId>
	<artifactId>spring-boot-starter</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>Spring Boot Starter</name>
	<description>Spring boot starter project</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<war.plugin.version>2.4</war.plugin.version>
		<resources.plugin.version>2.6</resources.plugin.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-validation</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>com.github.mxab.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-data-attribute</artifactId>
		</dependency>
		<dependency>
			<groupId>nz.net.ultraq.thymeleaf</groupId>
			<artifactId>thymeleaf-layout-dialect</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-logging</artifactId>
		</dependency>
		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-springsecurity4</artifactId>
		</dependency>
		<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf-spring4</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<!-- Joda Time -->
		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
		</dependency>

		<!-- Joda Money -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.2</version>
		</dependency>
		<dependency>
			<groupId>com.github.darrachequesne</groupId>
			<artifactId>spring-data-jpa-datatables</artifactId>
			<version>4.0</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<!-- Set Java Version -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
					<showDeprecation>true</showDeprecation>
					<optimize>true</optimize>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<!-- War Plugin -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<configuration>
					<!-- Use Servlet Java Config instead of XML -->
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>

			<!-- Resources Plugin -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<configuration>
					<useSystemClassLoader>false</useSystemClassLoader>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
using System;
using System.Windows.Forms;
using Alphora.Dataphor.Dataphoria.Designers;

namespace Alphora.Dataphor.Dataphoria.ObjectTree.Nodes
{
    public class FormDocumentNode : DocumentNode
    {
        public FormDocumentNode(DocumentListNode parent, string documentName, string documentType) : base(parent, documentName, documentType)
        {
            ImageIndex = 10;
            SelectedImageIndex = ImageIndex;
        }

        protected override ContextMenu GetContextMenu()
        {
            ContextMenu menu = base.GetContextMenu();

            menu.MenuItems.Add(2, new MenuItem(Strings.ObjectTree_CustomizeMenuText, new EventHandler(CustomizeClicked)));
            menu.MenuItems.Add(3, new MenuItem(Strings.ObjectTree_ShowMenuText, new EventHandler(StartClicked), Shortcut.F9));

            return menu;
        }

        private string GetDocumentExpression()
        {
            return
                String.Format
                    (
                    ".Frontend.Form('{0}', '{1}')",
                    DAE.Schema.Object.EnsureRooted(LibraryName),
                    DAE.Schema.Object.EnsureRooted(DocumentName)
                    );
        }

        private void CustomizeClicked(object sender, EventArgs args)
        {
            Dataphor.Dataphoria.FormDesigner.CustomFormDesigner designer = new Dataphor.Dataphoria.FormDesigner.CustomFormDesigner(Dataphoria, "DFDX");
            try
            {
                BOP.Ancestors ancestors = new BOP.Ancestors();
                ancestors.Add(GetDocumentExpression());
                designer.New(ancestors);
                ((IDesigner)designer).Show();
            }
            catch
            {
                designer.Dispose();
                throw;
            }

        }

        private void StartClicked(object sender, EventArgs args)
        {
            Frontend.Client.Windows.Session session = Dataphoria.GetLiveDesignableFrontendSession();
            try
            {
                session.SetLibrary(LibraryName);
                session.StartCallback(GetDocumentExpression(), null);
            }
            catch
            {
                session.Dispose();
                throw;
            }
        }
    }
}


text:
all: checker client webserver

checker: privkey.pem server.pem
	cd src/checker && $(MAKE)
	cp src/checker/checker .

client: server.pem
	cd src/client && $(MAKE)
	cp src/client/client .

webserver: privkey.pem server.pem
	cd src/webserver && $(MAKE)
	cp src/webserver/webserver .

privkey.pem:
	openssl genrsa -out privkey.pem 4096
	chmod og-rwx privkey.pem

server.pem: privkey.pem
	openssl req -new -x509 -key privkey.pem -outform PEM -out server.pem -subj / -days 1095

clean:
	cd src/checker && $(MAKE) clean
	cd src/client && $(MAKE) clean
	cd src/common && $(MAKE) clean
	cd src/webserver && $(MAKE) clean
	$(RM) checker client webserver privkey.pem server.pem

.PHONY: all checker client webserver clean


text:
{% extends 'emails/base.html' %}

{% block footer %}
    {% include 'shared/terms_and_conditions.html' %}
{% endblock %}


text:
import createAsyncEncryptor from "redux-persist-transform-encrypt";

export default createAsyncEncryptor;


text:
lazyauth
========

Laravel 4 package for a really basic HTTP authentication process.

# Installation

- Install package

	In composer.json (of the root of your project) add the package:

		{
			...
			"require": {
				...
				"FR6/lazyauth": "dev-master"
			},
			"repositories": [{
				"type": "git",
				"url": "git@github.com:FR6/lazyauth.git"
			}],
			...
		}

	$ composer update FR6/lazyauth

	In app/config/app.php

		'providers' => array(
			...
			'FR6\Lazyauth\LazyauthServiceProvider'
		)

	$ composer dump-autoload

- Publish configuration file

	$ php artisan config:publish fr6/lazyauth

# Usage

In your routes.php:

	Route::group(array('before' => 'lazyauth', 'prefix' => 'admin'), function(){

		Route::get('/', function(){
			...
		});
	});