text:
import math
import numpy as np
from saltfit import Parameter, fit
from scipy import optimize

class FPRing:
    """This is a general class describing a ring.   As of now, we will define
       a ring to be defined as being described as an ellipse with an Gaussian
       profile around the central line

       A ring is described by the following equation:
       F=A*exp(-(r-r_o)**2/sigma)
       where:
       A--Peak intensity
       r_o--peak radius
       sigma--width of the line
       And the radius is given by:
       r**2=(x-xc/A)**2+(y-yc/B)**2

       For the time being, we will assume that A=B=1

    """
    def __init__(self, xc=0.0, yc=0.0, prad=100.0, norm=1,  sigma=10, ell=0, prad_err=1.0):
        self.xc=xc
        self.yc=yc
        self.norm=norm
        self.prad=prad
        self.prad_err=prad_err
        self.sigma=sigma
        self.ell=ell

    def __call__(self, x, y):
        r=((x-self.xc)**2+(y-self.yc)**2)**0.5
        if isinstance(x, np.ndarray):
           return self.norm*np.exp(-((r-self.prad)/self.sigma)**2)
        else:
           return self.norm*math.exp(-((r-self.prad)/self.sigma)**2)

def ringfit(data, mask=None, fpring=None, full_output=1):
   """Ring fit takes an array of data and then fits an fpring to it.

      Parameters
      ----------

      data: ndarray
        Array of values

      mask: ndarray
        Optional mask for the data

      fpring: FPRing
        Option initial guess for the FPRing

      Output
      ------

      ring: FPRing
        Returns an FPRing that is the best fit to the data
   """

   if mask is None:
      mask=(data>-999)

   if fpring is None:
      ylen,xlen=data.shape
      fpring=FPRing(0.5*xlen, 0.5*ylen, 383)

   #setup the indices
   y,x=np.indices(data.shape)

   #setup the parameters

   param=[fpring.xc, fpring.yc, fpring.prad, fpring.norm, fpring.sigma, 0]
   #set up the call
   def call(p, x, y):
       fpr=FPRing(p[0], p[1], p[2], p[3],p[4])
       return fpr(x,y)+p[5]

   #setup the erf
   def erf(p, x, y):
      return data[mask]-call(p,x,y)[mask] #call(x,y).ravel()

   results=optimize.leastsq(erf, param, args=(x,y)) #, full_output=full_output)
   fpring=FPRing(results[0][0], results[0][1],results[0][2],results[0][3],results[0][4])
   return fpring


text:
import os

cpth = os.path.join('temp', 't005')
# make the directory if it does not exist
if not os.path.isdir(cpth):
    os.makedirs(cpth)

def test_modflow_unstructured():
    import flopy
    mf = flopy.modflow.Modflow(version='mfusg', structured=False,
                               model_ws=cpth)
    assert isinstance(mf, flopy.modflow.Modflow)

    dis = flopy.modflow.ModflowDis(mf)
    assert isinstance(dis, flopy.modflow.ModflowDis)

    bas = flopy.modflow.ModflowBas(mf)
    assert isinstance(bas, flopy.modflow.ModflowBas)

    lpf = flopy.modflow.ModflowLpf(mf)
    assert isinstance(lpf, flopy.modflow.ModflowLpf)

    wel = flopy.modflow.ModflowWel(mf, stress_period_data={0: [[0, -100]]})
    assert isinstance(wel, flopy.modflow.ModflowWel)

    ghb = flopy.modflow.ModflowGhb(mf,
                                   stress_period_data={0: [[1, 5.9, 1000.]]})
    assert isinstance(ghb, flopy.modflow.ModflowGhb)

    oc = flopy.modflow.ModflowOc(mf)
    assert isinstance(oc, flopy.modflow.ModflowOc)

    sms = flopy.modflow.ModflowSms(mf)
    assert isinstance(sms, flopy.modflow.ModflowSms)

    # write well file
    wel.write_file()
    assert os.path.isfile(os.path.join(cpth, '{}.wel'.format(mf.name))) is True
    wel2 = flopy.modflow.ModflowWel.load(
        os.path.join(cpth, '{}.wel'.format(mf.name)), mf)
    assert wel2.stress_period_data[0] == wel.stress_period_data[0]

    # write ghb file
    ghb.write_file(check=False)
    assert os.path.isfile(os.path.join(cpth, '{}.ghb'.format(mf.name))) is True
    ghb2 = flopy.modflow.ModflowGhb.load(
        os.path.join(cpth, '{}.ghb'.format(mf.name)), mf)
    assert ghb2.stress_period_data[0] == ghb.stress_period_data[0]

    return

if __name__ == '__main__':
    test_modflow_unstructured()

redpajama_set_name: RedPajamaGithub


text:
#  Using Amazon API Gateway to invoke  Lambda functions

## Overview
| Heading      | Description |
| ----------- | ----------- |
| Description | Dicusses how to develop an AWS Lambda function using the Java run-time API and then how to invoke it by using Amazon API Gateway.  |
| Audience   |  Developer (beginner / intermediate)        |
| Updated   | 1/14/2022        |
| Required Skills   | Java, Maven  |

## Purpose
You can invoke an AWS Lambda function by using Amazon API Gateway, which is an AWS service for creating, publishing, maintaining, monitoring, and securing REST, HTTP, and WebSocket APIs at scale. API developers can create APIs that access AWS or other web services, as well as data stored in the AWS Cloud. As an API Gateway developer, you can create APIs for use in your own client applications. For more information, see [What is Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html).

Lambda is a compute service that enables you to run code without provisioning or managing servers. You can create Lambda functions in various programming languages. For more information about AWS Lambda, see
[What is AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html).

In this tutorial, you create a Lambda function by using the AWS Lambda Java runtime API. This example invokes different AWS services to perform a specific use case. For example, assume that an organization sends a mobile text message to its employees that congratulates them at the one year anniversary date, as shown in this illustration.

![AWS Tracking Application](images/picPhone.png)

This tutorial shows you how to use Java logic to create a solution that performs this use case.  For example, you'll learn how to read a database to determine which employees have reached the one year anniversary date, how to process the data, and send out a text message all by using a Lambda function. Then you'll learn how to use Amazon API Gateway to invoke this Lambda function by using a Rest endpoint. For example, you can invoke the Lambda function by using this curl command:

      curl -XGET "https://xxxxqjko1o3.execute-api.us-east-1.amazonaws.com/cronstage/employee"

This AWS tutorial uses an Amazon DynamoDB table named **Employee** that contains these fields.

-	**Id** – the key for the table.
-	**first** – the employee's first name.
-	**phone** – the employee's phone number.
-	**startDate** – the employee's start date.

![AWS Tracking Application](images/employeetable2.png)

**Note**: To learn how to invoke an AWS Lambda function using scheduled events, see [Creating scheduled events to invoke Lambda functions](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/usecases/creating_scheduled_events).

#### Topics
+	Prerequisites
+	Create an AWS Identity and Access Management (IAM) role that is used to execute Lambda functions
+	Create an IntelliJ project named **LambdaCronFunctions**
+	Add the POM dependencies to your project
+	Create an AWS Lambda function by using the AWS Lambda runtime API
+	Package the project that contains the AWS Lambda function
+	Deploy the AWS Lambda function
+	Configure Amazon API Gateway to invoke the Lambda function

## Prerequisites
To follow along with this tutorial, you need the following:
+ An AWS Account with proper credentials.
+ A Java IDE (for this tutorial, the IntelliJ IDE is used).
+ Java 1.8 JDK.
+ Maven 3.6 or higher.

### Important

+ The AWS services included in this document are included in the [AWS Free Tier](https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&all-free-tier.sort-order=asc).
+  This code has not been tested in all AWS Regions. Some AWS services are available only in specific regions. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services).
+ Running this code might result in charges to your AWS account.
+ Be sure to terminate all of the resources you create while going through this tutorial to ensure that you're not charged.

### Creating the resources

An Amazon DynamoDB table named **Employee** with a key named **Id** and the fields shown in the previous illustration. Make sure you enter the correct data, including a valid mobile phone that you want to test this use case with. To learn how to create a DynamoDB table, see [Create a Table](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/getting-started-step-1.html).

## Create an IAM role that's used to execute Lambda functions

Create the following IAM role:

+ **lambda-support** - Used to invoke Lamdba functions.

This tutorial uses the DynamoDB and Amazon SNS services. The **lambda-support** role has to have policies that enable it to invoke these services from a Lambda function.

#### To create an IAM role

1. Open the AWS Management Console. When the page loads, enter **IAM** in the search box, and then choose **IAM** to open the IAM console.

2. In the navigation pane, choose **Roles**, and on the **Roles** page, choose **Create Role**.

3. Choose **AWS service**, and then choose **Lambda**.

![AWS Tracking Application](images/pic1.png)

4. Choose **Permissions**.

5. Search for **AWSLambdaBasicExecutionRole**.

6. Choose **Next Tags**.

7. Choose **Review**.

8. Name the role **lambda-support**.

![AWS Tracking Application](images/pic2.png)

9. Choose **Create role**.

10. Choose **lambda-support** to view the overview page.

11. Choose **Attach Policies**.

12. Search for **AmazonDynamoDBFullAccess**, and then choose **Attach policy**.

13. Search for **AmazonSNSFullAccess**, and then choose **Attach policy**. When you're done, you can see the permissions.

![AWS Tracking Application](images/pic3.png)

## Create an IntelliJ project named LambdaCronFunctions

1. In the IntelliJ IDE, choose **File**, **New**, **Project**.

2. In the **New Project** dialog box, choose **Maven**, and then choose **Next**.

3. For **GroupId**, enter **LambdaCronFunctions**.

4. For **ArtifactId**, enter **LambdaCronFunctions**.

5. Choose **Next**.

6. Choose **Finish**.

## Add the POM dependencies to your project

At this point, you have a new project named **LambdaCronFunctions**.

![AWS Tracking Application](images/pomlam.png)

The pom.xml file looks like the following.

```xml
   <?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>LambdaCronFunctions</groupId>
   <artifactId>LambdaCronFunctions</artifactId>
   <version>1.0-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>java-basic-function</name>
   <properties>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <maven.compiler.source>1.8</maven.compiler.source>
     <maven.compiler.target>1.8</maven.compiler.target>
   </properties>
   <dependencies>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-lambda-java-core</artifactId>
        <version>1.2.1</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.9</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.17.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.17.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j18-impl</artifactId>
        <version>2.17.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1.1</version>
    </dependency>
    <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>dynamodb-enhanced</artifactId>
        <version>2.17.110</version>
    </dependency>
    <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>dynamodb</artifactId>
        <version>2.17.110</version>
    </dependency>
    <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>sns</artifactId>
        <version>2.17.110</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M5</version>
        <type>maven-plugin</type>
    </dependency>
  </dependencies>
  <build>
    <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.2.2</version>
            <configuration>
                <createDependencyReducedPom>false</createDependencyReducedPom>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
    </build>
   </project>
```

## Create a Lambda function by using the AWS Lambda runtime Java API

Use the AWS Lambda runtime Java API to create the Java class that defines the Lamdba function. In this example, there is one Java class for the Lambda function and two extra classes required for this use case. The following figure shows the Java classes in the project. Notice that all Java classes are located in a package named **com.aws.example**.

![AWS Tracking Application](images/lampro1.png)

Create these Java classes:

+ **Handler** - used as the Lambda function that performs the use case described in this AWS tutorial. The application logic that's executed is located in the **handleRequest** method.
+ **ScanEmployees** - uses the Amazon DynamoDB Java V2 API to scan the **Employee** table using an **Expression** object. This class also uses the Amazon Simple Notification Service (Amazon SNS) Java V2 API to send a message to an employee.
+ **Employee** - a Java class that is used with the DynamoDB Enhanced client. The fields in this class match the columns in the **Employee** table.

### Handler class

This Java code represents the **Handler** class. The class creates a **ScanEmployees** object and invokes the **sendEmployeMessage** method. Notice that you can log messages to Amazon CloudWatch logs by using a **LambdaLogger** object.

```java
    package com.aws.example;

    import com.amazonaws.services.lambda.runtime.Context;
    import com.amazonaws.services.lambda.runtime.LambdaLogger;

    /**
    *  This is the entry point for the Lambda function
    */

    public class Handler {

     public Void handleRequest(Context context) {
        LambdaLogger logger = context.getLogger();
        ScanEmployees scanEmployees = new ScanEmployees();
       Boolean ans =  scanEmployees.sendEmployeMessage();
        if (ans)
            logger.log("Messages sent: " + ans);
        return null;
    }
}
```

### ScanEmployees class
The **ScanEmployees** class uses both Amazon DynamoDB Java V2 API and the Amazon SNS Java V2 API. In the following code example, notice the use of an **Expression** object. This object is used to return employees that have a start date one year ago. For each employee returned, a text message is sent using the **SnsClient** object's **publish** method.

```java
     package com.aws.example;

     import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
     import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
     import software.amazon.awssdk.enhanced.dynamodb.Expression;
     import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
     import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest;
     import software.amazon.awssdk.regions.Region;
     import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
     import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
     import software.amazon.awssdk.services.sns.SnsClient;
     import software.amazon.awssdk.services.sns.model.PublishRequest;
     import software.amazon.awssdk.services.sns.model.SnsException;
     import java.text.DateFormat;
     import java.text.SimpleDateFormat;
     import java.time.LocalDateTime;
     import java.time.ZoneId;
     import java.time.format.DateTimeFormatter;
     import java.util.*;

    /*
     Sends a text message to any employee that reached the one year anniversary mark
    */

    public class ScanEmployees {

       public Boolean sendEmployeMessage() {

         Boolean send = false;
         String myDate = getDate();

        Region region = Region.US_WEST_2;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        // Create a DynamoDbEnhancedClient and use the DynamoDbClient object
        DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
                .dynamoDbClient(ddb)
                .build();

        // Create a DynamoDbTable object based on Employee
        DynamoDbTable<Employee> table = enhancedClient.table("Employee", TableSchema.fromBean(Employee.class));

        try {
            AttributeValue attVal = AttributeValue.builder()
                .s(myDate)
                .build();

            // Get only items in the Employee table that match the date
            Map<String, AttributeValue> myMap = new HashMap<>();
            myMap.put(":val1", attVal);

            Map<String, String> myExMap = new HashMap<>();
            myExMap.put("#startDate", "startDate");

            Expression expression = Expression.builder()
                .expressionValues(myMap)
                .expressionNames(myExMap)
                .expression("#startDate = :val1")
                .build();

            ScanEnhancedRequest enhancedRequest = ScanEnhancedRequest.builder()
                .filterExpression(expression)
                .limit(15) // you can increase this value
                .build();

            // Get items in the Employee table
            Iterator<Employee> employees = table.scan(enhancedRequest).items().iterator();

            while (employees.hasNext()) {
                Employee employee = employees.next();
                String first = employee.getFirst();
                String phone = employee.getPhone();

                // Send an anniversary message!
                sentTextMessage(first, phone);
                send = true;
            }
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return send;
      }

    // Use the Amazon SNS Service to send a text message
    private void sentTextMessage(String first, String phone) {

        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_WEST_2)
                .build();
        String message = first +" happy one year anniversary. We are very happy that you have been working here for a year! ";

        try {
            PublishRequest request = PublishRequest.builder()
                    .message(message)
                    .phoneNumber(phone)
                    .build();

            snsClient.publish(request);
        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public String getDate() {

        String DATE_FORMAT = "yyyy-MM-dd";
        DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        DateTimeFormatter dateFormat8 = DateTimeFormatter.ofPattern(DATE_FORMAT);

        Date currentDate = new Date();
        System.out.println("date : " + dateFormat.format(currentDate));
        LocalDateTime localDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        System.out.println("localDateTime : " + dateFormat8.format(localDateTime));

        localDateTime = localDateTime.minusYears(1);
        String ann = dateFormat8.format(localDateTime);
        return ann;
     }
    }
```

### Employee class

The **Employee** class is used with the DynamoDB enhanced client and maps the **Employee** data members to items in the **Employee** table. Notice that this class uses the **@DynamoDbBean** annotation.

```java
     package com.aws.example;

     import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
     import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
     import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;

    @DynamoDbBean
    public class Employee {

     private String Id;
     private String first;
     private String phone;
     private String startDate;

     public void setId(String id) {
        this.Id = id;
     }

     @DynamoDbPartitionKey
     public String getId() {
        return this.Id;
     }

     public void setStartDate(String startDate) {
        this.startDate = startDate;
     }

     @DynamoDbSortKey
     public String getStartDate() {
        return this.startDate;
     }

     public void setPhone(String phone) {
        this.phone = phone;
     }

    public String getPhone() {
        return this.phone;
     }

     public void setFirst(String first) {
        this.first = first;
     }

     public String getFirst() {
        return this.first;
     }
    }
```

## Package the project that contains the Lambda functions

Package up the project into a .jar (JAR) file that you can deploy as a Lambda function by using the following Maven command.

    mvn package

The JAR file is located in the **target** folder (which is a child folder of the project folder).

![AWS Tracking Application](images/lamdeploy.png)

**Note**: Notice the use of the **maven-shade-plugin** in the project's POM file. This plugin is responsible for creating a JAR that contains the required dependencies. If you attempt to package up the project without this plugin, the required dependences are not included in the JAR file and you will encounter a **ClassNotFoundException**.

## Deploy the Lambda function

1. Open the Lambda console at https://us-east-1.console.aws.amazon.com/lambda/home.

2. Choose **Create Function**.

3. Choose **Author from scratch**.

4. In the **Basic** information section, enter **cron** as the name.

5. In the **Runtime**, choose **Java 8**.

6. Choose **Use an existing role**, and then choose **lambda-support** (the IAM role that you created).

![AWS Tracking Application](images/pic10.png)

7. Choose **Create function**.

8. For **Code entry type**, choose **Upload a .zip or .jar file**.

9. Choose **Upload**, and then browse to the JAR file that you created.

10. For **Handler**, enter the fully qualified name of the function, for example, **com.aws.example.Handler::handleRequest** (**com.aws.example.Handler** specifies the package and class followed by :: and method name).

11. Choose **Save.**

## Configure Amazon API Gateway to invoke the Lambda function

You can use the Amazon Gateway API console to create a Rest endpoint for the Lambda function. Once done, you are able to invoke the Lambda function using a Restful call.

1. Sign in to the Amazon API Gateway console at https://console.aws.amazon.com/apigateway.

2. Under Rest API, choose **Build**.

![AWS Tracking Application](images/picRest.png)

3. Select **New API**.

![AWS Tracking Application](images/PicNewAPI.png)

4. Specify **Employee** as the API name and provide a description.

![AWS Tracking Application](images/picEmployeeAPI.png)

5. Choose **Create API**.

6. Choose **Resources** under the **Employee** section.

![AWS Tracking Application](images/picResources.png)

7. From the **Actions** dropdown, choose **Create Resources**.

8. In the name field, specify **employees**.

9. Choose **Create Resources**.

![AWS Tracking Application](images/picCreateResources.png)

10. Choose **/employees** and then select GET from the drop down. Choose the checkmark icon.

![AWS Tracking Application](images/picGet.png)

11. Choose **Lambda function** and enter **cron** as the Lambda function name. Choose **Save**.

![AWS Tracking Application](images/picLambda.png)

12. Choose **OK**.

### Test the Amazon API Gateway method

At this point in the tutorial, you can test the Amazon API Gateway method that invokes the **cron** Lambda function. To test the method, choose **Test**, as shown in the following illustration.

![AWS Tracking Application](images/picTest.png)

Once the Lambda function is invoked, you can view the log file to see a successful message.

![AWS Tracking Application](images/picLogs.png)

### Deploying the API

After the test is successful, you can deploy the method from the AWS Management Console.

1. Choose **Get**.

![AWS Tracking Application](images/picGetDeploy.png)

2. From the **Actions** dropdown, select **Deploy API**.

3. Fill in the Deploy API form and choose **Deploy**.

![AWS Tracking Application](images/picDeployMethod.png)

4. Notice that a URL s displayed.

![AWS Tracking Application](images/picURL.png)

5.	Choose **Save Changes**.

6. Choose **Get** again and notice that the URL changes. This is the invocation URL that you can use to invoke the Lambda function.

![AWS Tracking Application](images/picURL2.png)

### Next steps
Congratulations, you have created an AWS Lambda function that is invoked by using an Amazon Gateway API method. As stated at the beginning of this tutorial, be sure to terminate all of the resources you created while going through this tutorial to ensure that you're not charged.

For more AWS multiservice examples, see
[usecases](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/usecases).


text:
import Form from 'react-bootstrap/Form';

function SwitchExample() {
  return (
    <Form>
      <Form.Check // prettier-ignore
        type="switch"
        id="custom-switch"
        label="Check this switch"
      />
      <Form.Check // prettier-ignore
        disabled
        type="switch"
        label="disabled switch"
        id="disabled-custom-switch"
      />
    </Form>
  );
}

export default SwitchExample;


text:
#include <click/config.h>
#include "udprewriter.hh"
#include <click/args.hh>
#include <click/straccum.hh>
#include <click/error.hh>
#include <click/timer.hh>
#include <clicknet/tcp.h>
#include <clicknet/udp.h>
CLICK_DECLS

void
UDPRewriter::UDPFlow::apply(WritablePacket *p, bool direction, unsigned annos)
{
    assert(p->has_network_header());
    click_ip *iph = p->ip_header();

    // IP header
    const IPFlowID &revflow = _e[!direction].flowid();
    iph->ip_src = revflow.daddr();
    iph->ip_dst = revflow.saddr();
    if (annos & 1)
	p->set_dst_ip_anno(revflow.saddr());
    if (direction && (annos & 2))
	p->set_anno_u8(annos >> 2, _reply_anno);
    update_csum(&iph->ip_sum, direction, _ip_csum_delta);

    // end if not first fragment
    if (!IP_FIRSTFRAG(iph))
	return;

    // TCP/UDP header
    click_udp *udph = p->udp_header();
    udph->uh_sport = revflow.dport(); // TCP ports in the same place
    udph->uh_dport = revflow.sport();
    if (iph->ip_p == IP_PROTO_TCP) {
	if (p->transport_length() >= 18)
	    update_csum(&reinterpret_cast<click_tcp *>(udph)->th_sum, direction, _udp_csum_delta);
    } else if (iph->ip_p == IP_PROTO_UDP) {
	if (p->transport_length() >= 8 && udph->uh_sum)
	    // 0 checksum is no checksum
	    update_csum(&udph->uh_sum, direction, _udp_csum_delta);
    }

    // track connection state
    if (direction)
	_tflags |= 1;
    if (_tflags < 6)
	_tflags += 2;
}

UDPRewriter::UDPRewriter()
{
}

UDPRewriter::~UDPRewriter()
{
}

void *
UDPRewriter::cast(const char *n)
{
    if (strcmp(n, "IPRewriterBase") == 0)
	return (IPRewriterBase *)this;
    else if (strcmp(n, "UDPRewriter") == 0)
	return (UDPRewriter *)this;
    else
	return 0;
}

int
UDPRewriter::configure(Vector<String> &conf, ErrorHandler *errh)
{
    bool dst_anno = true, has_reply_anno = false,
	has_udp_streaming_timeout, has_streaming_timeout;
    int reply_anno;
    _timeouts[0] = 300;		// 5 minutes

    if (Args(this, errh).bind(conf)
	.read("DST_ANNO", dst_anno)
	.read("REPLY_ANNO", AnnoArg(1), reply_anno).read_status(has_reply_anno)
	.read("UDP_TIMEOUT", SecondsArg(), _timeouts[0])
	.read("TIMEOUT", SecondsArg(), _timeouts[0])
	.read("UDP_STREAMING_TIMEOUT", SecondsArg(), _udp_streaming_timeout).read_status(has_udp_streaming_timeout)
	.read("STREAMING_TIMEOUT", SecondsArg(), _udp_streaming_timeout).read_status(has_streaming_timeout)
	.read("UDP_GUARANTEE", SecondsArg(), _timeouts[1])
	.consume() < 0)
	return -1;

    _annos = (dst_anno ? 1 : 0) + (has_reply_anno ? 2 + (reply_anno << 2) : 0);
    if (!has_udp_streaming_timeout && !has_streaming_timeout)
	_udp_streaming_timeout = _timeouts[0];
    _udp_streaming_timeout *= CLICK_HZ; // IPRewriterBase handles the others

    return IPRewriterBase::configure(conf, errh);
}

IPRewriterEntry *
UDPRewriter::add_flow(int ip_p, const IPFlowID &flowid,
		      const IPFlowID &rewritten_flowid, int input)
{
    void *data;
    if (!(data = _allocator.allocate()))
	return 0;

    UDPFlow *flow = new(data) UDPFlow
	(&_input_specs[input], flowid, rewritten_flowid, ip_p,
	 !!_timeouts[1], click_jiffies() + relevant_timeout(_timeouts));

    return store_flow(flow, input, _map);
}

void
UDPRewriter::push(int port, Packet *p_in)
{
    WritablePacket *p = p_in->uniqueify();
    if (!p)
	return;
    click_ip *iph = p->ip_header();

    // handle non-TCP and non-first fragments
    int ip_p = iph->ip_p;
    if ((ip_p != IP_PROTO_TCP && ip_p != IP_PROTO_UDP && ip_p != IP_PROTO_DCCP)
	|| !IP_FIRSTFRAG(iph)
	|| p->transport_length() < 8) {
	const IPRewriterInput &is = _input_specs[port];
	if (is.kind == IPRewriterInput::i_nochange)
	    output(is.foutput).push(p);
	else
	    p->kill();
	return;
    }

    IPFlowID flowid(p);
    IPRewriterEntry *m = _map.get(flowid);

    if (!m) {			// create new mapping
	IPRewriterInput &is = _input_specs.at_u(port);
	IPFlowID rewritten_flowid = IPFlowID::uninitialized_t();
	int result = is.rewrite_flowid(flowid, rewritten_flowid, p);
	if (result == rw_addmap)
	    m = UDPRewriter::add_flow(ip_p, flowid, rewritten_flowid, port);
	if (!m) {
	    checked_output_push(result, p);
	    return;
	} else if (_annos & 2)
	    m->flow()->set_reply_anno(p->anno_u8(_annos >> 2));
    }

    UDPFlow *mf = static_cast<UDPFlow *>(m->flow());
    mf->apply(p, m->direction(), _annos);

    click_jiffies_t now_j = click_jiffies();
    if (_timeouts[1])
	mf->change_expiry(_heap, true, now_j + _timeouts[1]);
    else
	mf->change_expiry(_heap, false, now_j + udp_flow_timeout(mf));

    output(m->output()).push(p);
}

String
UDPRewriter::dump_mappings_handler(Element *e, void *)
{
    UDPRewriter *rw = (UDPRewriter *)e;
    click_jiffies_t now = click_jiffies();
    StringAccum sa;
    for (Map::iterator iter = rw->_map.begin(); iter.live(); ++iter) {
	iter->flow()->unparse(sa, iter->direction(), now);
	sa << '\n';
    }
    return sa.take_string();
}

void
UDPRewriter::add_handlers()
{
    add_read_handler("mappings", dump_mappings_handler, 0);
    add_rewriter_handlers(true);
}

CLICK_ENDDECLS
ELEMENT_REQUIRES(IPRewriterBase)
EXPORT_ELEMENT(UDPRewriter)


text:
package org.ovirt.engine.ui.common.widget.table.header;

import java.util.HashSet;
import java.util.Set;

import org.ovirt.engine.ui.common.widget.table.cell.CheckboxCell;
import org.ovirt.engine.ui.common.widget.tooltip.TooltipMixin;
import org.ovirt.engine.ui.uicompat.external.StringUtils;

import com.google.gwt.cell.client.Cell.Context;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.BrowserEvents;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;

public abstract class AbstractCheckboxHeader extends AbstractHeader<Boolean> {
    private static final String CHECKBOX_HEADER_STYLE = "position: relative; top: 3px"; //$NON-NLS-1$

    private static final SafeHtml INPUT_CHECKED_DISABLED = SafeHtmlUtils.fromSafeConstant(
            "<input type=\"checkbox\" disabled=\"\" tabindex=\"-1\" tabindex=\"-1\" checked style=\"" + CHECKBOX_HEADER_STYLE + "\"/>"); //$NON-NLS-1$ $NON-NLS-2$

    private static final SafeHtml INPUT_UNCHECKED_DISABLED = SafeHtmlUtils.fromSafeConstant(
            "<input type=\"checkbox\" disabled=\"\" tabindex=\"-1\" style=\"" + CHECKBOX_HEADER_STYLE + "\"/>"); //$NON-NLS-1$ $NON-NLS-2$

    public AbstractCheckboxHeader() {
        super(new CheckboxCell(true, false) {

            @Override
            public Set<String> getConsumedEvents() {  // override this to add MOUSEMOVE for mouse cursor changes
                Set<String> set = new HashSet<String>();
                TooltipMixin.addTooltipsEvents(set);
                set.add(BrowserEvents.CHANGE);
                set.add(BrowserEvents.KEYDOWN);
                set.add(BrowserEvents.MOUSEMOVE);
                return set;
            }

            @Override
            public void render(Context context, Boolean value, SafeHtmlBuilder sb, String id) {
                super.render(context, value, sb, id);
            }
        });

        setUpdater(new ValueUpdater<Boolean>() {
            @Override
            public void update(Boolean value) {
                selectionChanged(value);
            }
        });

        if (getTooltip() != null) {
            ((CheckboxCell) getCell()).setTooltip(getTooltip());
        }

        if (getLabel() != null) {
            if (SafeHtmlUtils.EMPTY_SAFE_HTML.equals(getTooltip())) {
                ((CheckboxCell) getCell()).setLabel(SafeHtmlUtils.fromString(getLabel()));
            } else {
                ((CheckboxCell) getCell()).setLabel(templates.hasTooltip(SafeHtmlUtils.fromString(getLabel())));
            }
        }

        ((CheckboxCell) getCell()).setAdditionalStyles(CHECKBOX_HEADER_STYLE);
    }

    /**
     * Override to set the value of the label.
     * @return A string representing the label, or null if not defined.
     */
    public String getLabel() {
        return null;
    }

    @Override
    public void render(Context context, SafeHtmlBuilder sb) {
        if (!isEnabled()) {
            if (getValue()) {
                sb.append(INPUT_CHECKED_DISABLED);
            } else {
                sb.append(INPUT_UNCHECKED_DISABLED);
            }
            if (getLabel() != null && !StringUtils.isEmpty(getLabel())) {
                sb.append(SafeHtmlUtils.fromString(getLabel()));
            }
        } else {
            super.render(context, sb);
        }
    }

    abstract protected void selectionChanged(Boolean value);

    abstract public boolean isEnabled();

    @Override
    public SafeHtml getTooltip() {
        return SafeHtmlUtils.EMPTY_SAFE_HTML;
    };

}


text:
using Newtonsoft.Json;
using RemoteExecute.Domain;
using RemoteExecute.Models;
using RemoteExecute.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RemoteExecute.Controllers
{
    public class HomeController : Controller
    {
        private readonly ICommandSetRepository commandRepository;
        private readonly IServerRepository serverRepository;
        private readonly IExecutionEngine executionEngine;

        public HomeController(ICommandSetRepository commandRepository, IServerRepository serverRepository,
            IExecutionEngine executionEngine)
        {
            this.commandRepository = commandRepository;
            this.serverRepository = serverRepository;
            this.executionEngine = executionEngine;
        }

        // GET: Home
        public ActionResult Index()
        {
            CommandSetSummaryViewModel vm = new CommandSetSummaryViewModel();
            vm.Commands = commandRepository.GetCommandSets();

            return View(vm);
        }

        public ActionResult New()
        {
            IEnumerable<Server> servers = serverRepository.GetServers();

            CommandEditViewModel model = new CommandEditViewModel();
            model.IsNewCommand = true;
            model.Id = null;
            model.Name = null;
            model.Commands = "undefined";
            model.CommandTypes = JavaScriptHelper.Serialize(servers);

            return View("Edit", model);
        }

        public ActionResult Edit(int id)
        {
            CommandSet commandSet = commandRepository.GetCommandSet(id);
            IEnumerable<Server> servers = serverRepository.GetServers();

            CommandEditViewModel model = new CommandEditViewModel();
            model.IsNewCommand = false;
            model.Id = id;
            model.Name = commandSet.Name;
            model.Commands = JsonConvert.SerializeObject(commandSet.Commands);
            model.CommandTypes = JavaScriptHelper.Serialize(servers);

            return View(model);
        }

        [HttpPost]
        public ActionResult Save(bool isNewCommand, int? id, string name, IEnumerable<Command> commands)
        {
            if (isNewCommand)
            {
                if (!string.IsNullOrEmpty(name))
                {
                    commandRepository.AddCommandSet(new CommandSet() { Name = name, Commands = commands });
                    return Json("Commandset created successfully.");
                }
            }
            else
            {
                commandRepository.UpdateCommandSet(id.Value, name, commands);
                return Json("Commandset updated successfully.");
            }

            return null;
        }

        [HttpPost]
        public ActionResult Execute(int id)
        {
            //return executionEngine.Execute(;
            return null;
        }
    }
}


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/display/overscan_calibrator.h"
#include "ash/display/cros_display_config.h"

#include "ash/shell.h"
#include "ash/test/ash_test_base.h"
#include "base/callback_helpers.h"
#include "base/strings/stringprintf.h"
#include "ui/display/manager/display_manager.h"
#include "ui/display/manager/managed_display_info.h"

namespace ash {

class OverscanCalibratorTest : public AshTestBase {
 public:
  OverscanCalibratorTest() = default;
  ~OverscanCalibratorTest() override = default;
  OverscanCalibratorTest(OverscanCalibratorTest&) = delete;
  OverscanCalibratorTest& operator=(const OverscanCalibratorTest&) = delete;

  OverscanCalibrator* StartCalibration(const std::string& id) {
    Shell::Get()->cros_display_config()->OverscanCalibration(
        id, mojom::DisplayConfigOperation::kStart,
        gfx::Insets(0, 0, 0, 0) /* not used */, base::DoNothing());
    return Shell::Get()->cros_display_config()->GetOverscanCalibrator(id);
  }
};

TEST_F(OverscanCalibratorTest, Rotation) {
  auto* display_manager = Shell::Get()->display_manager();

  int64_t display_id = display::Screen::GetScreen()->GetPrimaryDisplay().id();
  std::string id_str = base::StringPrintf("%" PRId64, display_id);

  auto* calibrator = StartCalibration(id_str);
  calibrator->UpdateInsets(gfx::Insets(100, 5, 10, 15));
  calibrator->Commit();
  display::ManagedDisplayInfo info =
      display_manager->GetDisplayInfo(display_id);
  EXPECT_EQ(gfx::Insets(100, 5, 10, 15), info.overscan_insets_in_dip());

  display_manager->SetDisplayRotation(display_id,
                                      display::Display::Rotation::ROTATE_90,
                                      display::Display::RotationSource::USER);
  EXPECT_EQ(gfx::Size(490, 780),
            display::Screen::GetScreen()->GetPrimaryDisplay().size());

  calibrator = StartCalibration(id_str);
  // The insets will be rotated and applied in the host coordinates.
  gfx::Insets insets = calibrator->insets();
  insets.set_left(105);
  insets.set_top(0);
  calibrator->UpdateInsets(insets);
  calibrator->Commit();

  info = display_manager->GetDisplayInfo(display_id);
  EXPECT_EQ(gfx::Insets(105, 5, 10, 0), info.overscan_insets_in_dip());
}

}  // namespace ash


text:
All notable changes to this project will be documented in this file.

## v1.1.0
### Updated

* Require Swift 5.1 and up.
* Require iOS 11 or newer.

## v1.0.2
### Added

* Added `Path.isFile()`.

## v1.0.1
### Fixed

* Fixed `Path.join()` not producing the expected result when passing an absolute path as first component.

## v1.0.0

* Initial release.


text:
package com.forward.exceptionHandler.util;
public class BaseException extends RuntimeException {

	/**
	 *
	 */
	private static final long serialVersionUID = -8411382662472806859L;

    private String descr;
	public String getDescr() {
		return descr;
	}
	public BaseException(String descr){
		super(400+"");
		this.descr=descr;
	}
	public BaseException(String message,String discr)
	{
		super(message);
		this.descr=discr;
	}

}


text:
package org.openehealth.ipf.commons.ihe.ws.cxf.databinding.plainxml;

import java.util.Collection;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.validation.Schema;

import org.apache.cxf.databinding.DataReader;
import org.apache.cxf.message.Attachment;
import org.apache.cxf.service.model.MessagePartInfo;

/**
 * Fake data reader which reads in the whole XML stream and returns
 * a null value instead of the expected POJO.
 * @author Dmytro Rud
 */
public class PlainXmlReader implements DataReader<XMLStreamReader>{

    @Override
    public Object read(XMLStreamReader reader) {
        try {
            while(reader.hasNext()) {
                reader.next();
            }
        } catch (XMLStreamException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public Object read(MessagePartInfo part, XMLStreamReader reader) {
        return read(reader);
    }

    @Override
    public Object read(QName elementQName, XMLStreamReader reader, Class type) {
        return read(reader);
    }

    @Override
    public void setAttachments(Collection<Attachment> attachments) {
        // nop
    }

    @Override
    public void setProperty(String prop, Object value) {
        // nop
    }

    @Override
    public void setSchema(Schema s) {
        // nop
    }
}


text:
<!DOCTYPE html>

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

  <link type="application/atom+xml" rel="alternate" href="/feed.xml" title="Hi!" />

<title>Hi!</title>
<meta name="generator" content="Jekyll v4.2.2" />
<meta property="og:title" content="Hi!" />
<meta name="author" content="Riccardo Graziosi" />
<meta property="og:locale" content="en_US" />
<link rel="canonical" href="/404.html" />
<meta property="og:url" content="/404.html" />
<meta property="og:site_name" content="Hi!" />
<meta property="og:type" content="website" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:title" content="Hi!" />

  <link rel="shortcut icon" type="image/x-icon" href="/./logo.png" />
  <link rel="stylesheet" href="/assets/css/main.css" />

404

Page not found :(

The requested page could not be found.


text:
void print_vprintf (AP_HAL::Print *s, unsigned char in_progmem, const char *fmt, va_list ap);

#endif //__AP_HAL_AVR_UTILITY_VPRINTF_H__


text:
/* pinmux_quark_mcu.h - pinmux operation for generic Quark MCU boards */

/*
 * Copyright (c) 2016 Intel Corporation
 *
 * SPDX-License-Identifier: Apache-2.0
 */

// KID 20170727
// PINMUX_PULLUP_OFFSET: 0x00
#define PINMUX_PULLUP_OFFSET   0x00
#define PINMUX_SLEW_OFFSET     0x10
#define PINMUX_INPUT_OFFSET    0x20
// KID 20170727
// PINMUX_SELECT_OFFSET: 0x30
#define PINMUX_SELECT_OFFSET   0x30

// KID 20170727
// base: 0xb0800900, 0
// PINMUX_SELECT_OFFSET: 0x30
//
// #define PINMUX_SELECT_REGISTER(0xb0800900, 0):
// (0xb0800900 + 0x30 + (0 << 2))
#define PINMUX_SELECT_REGISTER(base, reg_offset) \
	(base + PINMUX_SELECT_OFFSET + (reg_offset << 2))

/*
 * A little decyphering of what is going on here:
 *
 * Each pinmux register rperesents a bank of 16 pins, 2 bits per pin for a total
 * of four possible settings per pin.
 *
 * The first argument to the macro is name of the u32_t's that is being used
 * to contain the bit patterns for all the configuration registers.  The pin
 * number divided by 16 selects the correct register bank based on the pin
 * number.
 *
 * The pin number % 16 * 2 selects the position within the register bank for the
 * bits controlling the pin.
 *
 * All but the lower two bits of the config values are masked off to ensure
 * that we don't inadvertently affect other pins in the register bank.
 */
// KID 20170727
// PINMUX_FUNC_B: 1
//
// PIN_CONFIG(mux_config, 0, 1):
// (mux_config[((0) / 16)] |= ((0x3 & (1)) << (((0) % 16) * 2)))
#define PIN_CONFIG(A, _pin, _func) \
	(A[((_pin) / 16)] |= ((0x3 & (_func)) << (((_pin) % 16) * 2)))

// KID 20170727
// base_address: 0xb0800900, 104, PINMUX_PULLUP_ENABLE: 0x1
static inline int _quark_mcu_set_mux(u32_t base, u32_t pin, u8_t func)
{
	/*
	 * the registers are 32-bit wide, but each pin requires 1 bit
	 * to set the input enable bit.
	 */
	// pin:104
	u32_t register_offset = (pin / 32) * 4;
	// register_offset: 12

	/*
	 * Now figure out what is the full address for the register
	 * we are looking for.  Add the base register to the register_mask
	 */
	// base: 0xb0800900, register_offset: 12
	volatile u32_t *mux_register = (u32_t *)(base + register_offset);
	// mux_register: 0xb0800948

	/*
	 * Finally grab the pin offset within the register
	 */
	// pin:104
	u32_t pin_offset = pin % 32;
	// pin_offset: 8

	/*
	 * MAGIC NUMBER: 0x1 is used as the pullup is a single bit in a
	 * 32-bit register.
	 */
	// mux_register: 0xb0800948 pin_offset: 8, func: 0x1
	(*(mux_register)) = ((*(mux_register)) & ~(0x1 << pin_offset)) |
		((func & 0x01) << pin_offset);
	// *(0xb0800948):  0x100

	return 0;
	// return 0
}


text:
class Solution(object):

    # def __init__(self):
    #     self.label_map = {}

    # def cloneGraph(self, node):
    #     """
    #     :type node: UndirectedGraphNode
    #     :rtype: UndirectedGraphNode
    #     """
    #     # DFS
    #     if node is None:
    #         return None
    #     res = UndirectedGraphNode(node.label)
    #     self.label_map[node.label] = res
    #     for ne in node.neighbors:
    #         if ne.label not in self.label_map:
    #             res.neighbors.append(self.cloneGraph(ne))
    #         else:
    #             res.neighbors.append(self.label_map[ne.label])
    #     return res

    def cloneGraph(self, node):
        # BFS
        if node is None:
            return None
        label_map = {}
        queue = [node]
        graphCopy = UndirectedGraphNode(node.label)
        label_map[node.label] = graphCopy
        while len(queue) > 0:
            curr = queue.pop(0)
            for ne in curr.neighbors:
                if ne.label in label_map:
                    label_map[curr.label].neighbors.append(label_map[ne.label])
                else:
                    neighborCopy = UndirectedGraphNode(ne.label)
                    label_map[curr.label].neighbors.append(neighborCopy)
                    label_map[ne.label] = neighborCopy
                    queue.append(ne)
        return graphCopy


text:
<?php

namespace Krovitch\UnramalakBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class MediaType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('file');
        $builder->add('editor.save', 'submit');
        $builder->add('editor.cancel', 'reset');
        //$builder->add('avatar', 'file', array('data_class' => null));
        //$builder->add('race', 'entity', array('class' => 'UnramalakBundle:Race', 'property' => 'name'));

        return $builder;
    }

    /**
     * Returns the name of this type.
     *
     * @return string The name of this type
     */
    public function getName()
    {
        return 'Hero';
    }
}


text:
package org.apache.predictionio.data.store

import org.apache.predictionio.data.storage.Storage
import grizzled.slf4j.Logger

private[predictionio] object Common {

  @transient lazy val logger = Logger[this.type]
  @transient lazy private val appsDb = Storage.getMetaDataApps()
  @transient lazy private val channelsDb = Storage.getMetaDataChannels()

  /* throw exception if invalid app name or channel name */
  def appNameToId(appName: String, channelName: Option[String]): (Int, Option[Int]) = {
    val appOpt = appsDb.getByName(appName)

    appOpt.map { app =>
      val channelMap: Map[String, Int] = channelsDb.getByAppid(app.id)
        .map(c => (c.name, c.id)).toMap

      val channelId: Option[Int] = channelName.map { ch =>
        if (channelMap.contains(ch)) {
          channelMap(ch)
        } else {
          logger.error(s"Invalid channel name ${ch}.")
          throw new IllegalArgumentException(s"Invalid channel name ${ch}.")
        }
      }

      (app.id, channelId)
    }.getOrElse {
      logger.error(s"Invalid app name ${appName}")
      throw new IllegalArgumentException(s"Invalid app name ${appName}")
    }
  }
}


text:
package org.apache.isis.applib.profiles;

import java.util.Locale;
import java.util.TimeZone;

public interface Localization {

    Locale getLocale();

    TimeZone getTimeZone();

}


text:
package io.crate.expression.scalar.conditional;

import io.crate.data.Input;
import io.crate.expression.scalar.ScalarFunctionModule;
import io.crate.metadata.NodeContext;
import io.crate.metadata.Scalar;
import io.crate.metadata.TransactionContext;
import io.crate.metadata.functions.BoundSignature;
import io.crate.metadata.functions.Signature;

import static io.crate.metadata.functions.TypeVariableConstraint.typeVariable;
import static io.crate.types.TypeSignature.parseTypeSignature;

public class CoalesceFunction extends Scalar<Object, Object> {

    public static void register(ScalarFunctionModule module) {
        module.register(
            Signature
                .scalar(
                    NAME,
                    parseTypeSignature("E"),
                    parseTypeSignature("E"))
                .withVariableArity()
                .withTypeVariableConstraints(typeVariable("E")),
            CoalesceFunction::new
        );
    }

    public static final String NAME = "coalesce";

    private final Signature signature;
    private final BoundSignature boundSignature;

    private CoalesceFunction(Signature signature, BoundSignature boundSignature) {
        this.signature = signature;
        this.boundSignature = boundSignature;
    }

    @Override
    public Signature signature() {
        return signature;
    }

    @Override
    public BoundSignature boundSignature() {
        return boundSignature;
    }

    @Override
    public Object evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object>[] args) {
        for (Input<?> input : args) {
            Object value = input.value();
            if (value != null) {
                return value;
            }
        }
        return null;
    }
}


text:
import arrayToObj from 'array-to-obj';

const selectMetasURL = config => {
  const {
    metas
  } = config;
  return metas;
};

const selectProfilesURL = config => {
  const {
    profiles
  } = config;
  return profiles;
};

export default async ({config, dom, jQuery}) => {
  const metasURL = selectMetasURL(config);
  const profilesURL = selectProfilesURL(config);

  if (!metasURL || !profilesURL) {
    console.warn('Unable to load the Social Profiles component without metas and profiles urls.');
  }

  const container = dom.select('#social-profiles');
  const template = dom.select('#social-item-template').content;

  try {
    const {getJSON} = jQuery;

    const responses = [
      getJSON({url: profilesURL}),
      getJSON({url: metasURL})
    ];

    const [profilesResponse, metasResponse] = await Promise.all(responses);
    const {result: {profiles: profilesArray = []} = {}} = profilesResponse;
    const {result: {metas: metasArray = []} = {}} = metasResponse;

    const {order, orderBy} = metasArray.find(meta => meta.key === 'socialProfilesOrder') || {};
    if (metasArray.length === 0 || !order || !orderBy) {
      throw new Error('Profile metadata not found.');
    }

    const profiles = arrayToObj(profilesArray, {key: orderBy});
    if (profilesArray.length === 0 || !profiles) {
      throw new Error('Profile data not found.');
    }

    const fragment = document.createDocumentFragment();
    order.forEach(key => {
      if (!profiles[key]) {
        return;
      }

      const content = template.cloneNode(true);
      const {
        displayName,
        href,
        icon
      } = profiles[key];

      const iconCss = icon.class.split(' ');
      content.querySelector('.social-item-icon').classList.add(...iconCss);

      const link = content.querySelector('.social-item-link');
      link.title = `Chris Vogt on ${displayName}`;
      link.href = href;

      fragment.append(document.importNode(content, true));
    });

    container.innerHTML = '';
    container.append(document.importNode(fragment, true));
  } catch (error) {
    console.warn('Error loading social profiles section', error);
    dom.select('#social').classList.add('hidden');
  }
};


text:
package org.freedesktop.DBus.Exceptions;

import nl.bennyjacobs.aapbridge.dbus.RemoteDbusException;

public class NotConnected extends RemoteDbusException {

	private static final long serialVersionUID = 6427249803292814162L;

	public NotConnected(String errString) {
		super(NotConnected.class.getName(), errString);
	}

}


text:
package org.springframework.social.facebook.api.impl;

import org.springframework.social.facebook.api.GraphApi;
import org.springframework.social.facebook.api.PagedList;
import org.springframework.social.facebook.api.Question;
import org.springframework.social.facebook.api.QuestionOperations;
import org.springframework.social.facebook.api.QuestionOption;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

class QuestionTemplate extends AbstractFacebookOperations implements QuestionOperations {

	private GraphApi graphApi;

	public QuestionTemplate(GraphApi graphApi, boolean isAuthorized) {
		super(isAuthorized);
		this.graphApi = graphApi;
	}

	public String askQuestion(String questionText) {
		requireAuthorization();
		MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>();
		data.set("question", questionText);
		return graphApi.publish("me", "questions", data);
	}

	public String addOption(String questionId, String optionText) {
		requireAuthorization();
		MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>();
		data.set("option", optionText);
		return graphApi.publish(questionId, "options", data);
	}

	public PagedList<Question> getQuestions() {
		return getQuestions("me");
	}

	public PagedList<Question> getQuestions(String userId) {
		requireAuthorization();
		return graphApi.fetchConnections(userId, "questions", Question.class);
	}

	public void deleteQuestion(String questionId) {
		requireAuthorization();
		graphApi.delete(questionId);
	}

	public Question getQuestion(String questionId) {
		requireAuthorization();
		return graphApi.fetchObject(questionId, Question.class);
	}

	public QuestionOption getOption(String optionId) {
		requireAuthorization();
		return graphApi.fetchObject(optionId, QuestionOption.class);
	}

	public PagedList<QuestionOption> getOptions(String questionId) {
		requireAuthorization();
		return graphApi.fetchConnections(questionId, "options", QuestionOption.class);
	}

	public void deleteOption(String optionId) {
		requireAuthorization();
		graphApi.delete(optionId);
	}

}


text:
import json

from nose.tools import assert_equal, assert_true, assert_false

from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

from desktop.lib.django_test_util import make_logged_in_client
from desktop.lib.test_utils import grant_access
from desktop.models import Directory, Document, Document2

from notebook.api import _historify

class TestNotebookApi(object):

  def setUp(self):
    self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False)
    self.client_not_me = make_logged_in_client(username="not_perm_user", groupname="default", recreate=True, is_superuser=False)

    self.user = User.objects.get(username="test")
    self.user_not_me = User.objects.get(username="not_perm_user")

    grant_access("test", "default", "notebook")
    grant_access("not_perm_user", "default", "notebook")

    self.notebook_json = """
      {
        "selectedSnippet": "hive",
        "showHistory": false,
        "description": "Test Hive Query",
        "name": "Test Hive Query",
        "sessions": [
            {
                "type": "hive",
                "properties": [],
                "id": null
            }
        ],
        "type": "query-hive",
        "id": 50010,
        "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement":"select * from web_logs","properties":{"settings":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from web_logs","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}],
        "uuid": "5982a274-de78-083c-2efc-74f53dce744c",
        "isSaved": false,
        "parentUuid": null
    }
    """

    self.notebook = json.loads(self.notebook_json)
    self.doc2 = Document2.objects.create(id=50010, name=self.notebook['name'], type=self.notebook['type'], owner=self.user)
    self.doc1 = Document.objects.link(self.doc2, owner=self.user, name=self.doc2.name,
                                      description=self.doc2.description, extra=self.doc2.type)

  def test_save_notebook(self):
    # Test that saving a new document with a new parent will set the parent_directory
    home_dir = Document2.objects.get_home_directory(self.user)
    assert_equal(home_dir.uuid, self.doc2.parent_directory.uuid)

    new_dir = Directory.objects.create(name='new_dir', owner=self.user, parent_directory=home_dir)
    notebook_cp = self.notebook.copy()
    notebook_cp.pop('id')
    notebook_cp['directoryUuid'] = new_dir.uuid
    notebook_json = json.dumps(notebook_cp)

    response = self.client.post(reverse('notebook:save_notebook'), {'notebook': notebook_json})
    data = json.loads(response.content)

    assert_equal(0, data['status'], data)
    doc = Document2.objects.get(pk=data['id'])
    assert_equal(new_dir.uuid, doc.parent_directory.uuid)

    # Test that saving a new document with a no parent will map it to its home dir
    notebook_json = """
      {
        "selectedSnippet": "hive",
        "showHistory": false,
        "description": "Test Hive Query",
        "name": "Test Hive Query",
        "sessions": [
            {
                "type": "hive",
                "properties": [],
                "id": null
            }
        ],
        "type": "query-hive",
        "id": null,
        "snippets": [],
        "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a"
    }
    """

    response = self.client.post(reverse('notebook:save_notebook'), {'notebook': notebook_json})
    data = json.loads(response.content)

    assert_equal(0, data['status'], data)
    doc = Document2.objects.get(pk=data['id'])
    assert_equal(Document2.objects.get_home_directory(self.user).uuid, doc.parent_directory.uuid)

  def test_historify(self):
    # Starts with no history
    assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count())
    assert_equal(1, Document.objects.filter(name__contains=self.notebook['name']).count())

    history_doc = _historify(self.notebook, self.user)

    assert_true(history_doc.id > 0)

    # Test that historify creates new Doc2 and linked Doc1
    assert_equal(1, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count())
    assert_equal(2, Document.objects.filter(name__contains=self.notebook['name']).count())

    # Historify again
    history_doc = _historify(self.notebook, self.user)

    assert_equal(2, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count())
    assert_equal(3, Document.objects.filter(name__contains=self.notebook['name']).count())

  def test_get_history(self):
    assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count())
    _historify(self.notebook, self.user)
    _historify(self.notebook, self.user)
    _historify(self.notebook, self.user)
    assert_equal(3, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count())

    # History should not return history objects that don't have the given doc type
    Document2.objects.create(name='Impala History', type='query-impala', data=self.notebook_json, owner=self.user, is_history=True)

    # Verify that get_history API returns history objects for given type and current user
    response = self.client.get(reverse('notebook:get_history'), {'doc_type': 'hive'})
    data = json.loads(response.content)
    assert_equal(0, data['status'], data)
    assert_equal(3, len(data['history']), data)
    assert_true(all(doc['type'] == 'query-hive' for doc in data['history']), data)

    # TODO: test that query history for shared query only returns docs accessible by current user

  def test_clear_history(self):
    assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count())
    _historify(self.notebook, self.user)
    _historify(self.notebook, self.user)
    _historify(self.notebook, self.user)
    assert_equal(3, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count())

    # Clear history should not clear history objects that don't have the given doc type
    Document2.objects.create(name='Impala History', type='query-impala', owner=self.user, is_history=True)

    # clear history should retain original document but wipe history
    response = self.client.post(reverse('notebook:clear_history'), {'notebook': self.notebook_json, 'doc_type': 'hive'})
    data = json.loads(response.content)
    assert_equal(0, data['status'], data)
    assert_false(Document2.objects.filter(type='query-hive', is_history=True).exists())
    assert_true(Document2.objects.filter(type='query-hive', is_history=False).exists())
    assert_true(Document2.objects.filter(type='query-impala', is_history=True).exists())


text:
using System;
using System.Collections.Generic;

namespace LinqExtender
{
    internal class Buckets<T> : Dictionary<Type, BucketImpl>
    {
        public BucketImpl Current
        {
            get
            {
                Ensure(typeof(T));
                return current;
            }
            set
            {
                this[typeof (T)] = value;
            }
        }

        private void Ensure(Type targetType)
        {
            if (this.ContainsKey(targetType))
            {
                // set the current object.
                current = this[targetType].InstanceImpl;
            }
        }

        private BucketImpl current = null;

    }
}


text:
package stroom.legacy.model_6_1;

import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import io.swagger.v3.oas.annotations.media.Schema;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@JsonPropertyOrder({"uuid"})
@XmlType(name = "QueryKey", propOrder = {"uuid"})
@XmlAccessorType(XmlAccessType.FIELD)
@Schema(description = "A unique key to identify the instance of the search by. This key is used to " +
        "identify multiple requests for the same search when running in incremental mode.")
@Deprecated
public final class QueryKey implements Serializable {
    private static final long serialVersionUID = -3222989872764402068L;

    @XmlElement
    @Schema(description = "The UUID that makes up the query key",
            example = "7740bcd0-a49e-4c22-8540-044f85770716",
            required = true)
    private String uuid;

    private QueryKey() {
    }

    public QueryKey(final String uuid) {
        this.uuid = uuid;
    }

    public String getUuid() {
        return uuid;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        final QueryKey queryKey = (QueryKey) o;

        return uuid.equals(queryKey.uuid);
    }

    @Override
    public int hashCode() {
        return uuid.hashCode();
    }

    @Override
    public String toString() {
        return uuid;
    }
}


text:
package interrupts

import (
	"bufio"
	_ "embed"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/plugins/inputs"
)

// DO NOT REMOVE THE NEXT TWO LINES! This is required to embed the sampleConfig data.
//go:embed sample.conf
var sampleConfig string

type Interrupts struct {
	CPUAsTag bool `toml:"cpu_as_tag"`
}

type IRQ struct {
	ID     string
	Type   string
	Device string
	Total  int64
	Cpus   []int64
}

func NewIRQ(id string) *IRQ {
	return &IRQ{ID: id, Cpus: []int64{}}
}

func parseInterrupts(r io.Reader) ([]IRQ, error) {
	var irqs []IRQ
	var cpucount int
	scanner := bufio.NewScanner(r)
	if scanner.Scan() {
		cpus := strings.Fields(scanner.Text())
		if cpus[0] != "CPU0" {
			return nil, fmt.Errorf("expected first line to start with CPU0, but was %s", scanner.Text())
		}
		cpucount = len(cpus)
	}

scan:
	for scanner.Scan() {
		fields := strings.Fields(scanner.Text())
		if !strings.HasSuffix(fields[0], ":") {
			continue
		}
		irqid := strings.TrimRight(fields[0], ":")
		irq := NewIRQ(irqid)
		irqvals := fields[1:]
		for i := 0; i < cpucount; i++ {
			if i < len(irqvals) {
				irqval, err := strconv.ParseInt(irqvals[i], 10, 64)
				if err != nil {
					continue scan
				}
				irq.Cpus = append(irq.Cpus, irqval)
			}
		}
		for _, irqval := range irq.Cpus {
			irq.Total += irqval
		}
		_, err := strconv.ParseInt(irqid, 10, 64)
		if err == nil && len(fields) >= cpucount+2 {
			irq.Type = fields[cpucount+1]
			irq.Device = strings.Join(fields[cpucount+2:], " ")
		} else if len(fields) > cpucount {
			irq.Type = strings.Join(fields[cpucount+1:], " ")
		}
		irqs = append(irqs, *irq)
	}
	if scanner.Err() != nil {
		return nil, fmt.Errorf("error scanning file: %s", scanner.Err())
	}
	return irqs, nil
}

func gatherTagsFields(irq IRQ) (map[string]string, map[string]interface{}) {
	tags := map[string]string{"irq": irq.ID, "type": irq.Type, "device": irq.Device}
	fields := map[string]interface{}{"total": irq.Total}
	for i := 0; i < len(irq.Cpus); i++ {
		cpu := fmt.Sprintf("CPU%d", i)
		fields[cpu] = irq.Cpus[i]
	}
	return tags, fields
}

func (*Interrupts) SampleConfig() string {
	return sampleConfig
}

func (s *Interrupts) Gather(acc telegraf.Accumulator) error {
	for measurement, file := range map[string]string{"interrupts": "/proc/interrupts", "soft_interrupts": "/proc/softirqs"} {
		irqs, err := parseFile(file)
		if err != nil {
			acc.AddError(err)
			continue
		}
		reportMetrics(measurement, irqs, acc, s.CPUAsTag)
	}
	return nil
}

func parseFile(file string) ([]IRQ, error) {
	f, err := os.Open(file)
	if err != nil {
		return nil, fmt.Errorf("could not open file: %s", file)
	}
	defer f.Close()

	irqs, err := parseInterrupts(f)
	if err != nil {
		return nil, fmt.Errorf("parsing %s: %s", file, err)
	}
	return irqs, nil
}

func reportMetrics(measurement string, irqs []IRQ, acc telegraf.Accumulator, cpusAsTags bool) {
	for _, irq := range irqs {
		tags, fields := gatherTagsFields(irq)
		if cpusAsTags {
			for cpu, count := range irq.Cpus {
				cpuTags := map[string]string{"cpu": fmt.Sprintf("cpu%d", cpu)}
				for k, v := range tags {
					cpuTags[k] = v
				}
				acc.AddFields(measurement, map[string]interface{}{"count": count}, cpuTags)
			}
		} else {
			acc.AddFields(measurement, fields, tags)
		}
	}
}

func init() {
	inputs.Add("interrupts", func() telegraf.Input {
		return &Interrupts{}
	})
}


text:
import re
import time
from hashlib import sha256
from binascii import hexlify
from decimal import Decimal
from typing import Optional, TYPE_CHECKING, Type

import random
import bitstring

from .bitcoin import hash160_to_b58_address, b58_address_to_hash160, TOTAL_COIN_SUPPLY_LIMIT_IN_BTC
from .segwit_addr import bech32_encode, bech32_decode, CHARSET
from . import segwit_addr
from . import constants
from .constants import AbstractNet
from . import ecc
from .bitcoin import COIN

if TYPE_CHECKING:
    from .lnutil import LnFeatures

class LnInvoiceException(Exception): pass
class LnDecodeException(LnInvoiceException): pass
class LnEncodeException(LnInvoiceException): pass

# BOLT #11:
#
# A writer MUST encode `amount` as a positive decimal integer with no
# leading zeroes, SHOULD use the shortest representation possible.
def shorten_amount(amount):
    """ Given an amount in bitcoin, shorten it
    """
    # Convert to pico initially
    amount = int(amount * 10**12)
    units = ['p', 'n', 'u', 'm']
    for unit in units:
        if amount % 1000 == 0:
            amount //= 1000
        else:
            break
    else:
        unit = ''
    return str(amount) + unit

def unshorten_amount(amount) -> Decimal:
    """ Given a shortened amount, convert it into a decimal
    """
    # BOLT #11:
    # The following `multiplier` letters are defined:
    #
    #* `m` (milli): multiply by 0.001
    #* `u` (micro): multiply by 0.000001
    #* `n` (nano): multiply by 0.000000001
    #* `p` (pico): multiply by 0.000000000001
    units = {
        'p': 10**12,
        'n': 10**9,
        'u': 10**6,
        'm': 10**3,
    }
    unit = str(amount)[-1]
    # BOLT #11:
    # A reader SHOULD fail if `amount` contains a non-digit, or is followed by
    # anything except a `multiplier` in the table above.
    if not re.fullmatch("\\d+[pnum]?", str(amount)):
        raise LnDecodeException("Invalid amount '{}'".format(amount))

    if unit in units.keys():
        return Decimal(amount[:-1]) / units[unit]
    else:
        return Decimal(amount)

_INT_TO_BINSTR = {a: '0' * (5-len(bin(a)[2:])) + bin(a)[2:] for a in range(32)}

# Bech32 spits out array of 5-bit values.  Shim here.
def u5_to_bitarray(arr):
    b = ''.join(_INT_TO_BINSTR[a] for a in arr)
    return bitstring.BitArray(bin=b)

def bitarray_to_u5(barr):
    assert barr.len % 5 == 0
    ret = []
    s = bitstring.ConstBitStream(barr)
    while s.pos != s.len:
        ret.append(s.read(5).uint)
    return ret

def encode_fallback(fallback: str, net: Type[AbstractNet]):
    """ Encode all supported fallback addresses.
    """
    wver, wprog_ints = segwit_addr.decode_segwit_address(net.SEGWIT_HRP, fallback)
    if wver is not None:
        wprog = bytes(wprog_ints)
    else:
        addrtype, addr = b58_address_to_hash160(fallback)
        if addrtype == net.ADDRTYPE_P2PKH:
            wver = 17
        elif addrtype == net.ADDRTYPE_P2SH:
            wver = 18
        else:
            raise LnEncodeException(f"Unknown address type {addrtype} for {net}")
        wprog = addr
    return tagged('f', bitstring.pack("uint:5", wver) + wprog)

def parse_fallback(fallback, net: Type[AbstractNet]):
    wver = fallback[0:5].uint
    if wver == 17:
        addr = hash160_to_b58_address(fallback[5:].tobytes(), net.ADDRTYPE_P2PKH)
    elif wver == 18:
        addr = hash160_to_b58_address(fallback[5:].tobytes(), net.ADDRTYPE_P2SH)
    elif wver <= 16:
        witprog = fallback[5:]  # cut witver
        witprog = witprog[:len(witprog) // 8 * 8]  # can only be full bytes
        witprog = witprog.tobytes()
        addr = segwit_addr.encode_segwit_address(net.SEGWIT_HRP, wver, witprog)
    else:
        return None
    return addr

BOLT11_HRP_INV_DICT = {net.BOLT11_HRP: net for net in constants.NETS_LIST}

# Tagged field containing BitArray
def tagged(char, l):
    # Tagged fields need to be zero-padded to 5 bits.
    while l.len % 5 != 0:
        l.append('0b0')
    return bitstring.pack("uint:5, uint:5, uint:5",
                          CHARSET.find(char),
                          (l.len / 5) / 32, (l.len / 5) % 32) + l

# Tagged field containing bytes
def tagged_bytes(char, l):
    return tagged(char, bitstring.BitArray(l))

def trim_to_min_length(bits):
    """Ensures 'bits' have min number of leading zeroes.
    Assumes 'bits' is big-endian, and that it needs to be encoded in 5 bit blocks.
    """
    bits = bits[:]  # copy
    # make sure we can be split into 5 bit blocks
    while bits.len % 5 != 0:
        bits.prepend('0b0')
    # Get minimal length by trimming leading 5 bits at a time.
    while bits.startswith('0b00000'):
        if len(bits) == 5:
            break  # v == 0
        bits = bits[5:]
    return bits

# Discard trailing bits, convert to bytes.
def trim_to_bytes(barr):
    # Adds a byte if necessary.
    b = barr.tobytes()
    if barr.len % 8 != 0:
        return b[:-1]
    return b

# Try to pull out tagged data: returns tag, tagged data and remainder.
def pull_tagged(stream):
    tag = stream.read(5).uint
    length = stream.read(5).uint * 32 + stream.read(5).uint
    return (CHARSET[tag], stream.read(length * 5), stream)

def lnencode(addr: 'LnAddr', privkey) -> str:
    if addr.amount:
        amount = addr.net.BOLT11_HRP + shorten_amount(addr.amount)
    else:
        amount = addr.net.BOLT11_HRP if addr.net else ''

    hrp = 'ln' + amount

    # Start with the timestamp
    data = bitstring.pack('uint:35', addr.date)

    tags_set = set()

    # Payment hash
    data += tagged_bytes('p', addr.paymenthash)
    tags_set.add('p')

    if addr.payment_secret is not None:
        data += tagged_bytes('s', addr.payment_secret)
        tags_set.add('s')

    for k, v in addr.tags:

        # BOLT #11:
        #
        # A writer MUST NOT include more than one `d`, `h`, `n` or `x` fields,
        if k in ('d', 'h', 'n', 'x', 'p', 's'):
            if k in tags_set:
                raise LnEncodeException("Duplicate '{}' tag".format(k))

        if k == 'r':
            route = bitstring.BitArray()
            for step in v:
                pubkey, channel, feebase, feerate, cltv = step
                route.append(bitstring.BitArray(pubkey) + bitstring.BitArray(channel) + bitstring.pack('intbe:32', feebase) + bitstring.pack('intbe:32', feerate) + bitstring.pack('intbe:16', cltv))
            data += tagged('r', route)
        elif k == 't':
            pubkey, feebase, feerate, cltv = v
            route = bitstring.BitArray(pubkey) + bitstring.pack('intbe:32', feebase) + bitstring.pack('intbe:32', feerate) + bitstring.pack('intbe:16', cltv)
            data += tagged('t', route)
        elif k == 'f':
            if v is not None:
                data += encode_fallback(v, addr.net)
        elif k == 'd':
            # truncate to max length: 1024*5 bits = 639 bytes
            data += tagged_bytes('d', v.encode()[0:639])
        elif k == 'x':
            expirybits = bitstring.pack('intbe:64', v)
            expirybits = trim_to_min_length(expirybits)
            data += tagged('x', expirybits)
        elif k == 'h':
            data += tagged_bytes('h', sha256(v.encode('utf-8')).digest())
        elif k == 'n':
            data += tagged_bytes('n', v)
        elif k == 'c':
            finalcltvbits = bitstring.pack('intbe:64', v)
            finalcltvbits = trim_to_min_length(finalcltvbits)
            data += tagged('c', finalcltvbits)
        elif k == '9':
            if v == 0:
                continue
            feature_bits = bitstring.BitArray(uint=v, length=v.bit_length())
            feature_bits = trim_to_min_length(feature_bits)
            data += tagged('9', feature_bits)
        else:
            # FIXME: Support unknown tags?
            raise LnEncodeException("Unknown tag {}".format(k))

        tags_set.add(k)

    # BOLT #11:
    #
    # A writer MUST include either a `d` or `h` field, and MUST NOT include
    # both.
    if 'd' in tags_set and 'h' in tags_set:
        raise ValueError("Cannot include both 'd' and 'h'")
    if 'd' not in tags_set and 'h' not in tags_set:
        raise ValueError("Must include either 'd' or 'h'")

    # We actually sign the hrp, then data (padded to 8 bits with zeroes).
    msg = hrp.encode("ascii") + data.tobytes()
    privkey = ecc.ECPrivkey(privkey)
    sig = privkey.sign_message(msg, is_compressed=False, algo=lambda x:sha256(x).digest())
    recovery_flag = bytes([sig[0] - 27])
    sig = bytes(sig[1:]) + recovery_flag
    data += sig

    return bech32_encode(segwit_addr.Encoding.BECH32, hrp, bitarray_to_u5(data))

class LnAddr(object):
    def __init__(self, *, paymenthash: bytes = None, amount=None, net: Type[AbstractNet] = None, tags=None, date=None,
                 payment_secret: bytes = None):
        self.date = int(time.time()) if not date else int(date)
        self.tags = [] if not tags else tags
        self.unknown_tags = []
        self.paymenthash = paymenthash
        self.payment_secret = payment_secret
        self.signature = None
        self.pubkey = None
        self.net = constants.net if net is None else net  # type: Type[AbstractNet]
        self._amount = amount  # type: Optional[Decimal]  # in bitcoins
        self._min_final_cltv_expiry = 18

    @property
    def amount(self) -> Optional[Decimal]:
        return self._amount

    @amount.setter
    def amount(self, value):
        if not (isinstance(value, Decimal) or value is None):
            raise LnInvoiceException(f"amount must be Decimal or None, not {value!r}")
        if value is None:
            self._amount = None
            return
        assert isinstance(value, Decimal)
        if value.is_nan() or not (0 <= value <= TOTAL_COIN_SUPPLY_LIMIT_IN_BTC):
            raise LnInvoiceException(f"amount is out-of-bounds: {value!r} LTC")
        if value * 10**12 % 10:
            # max resolution is millisatoshi
            raise LnInvoiceException(f"Cannot encode {value!r}: too many decimal places")
        self._amount = value

    def get_amount_sat(self) -> Optional[Decimal]:
        # note that this has msat resolution potentially
        if self.amount is None:
            return None
        return self.amount * COIN

    def get_routing_info(self, tag):
        # note: tag will be 't' for trampoline
        r_tags = list(filter(lambda x: x[0] == tag, self.tags))
        # strip the tag type, it's implicitly 'r' now
        r_tags = list(map(lambda x: x[1], r_tags))
        # if there are multiple hints, we will use the first one that works,
        # from a random permutation
        random.shuffle(r_tags)
        return r_tags

    def get_amount_msat(self) -> Optional[int]:
        if self.amount is None:
            return None
        return int(self.amount * COIN * 1000)

    def get_features(self) -> 'LnFeatures':
        from .lnutil import LnFeatures
        return LnFeatures(self.get_tag('9') or 0)

    def __str__(self):
        return "LnAddr[{}, amount={}{} tags=[{}]]".format(
            hexlify(self.pubkey.serialize()).decode('utf-8') if self.pubkey else None,
            self.amount, self.net.BOLT11_HRP,
            ", ".join([k + '=' + str(v) for k, v in self.tags])
        )

    def get_min_final_cltv_expiry(self) -> int:
        return self._min_final_cltv_expiry

    def get_tag(self, tag):
        for k, v in self.tags:
            if k == tag:
                return v
        return None

    def get_description(self) -> str:
        return self.get_tag('d') or ''

    def get_fallback_address(self) -> str:
        return self.get_tag('f') or ''

    def get_expiry(self) -> int:
        exp = self.get_tag('x')
        if exp is None:
            exp = 3600
        return int(exp)

    def is_expired(self) -> bool:
        now = time.time()
        # BOLT-11 does not specify what expiration of '0' means.
        # we treat it as 0 seconds here (instead of never)
        return now > self.get_expiry() + self.date

class SerializableKey:
    def __init__(self, pubkey):
        self.pubkey = pubkey
    def serialize(self):
        return self.pubkey.get_public_key_bytes(True)

def lndecode(invoice: str, *, verbose=False, net=None) -> LnAddr:
    if net is None:
        net = constants.net
    decoded_bech32 = bech32_decode(invoice, ignore_long_length=True)
    hrp = decoded_bech32.hrp
    data = decoded_bech32.data
    if decoded_bech32.encoding is None:
        raise LnDecodeException("Bad bech32 checksum")
    if decoded_bech32.encoding != segwit_addr.Encoding.BECH32:
        raise LnDecodeException("Bad bech32 encoding: must be using vanilla BECH32")

    # BOLT #11:
    #
    # A reader MUST fail if it does not understand the `prefix`.
    if not hrp.startswith('ln'):
        raise LnDecodeException("Does not start with ln")

    if not hrp[2:].startswith(net.BOLT11_HRP):
        raise LnDecodeException(f"Wrong Lightning invoice HRP {hrp[2:]}, should be {net.BOLT11_HRP}")

    data = u5_to_bitarray(data)

    # Final signature 65 bytes, split it off.
    if len(data) < 65*8:
        raise LnDecodeException("Too short to contain signature")
    sigdecoded = data[-65*8:].tobytes()
    data = bitstring.ConstBitStream(data[:-65*8])

    addr = LnAddr()
    addr.pubkey = None

    m = re.search("[^\\d]+", hrp[2:])
    if m:
        addr.net = BOLT11_HRP_INV_DICT[m.group(0)]
        amountstr = hrp[2+m.end():]
        # BOLT #11:
        #
        # A reader SHOULD indicate if amount is unspecified, otherwise it MUST
        # multiply `amount` by the `multiplier` value (if any) to derive the
        # amount required for payment.
        if amountstr != '':
            addr.amount = unshorten_amount(amountstr)

    addr.date = data.read(35).uint

    while data.pos != data.len:
        tag, tagdata, data = pull_tagged(data)

        # BOLT #11:
        #
        # A reader MUST skip over unknown fields, an `f` field with unknown
        # `version`, or a `p`, `h`, or `n` field which does not have
        # `data_length` 52, 52, or 53 respectively.
        data_length = len(tagdata) / 5

        if tag == 'r':
            # BOLT #11:
            #
            # * `r` (3): `data_length` variable.  One or more entries
            # containing extra routing information for a private route;
            # there may be more than one `r` field, too.
            #    * `pubkey` (264 bits)
            #    * `short_channel_id` (64 bits)
            #    * `feebase` (32 bits, big-endian)
            #    * `feerate` (32 bits, big-endian)
            #    * `cltv_expiry_delta` (16 bits, big-endian)
            route=[]
            s = bitstring.ConstBitStream(tagdata)
            while s.pos + 264 + 64 + 32 + 32 + 16 < s.len:
                route.append((s.read(264).tobytes(),
                              s.read(64).tobytes(),
                              s.read(32).uintbe,
                              s.read(32).uintbe,
                              s.read(16).uintbe))
            addr.tags.append(('r',route))
        elif tag == 't':
            s = bitstring.ConstBitStream(tagdata)
            e = (s.read(264).tobytes(),
                 s.read(32).uintbe,
                 s.read(32).uintbe,
                 s.read(16).uintbe)
            addr.tags.append(('t', e))
        elif tag == 'f':
            fallback = parse_fallback(tagdata, addr.net)
            if fallback:
                addr.tags.append(('f', fallback))
            else:
                # Incorrect version.
                addr.unknown_tags.append((tag, tagdata))
                continue

        elif tag == 'd':
            addr.tags.append(('d', trim_to_bytes(tagdata).decode('utf-8')))

        elif tag == 'h':
            if data_length != 52:
                addr.unknown_tags.append((tag, tagdata))
                continue
            addr.tags.append(('h', trim_to_bytes(tagdata)))

        elif tag == 'x':
            addr.tags.append(('x', tagdata.uint))

        elif tag == 'p':
            if data_length != 52:
                addr.unknown_tags.append((tag, tagdata))
                continue
            addr.paymenthash = trim_to_bytes(tagdata)

        elif tag == 's':
            if data_length != 52:
                addr.unknown_tags.append((tag, tagdata))
                continue
            addr.payment_secret = trim_to_bytes(tagdata)

        elif tag == 'n':
            if data_length != 53:
                addr.unknown_tags.append((tag, tagdata))
                continue
            pubkeybytes = trim_to_bytes(tagdata)
            addr.pubkey = pubkeybytes

        elif tag == 'c':
            addr._min_final_cltv_expiry = tagdata.uint

        elif tag == '9':
            features = tagdata.uint
            addr.tags.append(('9', features))
            from .lnutil import validate_features
            validate_features(features)

        else:
            addr.unknown_tags.append((tag, tagdata))

    if verbose:
        print('hex of signature data (32 byte r, 32 byte s): {}'
              .format(hexlify(sigdecoded[0:64])))
        print('recovery flag: {}'.format(sigdecoded[64]))
        print('hex of data for signing: {}'
              .format(hexlify(hrp.encode("ascii") + data.tobytes())))
        print('SHA256 of above: {}'.format(sha256(hrp.encode("ascii") + data.tobytes()).hexdigest()))

    # BOLT #11:
    #
    # A reader MUST check that the `signature` is valid (see the `n` tagged
    # field specified below).
    addr.signature = sigdecoded[:65]
    hrp_hash = sha256(hrp.encode("ascii") + data.tobytes()).digest()
    if addr.pubkey: # Specified by `n`
        # BOLT #11:
        #
        # A reader MUST use the `n` field to validate the signature instead of
        # performing signature recovery if a valid `n` field is provided.
        if not ecc.ECPubkey(addr.pubkey).verify_message_hash(sigdecoded[:64], hrp_hash):
            raise LnDecodeException("bad signature")
        pubkey_copy = addr.pubkey
        class WrappedBytesKey:
            serialize = lambda: pubkey_copy
        addr.pubkey = WrappedBytesKey
    else: # Recover pubkey from signature.
        addr.pubkey = SerializableKey(ecc.ECPubkey.from_sig_string(sigdecoded[:64], sigdecoded[64], hrp_hash))

    return addr


text:
require File.expand_path(File.join(File.dirname(__FILE__), "helper"))

class LinksMechTest < Test::Unit::TestCase
  def setup
    @agent = WWW::Mechanize.new
  end

  def test_unsupported_link_types
    page = @agent.get("http://google.com/tc_links.html")
    link = page.links.text('javascript link').first
    assert_raise(WWW::Mechanize::UnsupportedSchemeError) {
      link.click
    }

    @agent.scheme_handlers['javascript'] = lambda { |link, page|
      URI.parse('http://localhost/tc_links.html')
    }
    assert_nothing_raised {
      link.click
    }
  end

  def test_base
    page = @agent.get("http://google.com/tc_base_link.html")
    page = page.links.first.click
    assert @agent.visited?("http://localhost/index.html")
  end

  def test_find_meta
    page = @agent.get("http://localhost/find_link.html")
    assert_equal(3, page.meta.length)
    assert_equal(%w{
      http://www.drphil.com/
      http://www.upcase.com/
      http://tenderlovemaking.com/ }.sort,
      page.meta.map { |x| x.href.downcase }.sort)
  end

  def test_find_link
    page = @agent.get("http://localhost/find_link.html")
    assert_equal(18, page.links.length)
  end

  def test_alt_text
    page = @agent.get("http://localhost/alt_text.html")
    assert_equal(5, page.links.length)
    assert_equal(1, page.meta.length)

    assert_equal('', page.meta.first.text)
    assert_equal('alt text', page.links.href('alt_text.html').first.text)
    assert_equal('', page.links.href('no_alt_text.html').first.text)
    assert_equal('no image', page.links.href('no_image.html').first.text)
    assert_equal('', page.links.href('no_text.html').first.text)
    assert_equal('', page.links.href('nil_alt_text.html').first.text)
  end

  def test_click_link
    @agent.user_agent_alias = 'Mac Safari'
    page = @agent.get("http://localhost/frame_test.html")
    link = page.links.text("Form Test")
    assert_not_nil(link)
    assert_equal('Form Test', link.text)
    page = @agent.click(link)
    assert_equal("http://localhost/form_test.html",
      @agent.history.last.uri.to_s)
  end

  def test_click_method
    page = @agent.get("http://localhost/frame_test.html")
    link = page.links.text("Form Test")
    assert_not_nil(link)
    assert_equal('Form Test', link.text)
    page = link.click
    assert_equal("http://localhost/form_test.html",
      @agent.history.last.uri.to_s)
  end

  def test_find_bold_link
    page = @agent.get("http://localhost/tc_links.html")
    link = page.links.text(/Bold Dude/)
    assert_equal(1, link.length)
    assert_equal('Bold Dude', link.first.text)

    link = page.links.text('Aaron James Patterson')
    assert_equal(1, link.length)
    assert_equal('Aaron James Patterson', link.first.text)

    link = page.links.text('Aaron Patterson')
    assert_equal(1, link.length)
    assert_equal('Aaron Patterson', link.first.text)

    link = page.links.text('Ruby Rocks!')
    assert_equal(1, link.length)
    assert_equal('Ruby Rocks!', link.first.text)
  end

  def test_link_with_encoded_space
    page = @agent.get("http://localhost/tc_links.html")
    link = page.links.text('encoded space').first
    page = @agent.click link
  end

  def test_link_with_space
    page = @agent.get("http://localhost/tc_links.html")
    link = page.links.text('not encoded space').first
    page = @agent.click link
  end

  def test_link_with_unusual_characters
    page = @agent.get("http://localhost/tc_links.html")
    link = page.links.text('unusual characters').first
    assert_nothing_raised { @agent.click link }
  end
end


text:
/**
 *
 * (c) 2013-2018 Wishtack
 *
 * $Id: $
 */

import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { GreetingsComponent } from '../fixtures/greetings.module';
import { ReactiveComponentLoaderModule } from './reactive-component-loader.module';
import { ReactiveComponentLoader } from './reactive-component-loader.service';
import Spy = jasmine.Spy;

describe('ReactiveComponentLoader', () => {

    let error: Spy;
    let next: Spy;

    beforeEach(() => {
        error = jasmine.createSpy('error');
        next = jasmine.createSpy('next');
    });

    describe('with one module', () => {

        beforeEach(() => TestBed.configureTestingModule({
            imports: [
                ReactiveComponentLoaderModule.withModule({
                    moduleId: 'greetings',
                    loadChildren: () => import('../fixtures/greetings.module').then(m => m.GreetingsModule)
                }),
                RouterTestingModule
            ]
        }));

        let reactiveComponentLoader: ReactiveComponentLoader;
        beforeEach(() => reactiveComponentLoader = TestBed.get(ReactiveComponentLoader));

        it('should retrieve component recipe', async () => {

            /* Retrieving the component's recipe using its location. */
            const recipe = await reactiveComponentLoader.getComponentRecipe({
                moduleId: 'greetings',
                selector: 'wt-greetings'
            }).toPromise();

            /* Check that we retrieved the right component type. */
            expect(recipe.componentType).toBe(GreetingsComponent);

            /* Create the component... */
            const fixture = TestBed.createComponent(recipe.componentType);

            /* ... and see if it works. */
            fixture.componentInstance.name = '@yjaaidi';
            fixture.detectChanges();
            expect(fixture.nativeElement.textContent).toEqual('Hello @yjaaidi');

        });

        it('should throw an error if module is not found', fakeAsync(() => {

            reactiveComponentLoader.getComponentRecipe({
                moduleId: 'unknown-module-id',
                selector: 'wt-greetings'
            })
                .subscribe({next, error});

            tick();

            expect(next).not.toHaveBeenCalled();
            expect(error).toHaveBeenCalledWith(new Error(`Module with id 'unknown-module-id' not found.`));

        }));

        it('should throw an error if component is not found', fakeAsync(() => {

            reactiveComponentLoader.getComponentRecipe({
                moduleId: 'greetings',
                selector: 'wt-unknown-component'
            })
                .subscribe({next, error});

            tick();

            expect(next).not.toHaveBeenCalled();
            expect(error).toHaveBeenCalledWith(new Error(`Component '<wt-unknown-component>' not found.`));

        }));

    });

    describe('with duplicate modules', () => {

        beforeEach(() => TestBed.configureTestingModule({
            imports: [
                ReactiveComponentLoaderModule.withModule({
                    moduleId: 'greetings',
                    loadChildren: './path/to/greetings-1.module#GreetingsModule'
                }),
                ReactiveComponentLoaderModule.withModule({
                    moduleId: 'greetings',
                    loadChildren: './path/to/greetings-2.module#GreetingsModule'
                }),
                RouterTestingModule
            ]
        }));

        let reactiveComponentLoader: ReactiveComponentLoader;
        beforeEach(() => reactiveComponentLoader = TestBed.get(ReactiveComponentLoader));

        it('should throw an error if module is declared with different locations', fakeAsync(() => {

            reactiveComponentLoader.getComponentRecipe({
                moduleId: 'greetings',
                selector: 'wt-greetings'
            })
                .subscribe({next, error});

            tick();

            expect(next).not.toHaveBeenCalled();
            expect(error).toHaveBeenCalledWith(new Error(
                `Module with id 'greetings' has been declared more than once with different locations.`
            ));

        }));

    });

});


text:
package cromwell.api.model

import spray.json.{DefaultJsonProtocol, JsObject}

object WorkflowLabelsJsonSupport extends DefaultJsonProtocol {
  implicit val LabelsResponseFormat = jsonFormat2(WorkflowLabels)
}

final case class WorkflowLabels(id: String, labels: JsObject)