text:
// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.client.changes;

import com.google.gerrit.client.rpc.Natives;
import com.google.gerrit.common.data.SubmitRecord;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwtjsonrpc.client.impl.ser.JavaSqlTimestamp_JsonSerializer;

import java.sql.Timestamp;
import java.util.Set;

public class ChangeInfo extends JavaScriptObject {
  public final Project.NameKey project_name_key() {
    return new Project.NameKey(project());
  }

  public final Change.Id legacy_id() {
    return new Change.Id(_number());
  }

  public final Timestamp created() {
    Timestamp ts = _get_cts();
    if (ts == null) {
      ts = JavaSqlTimestamp_JsonSerializer.parseTimestamp(createdRaw());
      _set_cts(ts);
    }
    return ts;
  }

  private final native Timestamp _get_cts() /*-{ return this._cts; }-*/;
  private final native void _set_cts(Timestamp ts) /*-{ this._cts = ts; }-*/;

  public final Timestamp updated() {
    return JavaSqlTimestamp_JsonSerializer.parseTimestamp(updatedRaw());
  }

  public final String id_abbreviated() {
    return new Change.Key(id()).abbreviate();
  }

  public final Change.Status status() {
    return Change.Status.valueOf(statusRaw());
  }

  public final Set<String> labels() {
    return Natives.keys(labels0());
  }

  public final native String project() /*-{ return this.project; }-*/;
  public final native String branch() /*-{ return this.branch; }-*/;
  public final native String topic() /*-{ return this.topic; }-*/;
  public final native String id() /*-{ return this.id; }-*/;
  private final native String statusRaw() /*-{ return this.status; }-*/;
  public final native String subject() /*-{ return this.subject; }-*/;
  public final native AccountInfo owner() /*-{ return this.owner; }-*/;
  private final native String createdRaw() /*-{ return this.created; }-*/;
  private final native String updatedRaw() /*-{ return this.updated; }-*/;
  public final native boolean starred() /*-{ return this.starred ? true : false; }-*/;
  public final native boolean reviewed() /*-{ return this.reviewed ? true : false; }-*/;
  public final native String _sortkey() /*-{ return this._sortkey; }-*/;
  private final native JavaScriptObject labels0() /*-{ return this.labels; }-*/;
  public final native LabelInfo label(String n) /*-{ return this.labels[n]; }-*/;
  final native int _number() /*-{ return this._number; }-*/;
  final native boolean _more_changes()
  /*-{ return this._more_changes ? true : false; }-*/;

  protected ChangeInfo() {
  }

  public static class AccountInfo extends JavaScriptObject {
    public final native String name() /*-{ return this.name; }-*/;

    protected AccountInfo() {
    }
  }

  public static class LabelInfo extends JavaScriptObject {
    public final SubmitRecord.Label.Status status() {
      if (approved() != null) {
        return SubmitRecord.Label.Status.OK;
      } else if (rejected() != null) {
        return SubmitRecord.Label.Status.REJECT;
      } else if (optional()) {
        return SubmitRecord.Label.Status.MAY;
      } else {
        return SubmitRecord.Label.Status.NEED;
      }
    }

    public final native String name() /*-{ return this._name; }-*/;
    public final native AccountInfo approved() /*-{ return this.approved; }-*/;
    public final native AccountInfo rejected() /*-{ return this.rejected; }-*/;

    public final native AccountInfo recommended() /*-{ return this.recommended; }-*/;
    public final native AccountInfo disliked() /*-{ return this.disliked; }-*/;
    public final native boolean optional() /*-{ return this.optional ? true : false; }-*/;
    final native short _value()
    /*-{
      if (this.value) return this.value;
      if (this.disliked) return -1;
      if (this.recommended) return 1;
      return 0;
    }-*/;

    protected LabelInfo() {
    }
  }
}


text:
class AddReuintedToReport < ActiveRecord::Migration
  def change
    add_column :reports, :reunited, :boolean
  end
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css">
    <link rel="stylesheet" href="app.css">

            x: {{scroll.x}}
            y: {{scroll.y}}
            distanceX: {{scroll.distanceX}}
            distanceY: {{scroll.distanceY}}
            velocityX: {{scroll.velocityX}}
            velocityY: {{scroll.velocityY}}
            timelapse: {{scroll.timelapse}}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';

class Profile extends Component {

    render() {

        return (

        { (() => {
            if (this.props.login && this.props.login.name) {
                return (

                Logged in as: {this.props.login.name}

                Logout

            );
            }
            else {
                return Login;
            }
        })()
        }

    );

    }

}

Profile.propTypes = {
    login: PropTypes.object
};

export default Profile;


text:
package org.jboss.arquillian.container.test.api;

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

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

/**
 * Define that a Deployment should cause a exception during deployment. If the Container does not throw a exception,
 * or the exception is of the wrong type, a RuntimeException will be thrown and the test failed.
 * If the correct exception is thrown the test will execute as normal.
 *

 *

 * Usage Example:

 *

 * @Deployment @ShouldThrowException(WeldDeploymentException.class)
 * public static WebArchive create() {
 *      return ShrinkWrap.create(WebArchive.class);
 * }
 *

 *

 * Adding the @ShouldThrowException annotation will force the @{@link Deployment} to be testable = false which again
 * will force a @{@link RunAsClient} test run mode, unless you explicitly mark testable = true
 *
 * @author Aslak Knutsen
 * @version $Revision: $
 */
@Documented
@Retention(RUNTIME)
@Target(ElementType.METHOD)
public @interface ShouldThrowException {
    Class<? extends Exception> value() default Exception.class;

    /**
     * @return whether or not this deployment is intended to be testable, default is false
     */
    boolean testable() default false;
}


text:
import ScDropdownCtrl from './dropdown.controller.js';

/**
 * @ngdoc component
 * @name talend.sunchoke.dropdown.component:ScDropdownComponent
 * @description Dropdown widget.
 * @restrict E
 * @usage
 <sc-dropdown close-on-select="false" on-open="open()" side="left">
     <sc-dropdown-trigger>
        Click me !
     </sc-dropdown-trigger>
     <sc-dropdown-content>
        My menu content
     </sc-dropdown-content>
 </sc-dropdown>`
 * @param {boolean} closeOnSelect Default `true`. If set to false, dropdown will not close on inner item click
 * @param {function} onOpen The callback to execute on dropdown open
 * @param {string} side Force display on the specified side (left | right)
 * @param {boolean} visibleOnInit Force dropdown to load
 * @param {number} distanceFromBorder Distance from window border in pixel
 */
const ScDropdownComponent = {
    template: `

    `,
    bindings: {
        closeOnSelect: '<',
        onOpen: '&',
        side: '@',
        visibleOnInit: '<',
        distanceFromBorder: '@'
    },
    transclude: {
        'sc-dropdown-trigger': 'scDropdownTrigger',
        'sc-dropdown-content': 'scDropdownContent'
    },
    controller: ScDropdownCtrl
};

export default ScDropdownComponent;


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Event\VisitContactEvent;
use AppBundle\Event\VisitEvents;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
      $firstname = "Symp";
        // replace this example code with whatever you need
        return $this->render('default-old/index.html.twig', [
          'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
          "firstname" => $firstname
        ]);
    }

    /**
     * @Route("/contact", name="contact-old")
     */

    public function contactAction(Request $request)
    {
        // -------------------------------
        // Déclencheur d'évenement
        $eventDispatcher = $this->get('event_dispatcher');

        $event = new VisitContactEvent();
        $event->setIp($request->getClientIp());

        // C''est ce qui va déclencher l'évnement
        $eventDispatcher->dispatch(VisitEvents::CONTACT, $event);

        // -------------------------------
        // Lecture du fichier CSV
        $fileCSV = file('../var/logs/contactFormLogs.csv');
        dump($fileCSV);

        $firstname = "Alexis";
      // dump($firstname);

      return $this->render('default-old/contact.html.twig', [
        "firstname" => $firstname,
          'fileCSV' => $fileCSV
          ]);

    }

        /**
     * @Route("/product", name="product-test")
     */

    public function productAction(Request $request)
    {
        $products = [
    [
        "id" => 1,
        "title" => "mon premier produit",
        "description" => "lorem ipsum",
        "date_created" => new \DateTime('now'),
        "prix" => 10
    ],
    [
        "id" => 2,
        "title" => "Mon deuxième produit",
        "description" => "lorem ipsum",
        "date_created" => new \DateTime('now'),
        "prix" => 20
    ],
    [
        "id" => 3,
        "title" => "Mon troisième produit",
        "description" => "lorem ipsum",
        "date_created" => new \DateTime('now'),
        "prix" => 30
    ],
    [
        "id" => 4,
        "title" => "",
        "description" => "lorem ipsum",
        "date_created" => new \DateTime('now'),
        "prix" => 410
    ],
    ];
    $prenom = "Alexis";
    $nom = "Persinette";

      return $this->render('default/product.html.twig', [
        "products" => $products,
        "prenom" => $prenom,
        "nom" => $nom

          ]);
    }

    /**
     * @Route("/bloc-mere", name="bloc-mere")
     */

    public function blocMereAction(Request $request)
    {

      return $this->render('default-old//bloc-mere.html.twig', [
          ]);

    }

    /**
     * @Route("/bloc-fille", name="bloc-fille")
     */

    public function blocFilleAction(Request $request)
    {

      return $this->render('default-old//bloc-fille.html.twig', [
          ]);

    }
    /**
     * @Route("/bloc-frere", name="bloc-frere")
     */

    public function blocFrereAction(Request $request)
    {

      return $this->render('default-old//bloc-frere.html.twig', [
          ]);

    }

    /**
     * @Route("/disclaimer-cookies", name="disclaimer-cookies")
     */
    public function disclaimerCookiesAction(Request $request)
    {
        $disclaimer = $request->get('disclaimer');

        $session = $request->getSession();
        $session->set('disclaimer', $disclaimer);

        return new JsonResponse([
            'success' => 'ok'
        ]);
        // dump($session);exit;
    }
}


text:
Sequel.migration do
  change do
    add_index :metadata_instances, :primary_tag, unique: true
  end
end


text:
module Delighted
  class SurveyRequest < Resource
    self.path = "/people/{PERSON_EMAIL}/survey_requests"

    def self.delete_pending(attributes = {}, client = Delighted.shared_client)
      raise ArgumentError, "You must pass :person_email" unless attributes[:person_email]
      interpolated_path = path.sub("{PERSON_EMAIL}", CGI.escape(attributes[:person_email]))
      interpolated_path << "/pending"
      json = client.delete_json(interpolated_path)
      json
    end
  end
end


text:
@interface FindButtonTests : XCTestCase

@end

@implementation FindButtonTests

- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testExample {
    // This is an example of a functional test case.
    // Use XCTAssert and related functions to verify your tests produce the correct results.
}

- (void)testPerformanceExample {
    // This is an example of a performance test case.
    [self measureBlock:^{
        // Put the code you want to measure the time of here.
    }];
}

- (void)testFindButtons {
    //首层
    UIView *view = [[UIView alloc] init];
    //第二层
    UIView *view11 = [[UIView alloc] init];
    [view addSubview:view11];
    UIView *view12 = [[UIView alloc] init];
    [view addSubview:view12];
    UIView *view13 = [[UIButton alloc] init];
    [view addSubview:view13];
    //第三层
    UIView *view111 = [[UIView alloc] init];
    [view11 addSubview:view111];
    UIView *view112 = [[UIButton alloc] init];
    [view11 addSubview:view112];
    UIView *view113 = [[UIButton alloc] init];
    [view11 addSubview:view113];

    UIView *view121 = [[UIView alloc] init];
    [view12 addSubview:view121];
    UIView *view122 = [[UIButton alloc] init];
    [view12 addSubview:view122];
    UIView *view123 = [[UIButton alloc] init];
    [view12 addSubview:view123];
    //第四层
    UIView *view1111 = [[UIView alloc] init];
    [view111 addSubview:view1111];
    UIView *view1112 = [[UIButton alloc] init];
    [view111 addSubview:view1112];
    UIView *view1113 = [[UIButton alloc] init];
    [view111 addSubview:view1113];

    //递归
    NSInteger recursion = [self recursionFindButtonInView:view];
    //迭代
    NSInteger iteration = [self iterationFindButtonInView:view];

    NSLog(@"recursion=%ld, iteration=%ld", recursion, iteration);
}

//递归查找View中所有button的个数
- (NSInteger)recursionFindButtonInView:(UIView *)view {
    NSInteger result = 0;
    for (UIView *subView in view.subviews) {
        if ([subView isKindOfClass:[UIButton class]]) {
            result += 1;
        }
        result += [self recursionFindButtonInView:subView];
    }
    return result;
}
//迭代查找View中所有button的个数
- (NSInteger)iterationFindButtonInView:(UIView *)view {
    NSInteger result = 0;
    NSMutableArray *array = [NSMutableArray array];
    [array addObject:view];
    while (array.count > 0) {
        UIView *firstView = array.firstObject;
        for (UIView *subView in firstView.subviews) {
            if ([subView isKindOfClass:[UIButton class]]) {
                result += 1;
            }
            [array addObject:subView];
        }
        [array removeObjectAtIndex:0];
    }
    return result;
}

@end


text:
[![Build Status](https://travis-ci.org/evanlok/card_processor.svg)](https://travis-ci.org/evanlok/card_processor) [![Code Climate](https://codeclimate.com/github/evanlok/card_processor/badges/gpa.svg)](https://codeclimate.com/github/evanlok/card_processor) [![Coverage Status](https://coveralls.io/repos/evanlok/card_processor/badge.svg?branch=master)](https://coveralls.io/r/evanlok/card_processor?branch=master)

## Installation

```
$ git clone git@github.com:evanlok/card_processor.git
```

## Usage

Using a file
```
$ bin/card_processor input.txt
```

Using STDIN
```
$ cat input.txt | bin/card_processor
```

## Development

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

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

## Contributing

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


text:
package netdb.software.benchmark.remote;

import java.sql.SQLException;

public interface SutConnection {

	SutResultSet callStoredProc(int pid, Object... pars) throws SQLException;

}


text:
package org.jasig.cas.adaptors.trusted.web.flow;

import org.jasig.cas.adaptors.trusted.authentication.principal.PrincipalBearingCredential;
import org.jasig.cas.authentication.Credential;
import org.jasig.cas.web.flow.AbstractNonInteractiveCredentialsAction;
import org.jasig.cas.web.support.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.webflow.execution.RequestContext;

import javax.servlet.http.HttpServletRequest;

/**
 * Implementation of the NonInteractiveCredentialsAction that looks for a remote
 * user that is set in the {@code HttpServletRequest} and attempts to
 * construct a Principal (and thus a PrincipalBearingCredential). If it doesn't
 * find one, this class returns and error event which tells the web flow it
 * could not find any credentials.
 *
 * @author Scott Battaglia
 * @since 3.0.0
 */
@Component("principalFromRemoteUserAction")
public final class PrincipalFromRequestRemoteUserNonInteractiveCredentialsAction
            extends AbstractNonInteractiveCredentialsAction {

    private final transient Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    protected Credential constructCredentialsFromRequest(final RequestContext context) {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        final String remoteUser = request.getRemoteUser();

        if (StringUtils.hasText(remoteUser)) {
            logger.debug("Remote User [{}] found in HttpServletRequest", remoteUser);
            return new PrincipalBearingCredential(this.principalFactory.createPrincipal(remoteUser));
        }
        return null;
    }
}


text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.android;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.rules.android.AndroidDataConverter.JoinerType;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import javax.annotation.Nullable;

/**
 * Builder for creating $android_resource_merger action. The action merges resources and generates
 * the merged R classes for an android_library to hand off to java compilation of the library
 * sources. It also generates a merged resources zip file to pass on to the
 * $android_resource_validator action. For android_binary, see {@link
 * AndroidResourcesProcessorBuilder}.
 */
public class AndroidResourceMergingActionBuilder {

  private static final AndroidDataConverter<MergableAndroidData> RESOURCE_CONTAINER_TO_ARG =
      AndroidDataConverter.MERGABLE_DATA_CONVERTER;

  @AutoCodec @AutoCodec.VisibleForSerialization
  static final AndroidDataConverter<CompiledMergableAndroidData>
      RESOURCE_CONTAINER_TO_ARG_FOR_COMPILED =
          AndroidDataConverter.<CompiledMergableAndroidData>builder(JoinerType.SEMICOLON_AMPERSAND)
              .withRoots(CompiledMergableAndroidData::getResourceRoots)
              .withRoots(CompiledMergableAndroidData::getAssetRoots)
              .withLabel(CompiledMergableAndroidData::getLabel)
              .withArtifact(CompiledMergableAndroidData::getCompiledSymbols)
              .build();

  // Inputs
  private CompiledMergableAndroidData primary;
  private ResourceDependencies dependencies;

  // Outputs
  private Artifact mergedResourcesOut;
  private Artifact classJarOut;
  private Artifact manifestOut;
  private @Nullable Artifact dataBindingInfoZip;

  // Flags
  private String customJavaPackage;
  private boolean throwOnResourceConflict;
  private boolean useCompiledMerge;

  /**
   * The primary resource for merging. This resource will overwrite any resource or data value in
   * the transitive closure.
   */
  private AndroidResourceMergingActionBuilder withPrimary(CompiledMergableAndroidData primary) {
    this.primary = primary;
    return this;
  }

  public AndroidResourceMergingActionBuilder withDependencies(ResourceDependencies resourceDeps) {
    this.dependencies = resourceDeps;
    return this;
  }

  public AndroidResourceMergingActionBuilder setMergedResourcesOut(Artifact mergedResourcesOut) {
    this.mergedResourcesOut = mergedResourcesOut;
    return this;
  }

  public AndroidResourceMergingActionBuilder setClassJarOut(Artifact classJarOut) {
    this.classJarOut = classJarOut;
    return this;
  }

  public AndroidResourceMergingActionBuilder setManifestOut(Artifact manifestOut) {
    this.manifestOut = manifestOut;
    return this;
  }

  /**
   * The output zip for resource-processed data binding expressions (i.e. a zip of .xml files).
   *
   * <p>If null, data binding processing is skipped (and data binding expressions aren't allowed in
   * layout resources).
   */
  public AndroidResourceMergingActionBuilder setDataBindingInfoZip(Artifact zip) {
    this.dataBindingInfoZip = zip;
    return this;
  }

  public AndroidResourceMergingActionBuilder setJavaPackage(String customJavaPackage) {
    this.customJavaPackage = customJavaPackage;
    return this;
  }

  public AndroidResourceMergingActionBuilder setThrowOnResourceConflict(
      boolean throwOnResourceConflict) {
    this.throwOnResourceConflict = throwOnResourceConflict;
    return this;
  }

  public AndroidResourceMergingActionBuilder setUseCompiledMerge(boolean useCompiledMerge) {
    this.useCompiledMerge = useCompiledMerge;
    return this;
  }

  private BusyBoxActionBuilder createInputsForBuilder(BusyBoxActionBuilder builder) {
    return builder
        .addAndroidJar()
        .addInput("--primaryManifest", primary.getManifest())
        .maybeAddFlag("--packageForR", customJavaPackage)
        .maybeAddFlag("--throwOnResourceConflict", throwOnResourceConflict);
  }

  private void buildCompiledResourceMergingAction(BusyBoxActionBuilder builder) {
    Preconditions.checkNotNull(primary);

    createInputsForBuilder(builder)
        .addInput(
            "--primaryData",
            RESOURCE_CONTAINER_TO_ARG_FOR_COMPILED.map(primary),
            Iterables.concat(
                primary.getArtifacts(), ImmutableList.of(primary.getCompiledSymbols())));

    if (dependencies != null) {
      builder
          .addTransitiveFlag(
              "--data",
              dependencies.getTransitiveResourceContainers(),
              RESOURCE_CONTAINER_TO_ARG_FOR_COMPILED)
          .addTransitiveFlag(
              "--directData",
              dependencies.getDirectResourceContainers(),
              RESOURCE_CONTAINER_TO_ARG_FOR_COMPILED)
          .addTransitiveInputValues(dependencies.getTransitiveResources())
          .addTransitiveInputValues(dependencies.getTransitiveAssets())
          .addTransitiveInputValues(dependencies.getTransitiveCompiledSymbols());
    }

    builder.buildAndRegister("Merging compiled Android resources", "AndroidCompiledResourceMerger");
  }

  private void buildParsedResourceMergingAction(BusyBoxActionBuilder builder) {
    Preconditions.checkNotNull(primary);

    createInputsForBuilder(builder)
        .addInput(
            "--primaryData",
            RESOURCE_CONTAINER_TO_ARG.map(primary),
            Iterables.concat(primary.getArtifacts(), ImmutableList.of(primary.getSymbols())));

    if (dependencies != null) {
      builder
          .addTransitiveFlag(
              "--data", dependencies.getTransitiveResourceContainers(), RESOURCE_CONTAINER_TO_ARG)
          .addTransitiveFlag(
              "--directData", dependencies.getDirectResourceContainers(), RESOURCE_CONTAINER_TO_ARG)
          .addTransitiveInputValues(dependencies.getTransitiveResources())
          .addTransitiveInputValues(dependencies.getTransitiveAssets())
          .addTransitiveInputValues(dependencies.getTransitiveSymbolsBin());
    }

    builder.buildAndRegister("Merging Android resources", "AndroidResourceMerger");
  }

  private void build(AndroidDataContext dataContext) {
    BusyBoxActionBuilder parsedMergeBuilder = BusyBoxActionBuilder.create(dataContext, "MERGE");
    BusyBoxActionBuilder compiledMergeBuilder =
        BusyBoxActionBuilder.create(dataContext, "MERGE_COMPILED");

    parsedMergeBuilder.addOutput("--resourcesOutput", mergedResourcesOut);

    // TODO(corysmith): Move the data binding parsing out of the merging pass to enable faster
    // aapt2 builds.
    parsedMergeBuilder.maybeAddOutput("--dataBindingInfoOut", dataBindingInfoZip);

    (useCompiledMerge ? compiledMergeBuilder : parsedMergeBuilder)
        .addOutput("--classJarOutput", classJarOut)
        .addLabelFlag("--targetLabel")

        // For now, do manifest processing to remove placeholders that aren't handled by the legacy
        // manifest merger. Remove this once enough users migrate over to the new manifest merger.
        .maybeAddOutput("--manifestOutput", manifestOut);

    if (useCompiledMerge) {
      buildCompiledResourceMergingAction(compiledMergeBuilder);
    }

    // Always make an action for merging parsed resources - the merged resources are still created
    // this way.
    buildParsedResourceMergingAction(parsedMergeBuilder);
  }

  public ResourceContainer build(
      AndroidDataContext dataContext, ResourceContainer resourceContainer) {
    withPrimary(resourceContainer).build(dataContext);

    // Return the full set of processed transitive dependencies.
    ResourceContainer.Builder result = resourceContainer.toBuilder();

    result.setJavaClassJar(classJarOut);

    if (manifestOut != null) {
      result.setManifest(manifestOut);
    }
    if (mergedResourcesOut != null) {
      result.setMergedResources(mergedResourcesOut);
    }
    return result.build();
  }

  public MergedAndroidResources build(
      AndroidDataContext dataContext, ParsedAndroidResources parsed) {
    withPrimary(parsed).build(dataContext);

    return MergedAndroidResources.of(
        parsed,
        mergedResourcesOut,
        classJarOut,
        dataBindingInfoZip,
        dependencies,
        parsed.getStampedManifest().withProcessedManifest(manifestOut));
  }
}


text:
* Update minimum Ruby version to 2.6 ([#75](https://github.com/googleapis/common-protos-ruby/issues/75))

### 1.0.1 (2022-06-23)

#### Bug Fixes

* Remove some unnecessary requires

### 1.0.0 (2021-10-19)

* Initial creation of google-cloud-common


text:
from flask import render_template, url_for, request, redirect
from flask.ext.login import login_required, current_user

import rfk
import rfk.site
import rfk.database
import rfk.liquidsoap
from rfk.site.helper import permission_required
from rfk.site.forms.stream import new_stream
from rfk.database.streaming import Stream, Relay
from rfk.exc.streaming import CodeTakenException, InvalidCodeException, MountpointTakenException

from ..admin import admin

@admin.route('/streams')
@login_required
def streams():
    return render_template('admin/streams.html')

@admin.route('/stream')
@login_required
@permission_required(permission='manage-liquidsoap')
def stream_list():
    streams = Stream.query.all()
    return render_template('admin/stream/list.html', streams=streams)

@admin.route('/stream/add', methods=['GET', 'POST'])
@login_required
@permission_required(permission='manage-liquidsoap')
def stream_add():
    form = new_stream(request.form)
    if request.method == 'POST' and form.validate():
        try:
            if form.type.data != 0:
                Stream.add_stream(form.code.data, form.name.data, form.mount.data, form.type.data, form.quality.data)
                rfk.database.session.commit()
                return redirect(url_for('.stream_list'))
            else:
                form.type.errors.append('Invalid type')
        except InvalidCodeException as e:
            form.code.errors.append('Invalid Chars')
        except CodeTakenException as e:
            form.code.errors.append('Identifier Taken')
        except MountpointTakenException as e:
            form.mount.errors.append('Mountpoint already taken')
    return render_template('admin/stream/streamform.html', form=form)


text:
package repository

import (
	"github.com/asdine/storm"
	"github.com/cswank/quimby/internal/schema"
)

// User does database-y things.
type User struct {
	db *storm.DB
}

func (u User) GetAll() ([]schema.User, error) {
	var out []schema.User
	return out, u.db.All(&out)
}

func (u User) Get(username string) (schema.User, error) {
	var out schema.User
	return out, u.db.One("Name", username, &out)
}

func (u User) Create(name string, pw, tfa []byte) (*schema.User, error) {
	out := &schema.User{Name: name, Password: pw, TFA: tfa}
	return out, u.db.Save(out)
}

func (u User) Delete(name string) error {
	out, err := u.Get(name)
	if err != nil {
		return err
	}
	return u.db.DeleteStruct(&out)
}


text:
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include <asm-generic/sections.h>
#include <asm/cpu_device_id.h>
#include <asm/imr.h>
#include <asm/iosf_mbi.h>
#include <linux/debugfs.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/types.h>

struct imr_device {
	struct dentry	*file;
	bool		init;
	struct mutex	lock;
	int		max_imr;
	int		reg_base;
};

static struct imr_device imr_dev;

/*
 * IMR read/write mask control registers.
 * See quark-x1000-datasheet.pdf sections 12.7.4.5 and 12.7.4.6 for
 * bit definitions.
 *
 * addr_hi
 * 31		Lock bit
 * 30:24	Reserved
 * 23:2		1 KiB aligned lo address
 * 1:0		Reserved
 *
 * addr_hi
 * 31:24	Reserved
 * 23:2		1 KiB aligned hi address
 * 1:0		Reserved
 */
#define IMR_LOCK	BIT(31)

struct imr_regs {
	u32 addr_lo;
	u32 addr_hi;
	u32 rmask;
	u32 wmask;
};

#define IMR_NUM_REGS	(sizeof(struct imr_regs)/sizeof(u32))
#define IMR_SHIFT	8
#define imr_to_phys(x)	((x) << IMR_SHIFT)
#define phys_to_imr(x)	((x) >> IMR_SHIFT)

/**
 * imr_is_enabled - true if an IMR is enabled false otherwise.
 *
 * Determines if an IMR is enabled based on address range and read/write
 * mask. An IMR set with an address range set to zero and a read/write
 * access mask set to all is considered to be disabled. An IMR in any
 * other state - for example set to zero but without read/write access
 * all is considered to be enabled. This definition of disabled is how
 * firmware switches off an IMR and is maintained in kernel for
 * consistency.
 *
 * @imr:	pointer to IMR descriptor.
 * @return:	true if IMR enabled false if disabled.
 */
static inline int imr_is_enabled(struct imr_regs *imr)
{
	return !(imr->rmask == IMR_READ_ACCESS_ALL &&
		 imr->wmask == IMR_WRITE_ACCESS_ALL &&
		 imr_to_phys(imr->addr_lo) == 0 &&
		 imr_to_phys(imr->addr_hi) == 0);
}

/**
 * imr_read - read an IMR at a given index.
 *
 * Requires caller to hold imr mutex.
 *
 * @idev:	pointer to imr_device structure.
 * @imr_id:	IMR entry to read.
 * @imr:	IMR structure representing address and access masks.
 * @return:	0 on success or error code passed from mbi_iosf on failure.
 */
static int imr_read(struct imr_device *idev, u32 imr_id, struct imr_regs *imr)
{
	u32 reg = imr_id * IMR_NUM_REGS + idev->reg_base;
	int ret;

	ret = iosf_mbi_read(QRK_MBI_UNIT_MM, QRK_MBI_MM_READ,
				reg++, &imr->addr_lo);
	if (ret)
		return ret;

	ret = iosf_mbi_read(QRK_MBI_UNIT_MM, QRK_MBI_MM_READ,
				reg++, &imr->addr_hi);
	if (ret)
		return ret;

	ret = iosf_mbi_read(QRK_MBI_UNIT_MM, QRK_MBI_MM_READ,
				reg++, &imr->rmask);
	if (ret)
		return ret;

	return iosf_mbi_read(QRK_MBI_UNIT_MM, QRK_MBI_MM_READ,
				reg++, &imr->wmask);
}

/**
 * imr_write - write an IMR at a given index.
 *
 * Requires caller to hold imr mutex.
 * Note lock bits need to be written independently of address bits.
 *
 * @idev:	pointer to imr_device structure.
 * @imr_id:	IMR entry to write.
 * @imr:	IMR structure representing address and access masks.
 * @lock:	indicates if the IMR lock bit should be applied.
 * @return:	0 on success or error code passed from mbi_iosf on failure.
 */
static int imr_write(struct imr_device *idev, u32 imr_id,
		     struct imr_regs *imr, bool lock)
{
	unsigned long flags;
	u32 reg = imr_id * IMR_NUM_REGS + idev->reg_base;
	int ret;

	local_irq_save(flags);

	ret = iosf_mbi_write(QRK_MBI_UNIT_MM, QRK_MBI_MM_WRITE, reg++,
				imr->addr_lo);
	if (ret)
		goto failed;

	ret = iosf_mbi_write(QRK_MBI_UNIT_MM, QRK_MBI_MM_WRITE,
				reg++, imr->addr_hi);
	if (ret)
		goto failed;

	ret = iosf_mbi_write(QRK_MBI_UNIT_MM, QRK_MBI_MM_WRITE,
				reg++, imr->rmask);
	if (ret)
		goto failed;

	ret = iosf_mbi_write(QRK_MBI_UNIT_MM, QRK_MBI_MM_WRITE,
				reg++, imr->wmask);
	if (ret)
		goto failed;

	/* Lock bit must be set separately to addr_lo address bits. */
	if (lock) {
		imr->addr_lo |= IMR_LOCK;
		ret = iosf_mbi_write(QRK_MBI_UNIT_MM, QRK_MBI_MM_WRITE,
					reg - IMR_NUM_REGS, imr->addr_lo);
		if (ret)
			goto failed;
	}

	local_irq_restore(flags);
	return 0;
failed:
	/*
	 * If writing to the IOSF failed then we're in an unknown state,
	 * likely a very bad state. An IMR in an invalid state will almost
	 * certainly lead to a memory access violation.
	 */
	local_irq_restore(flags);
	WARN(ret, "IOSF-MBI write fail range 0x%08x-0x%08x unreliable\n",
	     imr_to_phys(imr->addr_lo), imr_to_phys(imr->addr_hi) + IMR_MASK);

	return ret;
}

/**
 * imr_dbgfs_state_show - print state of IMR registers.
 *
 * @s:		pointer to seq_file for output.
 * @unused:	unused parameter.
 * @return:	0 on success or error code passed from mbi_iosf on failure.
 */
static int imr_dbgfs_state_show(struct seq_file *s, void *unused)
{
	phys_addr_t base;
	phys_addr_t end;
	int i;
	struct imr_device *idev = s->private;
	struct imr_regs imr;
	size_t size;
	int ret = -ENODEV;

	mutex_lock(&idev->lock);

	for (i = 0; i < idev->max_imr; i++) {

		ret = imr_read(idev, i, &imr);
		if (ret)
			break;

		/*
		 * Remember to add IMR_ALIGN bytes to size to indicate the
		 * inherent IMR_ALIGN size bytes contained in the masked away
		 * lower ten bits.
		 */
		if (imr_is_enabled(&imr)) {
			base = imr_to_phys(imr.addr_lo);
			end = imr_to_phys(imr.addr_hi) + IMR_MASK;
		} else {
			base = 0;
			end = 0;
		}
		size = end - base;
		seq_printf(s, "imr%02i: base=%pa, end=%pa, size=0x%08zx "
			   "rmask=0x%08x, wmask=0x%08x, %s, %s\n", i,
			   &base, &end, size, imr.rmask, imr.wmask,
			   imr_is_enabled(&imr) ? "enabled " : "disabled",
			   imr.addr_lo & IMR_LOCK ? "locked" : "unlocked");
	}

	mutex_unlock(&idev->lock);
	return ret;
}

/**
 * imr_state_open - debugfs open callback.
 *
 * @inode:	pointer to struct inode.
 * @file:	pointer to struct file.
 * @return:	result of single open.
 */
static int imr_state_open(struct inode *inode, struct file *file)
{
	return single_open(file, imr_dbgfs_state_show, inode->i_private);
}

static const struct file_operations imr_state_ops = {
	.open		= imr_state_open,
	.read		= seq_read,
	.llseek		= seq_lseek,
	.release	= single_release,
};

/**
 * imr_debugfs_register - register debugfs hooks.
 *
 * @idev:	pointer to imr_device structure.
 * @return:	0 on success - errno on failure.
 */
static int imr_debugfs_register(struct imr_device *idev)
{
	idev->file = debugfs_create_file("imr_state", S_IFREG | S_IRUGO, NULL,
					 idev, &imr_state_ops);
	return PTR_ERR_OR_ZERO(idev->file);
}

/**
 * imr_debugfs_unregister - unregister debugfs hooks.
 *
 * @idev:	pointer to imr_device structure.
 * @return:
 */
static void imr_debugfs_unregister(struct imr_device *idev)
{
	debugfs_remove(idev->file);
}

/**
 * imr_check_params - check passed address range IMR alignment and non-zero size
 *
 * @base:	base address of intended IMR.
 * @size:	size of intended IMR.
 * @return:	zero on valid range -EINVAL on unaligned base/size.
 */
static int imr_check_params(phys_addr_t base, size_t size)
{
	if ((base & IMR_MASK) || (size & IMR_MASK)) {
		pr_err("base %pa size 0x%08zx must align to 1KiB\n",
			&base, size);
		return -EINVAL;
	}
	if (size == 0)
		return -EINVAL;

	return 0;
}

/**
 * imr_raw_size - account for the IMR_ALIGN bytes that addr_hi appends.
 *
 * IMR addr_hi has a built in offset of plus IMR_ALIGN (0x400) bytes from the
 * value in the register. We need to subtract IMR_ALIGN bytes from input sizes
 * as a result.
 *
 * @size:	input size bytes.
 * @return:	reduced size.
 */
static inline size_t imr_raw_size(size_t size)
{
	return size - IMR_ALIGN;
}

/**
 * imr_address_overlap - detects an address overlap.
 *
 * @addr:	address to check against an existing IMR.
 * @imr:	imr being checked.
 * @return:	true for overlap false for no overlap.
 */
static inline int imr_address_overlap(phys_addr_t addr, struct imr_regs *imr)
{
	return addr >= imr_to_phys(imr->addr_lo) && addr <= imr_to_phys(imr->addr_hi);
}

/**
 * imr_add_range - add an Isolated Memory Region.
 *
 * @base:	physical base address of region aligned to 1KiB.
 * @size:	physical size of region in bytes must be aligned to 1KiB.
 * @read_mask:	read access mask.
 * @write_mask:	write access mask.
 * @lock:	indicates whether or not to permanently lock this region.
 * @return:	zero on success or negative value indicating error.
 */
int imr_add_range(phys_addr_t base, size_t size,
		  unsigned int rmask, unsigned int wmask, bool lock)
{
	phys_addr_t end;
	unsigned int i;
	struct imr_device *idev = &imr_dev;
	struct imr_regs imr;
	size_t raw_size;
	int reg;
	int ret;

	if (WARN_ONCE(idev->init == false, "driver not initialized"))
		return -ENODEV;

	ret = imr_check_params(base, size);
	if (ret)
		return ret;

	/* Tweak the size value. */
	raw_size = imr_raw_size(size);
	end = base + raw_size;

	/*
	 * Check for reserved IMR value common to firmware, kernel and grub
	 * indicating a disabled IMR.
	 */
	imr.addr_lo = phys_to_imr(base);
	imr.addr_hi = phys_to_imr(end);
	imr.rmask = rmask;
	imr.wmask = wmask;
	if (!imr_is_enabled(&imr))
		return -ENOTSUPP;

	mutex_lock(&idev->lock);

	/*
	 * Find a free IMR while checking for an existing overlapping range.
	 * Note there's no restriction in silicon to prevent IMR overlaps.
	 * For the sake of simplicity and ease in defining/debugging an IMR
	 * memory map we exclude IMR overlaps.
	 */
	reg = -1;
	for (i = 0; i < idev->max_imr; i++) {
		ret = imr_read(idev, i, &imr);
		if (ret)
			goto failed;

		/* Find overlap @ base or end of requested range. */
		ret = -EINVAL;
		if (imr_is_enabled(&imr)) {
			if (imr_address_overlap(base, &imr))
				goto failed;
			if (imr_address_overlap(end, &imr))
				goto failed;
		} else {
			reg = i;
		}
	}

	/* Error out if we have no free IMR entries. */
	if (reg == -1) {
		ret = -ENOMEM;
		goto failed;
	}

	pr_debug("add %d phys %pa-%pa size %zx mask 0x%08x wmask 0x%08x\n",
		 reg, &base, &end, raw_size, rmask, wmask);

	/* Enable IMR at specified range and access mask. */
	imr.addr_lo = phys_to_imr(base);
	imr.addr_hi = phys_to_imr(end);
	imr.rmask = rmask;
	imr.wmask = wmask;

	ret = imr_write(idev, reg, &imr, lock);
	if (ret < 0) {
		/*
		 * In the highly unlikely event iosf_mbi_write failed
		 * attempt to rollback the IMR setup skipping the trapping
		 * of further IOSF write failures.
		 */
		imr.addr_lo = 0;
		imr.addr_hi = 0;
		imr.rmask = IMR_READ_ACCESS_ALL;
		imr.wmask = IMR_WRITE_ACCESS_ALL;
		imr_write(idev, reg, &imr, false);
	}
failed:
	mutex_unlock(&idev->lock);
	return ret;
}
EXPORT_SYMBOL_GPL(imr_add_range);

/**
 * __imr_remove_range - delete an Isolated Memory Region.
 *
 * This function allows you to delete an IMR by its index specified by reg or
 * by address range specified by base and size respectively. If you specify an
 * index on its own the base and size parameters are ignored.
 * imr_remove_range(0, base, size); delete IMR at index 0 base/size ignored.
 * imr_remove_range(-1, base, size); delete IMR from base to base+size.
 *
 * @reg:	imr index to remove.
 * @base:	physical base address of region aligned to 1 KiB.
 * @size:	physical size of region in bytes aligned to 1 KiB.
 * @return:	-EINVAL on invalid range or out or range id
 *		-ENODEV if reg is valid but no IMR exists or is locked
 *		0 on success.
 */
static int __imr_remove_range(int reg, phys_addr_t base, size_t size)
{
	phys_addr_t end;
	bool found = false;
	unsigned int i;
	struct imr_device *idev = &imr_dev;
	struct imr_regs imr;
	size_t raw_size;
	int ret = 0;

	if (WARN_ONCE(idev->init == false, "driver not initialized"))
		return -ENODEV;

	/*
	 * Validate address range if deleting by address, else we are
	 * deleting by index where base and size will be ignored.
	 */
	if (reg == -1) {
		ret = imr_check_params(base, size);
		if (ret)
			return ret;
	}

	/* Tweak the size value. */
	raw_size = imr_raw_size(size);
	end = base + raw_size;

	mutex_lock(&idev->lock);

	if (reg >= 0) {
		/* If a specific IMR is given try to use it. */
		ret = imr_read(idev, reg, &imr);
		if (ret)
			goto failed;

		if (!imr_is_enabled(&imr) || imr.addr_lo & IMR_LOCK) {
			ret = -ENODEV;
			goto failed;
		}
		found = true;
	} else {
		/* Search for match based on address range. */
		for (i = 0; i < idev->max_imr; i++) {
			ret = imr_read(idev, i, &imr);
			if (ret)
				goto failed;

			if (!imr_is_enabled(&imr) || imr.addr_lo & IMR_LOCK)
				continue;

			if ((imr_to_phys(imr.addr_lo) == base) &&
			    (imr_to_phys(imr.addr_hi) == end)) {
				found = true;
				reg = i;
				break;
			}
		}
	}

	if (!found) {
		ret = -ENODEV;
		goto failed;
	}

	pr_debug("remove %d phys %pa-%pa size %zx\n", reg, &base, &end, raw_size);

	/* Tear down the IMR. */
	imr.addr_lo = 0;
	imr.addr_hi = 0;
	imr.rmask = IMR_READ_ACCESS_ALL;
	imr.wmask = IMR_WRITE_ACCESS_ALL;

	ret = imr_write(idev, reg, &imr, false);

failed:
	mutex_unlock(&idev->lock);
	return ret;
}

/**
 * imr_remove_range - delete an Isolated Memory Region by address
 *
 * This function allows you to delete an IMR by an address range specified
 * by base and size respectively.
 * imr_remove_range(base, size); delete IMR from base to base+size.
 *
 * @base:	physical base address of region aligned to 1 KiB.
 * @size:	physical size of region in bytes aligned to 1 KiB.
 * @return:	-EINVAL on invalid range or out or range id
 *		-ENODEV if reg is valid but no IMR exists or is locked
 *		0 on success.
 */
int imr_remove_range(phys_addr_t base, size_t size)
{
	return __imr_remove_range(-1, base, size);
}
EXPORT_SYMBOL_GPL(imr_remove_range);

/**
 * imr_clear - delete an Isolated Memory Region by index
 *
 * This function allows you to delete an IMR by an address range specified
 * by the index of the IMR. Useful for initial sanitization of the IMR
 * address map.
 * imr_ge(base, size); delete IMR from base to base+size.
 *
 * @reg:	imr index to remove.
 * @return:	-EINVAL on invalid range or out or range id
 *		-ENODEV if reg is valid but no IMR exists or is locked
 *		0 on success.
 */
static inline int imr_clear(int reg)
{
	return __imr_remove_range(reg, 0, 0);
}

/**
 * imr_fixup_memmap - Tear down IMRs used during bootup.
 *
 * BIOS and Grub both setup IMRs around compressed kernel, initrd memory
 * that need to be removed before the kernel hands out one of the IMR
 * encased addresses to a downstream DMA agent such as the SD or Ethernet.
 * IMRs on Galileo are setup to immediately reset the system on violation.
 * As a result if you're running a root filesystem from SD - you'll need
 * the boot-time IMRs torn down or you'll find seemingly random resets when
 * using your filesystem.
 *
 * @idev:	pointer to imr_device structure.
 * @return:
 */
static void __init imr_fixup_memmap(struct imr_device *idev)
{
	phys_addr_t base = virt_to_phys(&_text);
	size_t size = virt_to_phys(&__end_rodata) - base;
	int i;
	int ret;

	/* Tear down all existing unlocked IMRs. */
	for (i = 0; i < idev->max_imr; i++)
		imr_clear(i);

	/*
	 * Setup a locked IMR around the physical extent of the kernel
	 * from the beginning of the .text secton to the end of the
	 * .rodata section as one physically contiguous block.
	 */
	ret = imr_add_range(base, size, IMR_CPU, IMR_CPU, true);
	if (ret < 0) {
		pr_err("unable to setup IMR for kernel: (%p - %p)\n",
			&_text, &__end_rodata);
	} else {
		pr_info("protecting kernel .text - .rodata: %zu KiB (%p - %p)\n",
			size / 1024, &_text, &__end_rodata);
	}

}

static const struct x86_cpu_id imr_ids[] __initconst = {
	{ X86_VENDOR_INTEL, 5, 9 },	/* Intel Quark SoC X1000. */
	{}
};
MODULE_DEVICE_TABLE(x86cpu, imr_ids);

/**
 * imr_init - entry point for IMR driver.
 *
 * return: -ENODEV for no IMR support 0 if good to go.
 */
static int __init imr_init(void)
{
	struct imr_device *idev = &imr_dev;
	int ret;

	if (!x86_match_cpu(imr_ids) || !iosf_mbi_available())
		return -ENODEV;

	idev->max_imr = QUARK_X1000_IMR_MAX;
	idev->reg_base = QUARK_X1000_IMR_REGBASE;
	idev->init = true;

	mutex_init(&idev->lock);
	ret = imr_debugfs_register(idev);
	if (ret != 0)
		pr_warn("debugfs register failed!\n");
	imr_fixup_memmap(idev);
	return 0;
}

/**
 * imr_exit - exit point for IMR code.
 *
 * Deregisters debugfs, leave IMR state as-is.
 *
 * return:
 */
static void __exit imr_exit(void)
{
	imr_debugfs_unregister(&imr_dev);
}

module_init(imr_init);
module_exit(imr_exit);

MODULE_AUTHOR("Bryan O'Donoghue <pure.logic@nexus-software.ie>");
MODULE_DESCRIPTION("Intel Isolated Memory Region driver");
MODULE_LICENSE("Dual BSD/GPL");


text:
package com.coveros.selenified.element;

import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.log4testng.Logger;

/**
 * Is retrieves information about a particular element. A boolean is always
 * returning, indicating if an object is present or not
 *
 * @author Max Saperstone
 * @version 3.3.1
 * @lastupdate 3/7/2019
 */
public class Is {

    private static final Logger log = Logger.getLogger(Is.class);
    // constants
    private static final String SELECT = "select";
    // what element are we trying to interact with on the page
    private final Element element;

    public Is(Element element) {
        this.element = element;
    }

    // ////////////////////////////////////
    // checking element availability
    // ////////////////////////////////////

    /**
     * Determines whether the element is present or not.
     *
     * @return Boolean: whether the element is present or not
     */
    public boolean present() {
        boolean isPresent = false;
        try {
            element.getWebElement().getText();
            isPresent = true;
        } catch (NoSuchElementException | StaleElementReferenceException e) {
            log.info(e);
        }
        return isPresent;
    }

    /**
     * Determines whether the element is an input or not. An input could be an
     * input element, a textarea, or a select
     *
     * @return Boolean: whether the element is an input or not
     */
    public boolean input() {
        boolean isInput = false;
        try {
            String elementTag = element.get().tagName();
            if ("input".equalsIgnoreCase(elementTag) ||
                    "textarea".equalsIgnoreCase(elementTag) ||
                    SELECT.equalsIgnoreCase(elementTag)) {
                isInput = true;
            }
        } catch (NoSuchElementException e) {
            log.info(e);
        }
        return isInput;
    }

    /**
     * Determines whether the element is a select or not.
     *
     * @return Boolean: whether the element is an input or not
     */
    public boolean select() {
        boolean isSelect = false;
        try {
            if (SELECT.equalsIgnoreCase(element.get().tagName())) {
                isSelect = true;
            }
        } catch (NoSuchElementException e) {
            log.info(e);
        }
        return isSelect;
    }

    /**
     * Determines whether the element is a table or not.
     *
     * @return Boolean: whether the element is an input or not
     */
    public boolean table() {
        boolean isTable = false;
        try {
            if ("table".equalsIgnoreCase(element.get().tagName())) {
                isTable = true;
            }
        } catch (NoSuchElementException e) {
            log.info(e);
        }
        return isTable;
    }

    /**
     * Determines whether the element is enabled or not.
     *
     * @return Boolean: whether the element is enabled or not
     */
    public boolean enabled() {
        boolean isEnabled = false;
        try {
            // adding additional check for disabled attribute, due to issues with safari
            isEnabled = (element.getWebElement().isEnabled() && !element.get().allAttributes().containsKey("disabled"));
        } catch (NullPointerException | NoSuchElementException e) {
            // Null pointer means the element was deleted, and there has no attributes. No such element means the same thing
            log.info(e);
        }
        return isEnabled;
    }

    /**
     * Determines whether the element is editable or not. To be editable, it must
     * be an input, and enabled
     *
     * @return Boolean: whether the element is editable or not
     */
    public boolean editable() {
        return enabled() && input();
    }

    /**
     * Determines whether the element is checked or not.
     *
     * @return Boolean: whether the element is checked or not
     */
    public boolean checked() {
        boolean isChecked = false;
        try {
            isChecked = element.getWebElement().isSelected();
        } catch (Exception e) {
            log.info(e);
        }
        return isChecked;
    }

    /**
     * Determines whether the element is displayed or not.
     *
     * @return Boolean: whether the element is displayed or not
     */
    public boolean displayed() {
        boolean isDisplayed = false;
        try {
            isDisplayed = element.getWebElement().isDisplayed();
        } catch (NoSuchElementException e) {
            log.info(e);
        }
        return isDisplayed;
    }

    /**
     * Determines whether the element has something selected or not. Checkboxes,
     * radio buttons, and selects could all have something selected. Other
     * elements will default to false.
     *
     * @return Boolean: is something selected or not
     */
    public boolean somethingSelected() {
        boolean isSelected = false;
        if (input()) {
            String elementTag = element.get().tagName();
            WebElement webElement = element.getWebElement();
            if ("input".equalsIgnoreCase(elementTag)) {
                isSelected = webElement.isSelected();
            } else if (SELECT.equalsIgnoreCase(elementTag)) {
                Select dropdown = new Select(webElement);
                isSelected = !dropdown.getAllSelectedOptions().isEmpty();
            }
        }
        return isSelected;
    }
}


text:
package uk.co.blueberrymoss.spark.training.tasks.messages;

import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;

import com.cloupia.model.cIM.FormFieldDefinition;
import com.cloupia.service.cIM.inframgr.TaskConfigIf;
import com.cloupia.service.cIM.inframgr.customactions.UserInputField;
import com.cloupia.service.cIM.inframgr.forms.wizard.FormField;

import uk.co.blueberrymoss.spark.training.constants.Constants;

/**
 * Configuration task to delete a message from a Spark room
 * <p>
 * This provides the GUI and configuration elements to execute this task. It can
 * be used via an action button or as a workflow task.
 *
 * @author Matt Day
 * @see SendMessageTask
 */
@PersistenceCapable(detachable = "true", table = "SparkTraining_delete_message_from_room")
public class DeleteMessageConfig implements TaskConfigIf {

	@Persistent
	private long configEntryId;

	@Persistent
	private long actionId;

	@FormField(label = "Spark Account", help = "The account from which to send this message", mandatory = true, type = FormFieldDefinition.FIELD_TYPE_TABULAR_POPUP, table = Constants.ACCOUNT_INPUT_NAME)
	@UserInputField(type = Constants.ACCOUNT_INPUT_NAME)
	@Persistent
	private String account;

	@FormField(label = "Message ID", help = "Message ID Number", mandatory = true, type = FormFieldDefinition.FIELD_TYPE_TEXT)
	@UserInputField(type = Constants.GENERIC_TEXT_INPUT)
	@Persistent
	private String messageId;

	/**
	 * Empty default constructor - you could initialise default values here if
	 * you wanted, for example pick an account by default
	 */
	public DeleteMessageConfig() {
		super();
	}

	/**
	 * Rollback constructor. This is used from the SendMessageTask to allow UCS
	 * Director to undo the message posted.
	 *
	 * @param config
	 *            Original configuration to post the message
	 * @param messageId
	 *            Message ID from posted message
	 *
	 * @see SendMessageTask
	 */
	public DeleteMessageConfig(SendMessageConfig config, String messageId) {
		this.setAccount(config.getAccount());
		this.setMessageId(messageId);
	}

	/**
	 * @return the selected account
	 */
	public String getAccount() {
		// We're only interested in the first part, remove anything after ;
		return this.account.split(";")[0];
	}

	/**
	 * Set the account
	 *
	 * @param account
	 *            Account to set
	 */
	public void setAccount(String account) {
		this.account = account;
	}

	/**
	 * @return Message ID set by the user
	 */
	public String getMessageId() {
		return this.messageId;
	}

	/**
	 * Set the message ID
	 *
	 * @param messageId
	 *            message ID to set
	 */
	public void setMessageId(String messageId) {
		this.messageId = messageId;
	}

	@Override
	public long getActionId() {
		return this.actionId;
	}

	@Override
	public long getConfigEntryId() {
		return this.configEntryId;
	}

	@Override
	public String getDisplayLabel() {
		return "Delete Spark Message";
	}

	@Override
	public void setActionId(long actionId) {
		this.actionId = actionId;
	}

	@Override
	public void setConfigEntryId(long configEntryId) {
		this.configEntryId = configEntryId;
	}

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Mac
 */
@WebServlet(name = "selectStudentController", urlPatterns = {"/select-student"})
public class selectStudentController extends HttpServlet {

    /**
     * Processes requests for both HTTP GET and POST
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //do nothing
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //get data from the model
        request.getRequestDispatcher("View/selectStudent.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //get student id from form and put on request
        request.getRequestDispatcher("select-course").forward(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


text:
package org.jboss.netty.handler.codec.base64;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelHandler.Sharable;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.Delimiters;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;

/**
 * Encodes a {@link ChannelBuffer} into a Base64-encoded {@link ChannelBuffer}.
 * A typical setup for TCP/IP would be:
 *

 * {@link ChannelPipeline} pipeline = ...;
 *
 * // Decoders
 * pipeline.addLast("frameDecoder", new {@link DelimiterBasedFrameDecoder}(80, {@link Delimiters#nulDelimiter()}));
 * pipeline.addLast("base64Decoder", new {@link Base64Decoder}());
 *
 * // Encoder
 * pipeline.addLast("base64Encoder", new {@link Base64Encoder}());
 *

 *
 * @author The Netty Project
 * @author Trustin Lee
 * @version $Rev: 2241 $, $Date: 2010-04-16 13:12:43 +0900 (Fri, 16 Apr 2010) $
 *
 * @apiviz.landmark
 * @apiviz.uses org.jboss.netty.handler.codec.base64.Base64
 */
@Sharable
public class Base64Encoder extends OneToOneEncoder {

    private final boolean breakLines;
    private final Base64Dialect dialect;

    public Base64Encoder() {
        this(true);
    }

    public Base64Encoder(boolean breakLines) {
        this(breakLines, Base64Dialect.STANDARD);
    }

    public Base64Encoder(boolean breakLines, Base64Dialect dialect) {
        if (dialect == null) {
            throw new NullPointerException("dialect");
        }

        this.breakLines = breakLines;
        this.dialect = dialect;
    }

    @Override
    protected Object encode(ChannelHandlerContext ctx, Channel channel,
            Object msg) throws Exception {
        if (!(msg instanceof ChannelBuffer)) {
            return msg;
        }

        ChannelBuffer src = (ChannelBuffer) msg;
        return Base64.encode(
                src, src.readerIndex(), src.readableBytes(),
                breakLines, dialect);
    }
}


text:
<?php

declare(strict_types=1);

namespace FunTimeCoding\PhpUtility\LanguageExample\RabbitMessageQueue;

use ErrorException;

class Consumer
{
    /**
     * @throws ErrorException
     */
    public function main(): void
    {
        $helper = new Helper();

        $channel = $helper->connect();
        $callback = static function ($msg): void {
            echo $msg->body . PHP_EOL;
        };
        $channel->basic_consume(
            'hello',
            '',
            false,
            true,
            false,
            false,
            $callback
        );

        while ($channel->is_consuming()) {
            $channel->wait();
        }
    }
}


text:
package org.wso2.carbon.apimgt.gateway.handlers.security.model;

import com.atlassian.oai.validator.model.Request;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.wso2.carbon.apimgt.gateway.APIMgtGatewayConstants;
import org.wso2.carbon.apimgt.gateway.handlers.security.utils.SchemaValidationUtils;

import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.annotation.Nonnull;

/**
 * Request Model class for OpenAPI
 */
public class OpenAPIRequest implements Request {

    private static final Log logger = LogFactory.getLog(OpenAPIRequest.class);
    private static final String REST_SUB_REQUEST_PATH = "REST_SUB_REQUEST_PATH";
    private Request.Method method;
    private String path;
    private Multimap<String, String> headers = ArrayListMultimap.create();
    private Map<String, Collection<String>> queryParams;
    private Optional<String> requestBody;
    /**
     * Build OAI Request from Message Context.
     *
     * @param messageContext Synapse message context.
     * @return OAI Request.
     */
    public OpenAPIRequest(MessageContext messageContext) {

        org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext)
                messageContext).getAxis2MessageContext();
        //set HTTP Method
        method = Request.Method.valueOf((String)
                messageContext.getProperty(APIMgtGatewayConstants.HTTP_METHOD));
        //Set Request path
        path = SchemaValidationUtils.getRestSubRequestPath(
                messageContext.getProperty(REST_SUB_REQUEST_PATH).toString());
        //extract transport headers
        Map<String, String> transportHeaders = (Map<String, String>)
                (axis2MessageContext.getProperty(APIMgtGatewayConstants.TRANSPORT_HEADERS));
        //Set Request body
        requestBody = SchemaValidationUtils.getMessageContent(messageContext);
        Map<String, Collection<String>> headerMap = transportHeaders.entrySet()
                .stream()
                .collect(Collectors.toMap(Map.Entry::getKey, entry -> Collections.singleton(entry.getValue())));
        //Set transport headers
        for (Map.Entry<String, Collection<String>> header : headerMap.entrySet()) {
            headers.put(header.getKey(), header.getValue().iterator().next());
        }
        String apiResource = messageContext.getProperty(APIMgtGatewayConstants.RESOURCE).toString();
        //Extracting query params
        try {
            queryParams = SchemaValidationUtils.getQueryParams(apiResource, (String)
                    messageContext.getProperty(APIMgtGatewayConstants.API_ELECTED_RESOURCE));
        } catch (UnsupportedEncodingException e) {
            logger.error("Failed to decode query string");
        }
    }

    @Nonnull
    @Override
    public String getPath() {

        return this.path;
    }

    @Nonnull
    @Override
    public Method getMethod() {

        return this.method;
    }

    @Nonnull
    @Override
    public Optional<String> getBody() {

        return this.requestBody;
    }

    @Nonnull
    @Override
    public Collection<String> getQueryParameters() {

        if (this.queryParams == null) {
            return Collections.emptyList();
        }
        return Collections.unmodifiableCollection(this.queryParams.keySet());
    }

    @Nonnull
    @Override
    public Collection<String> getQueryParameterValues(String s) {

        if (this.queryParams == null) {
            return Collections.emptyList();
        }
        return SchemaValidationUtils.getFromMapOrEmptyList(this.queryParams, s);
    }

    @Nonnull
    @Override
    public Map<String, Collection<String>> getHeaders() {

        if (this.headers == null) {
            return Collections.emptyMap();
        }
        return headers.asMap();
    }

    @Nonnull
    @Override
    public Collection<String> getHeaderValues(String s) {

        if (this.headers == null) {
            return Collections.emptyList();
        }
        return SchemaValidationUtils.getFromMapOrEmptyList(this.headers.asMap(), s);
    }

}


text:
package org.apache.curator.framework.imps;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
import java.util.zip.GZIPOutputStream;

public class TestGzipCompressionProvider
{
    @Test
    public void testSimple() throws IOException
    {
        GzipCompressionProvider provider = new GzipCompressionProvider();
        byte[] data = "Hello, world!".getBytes();
        byte[] compressedData = provider.compress(null, data);
        byte[] jdkCompressedData = jdkCompress(data);
        assertTrue(Arrays.equals(compressedData, jdkCompressedData));
        byte[] decompressedData = provider.decompress(null, compressedData);
        assertTrue(Arrays.equals(decompressedData, data));
    }

    @Test
    public void testEmpty() throws IOException
    {
        GzipCompressionProvider provider = new GzipCompressionProvider();
        byte[] compressedData = provider.compress(null, new byte[0]);
        byte[] compressedData2 = GzipCompressionProvider.doCompress(new byte[0]);
        byte[] jdkCompress = jdkCompress(new byte[0]);
        // Ensures GzipCompressionProvider.COMPRESSED_EMPTY_BYTES value is valid
        assertTrue(Arrays.equals(compressedData, compressedData2));
        assertTrue(Arrays.equals(compressedData, jdkCompress));
        byte[] decompressedData = provider.decompress(null, compressedData);
        assertEquals(0, decompressedData.length);
    }

    /**
     * This test ensures that in the face of corrupt data, specifically IOException is thrown, rather some other kind
     * of runtime exception. Users of {@link GzipCompressionProvider#decompress(String, byte[])} may depend on this.
     */
    @Test
    public void testDecompressCorrupt()
    {
        GzipCompressionProvider provider = new GzipCompressionProvider();
        try {
            provider.decompress(null, new byte[100]);
            fail("Expected IOException");
        } catch (IOException ignore) {
            // expected
        }
        byte[] compressedData = provider.compress(null, new byte[0]);
        for (int i = 0; i < compressedData.length; i++)
        {
            try {
                provider.decompress(null, Arrays.copyOf(compressedData, i));
            } catch (IOException ignore) {
                // expected
            }
            for (int change = 1; change < 256; change++)
            {
                byte b = compressedData[i];
                compressedData[i] = (byte) (b + change);
                try {
                    provider.decompress(null, compressedData);
                    // No exception is OK
                } catch (IOException ignore) {
                    // expected
                }
                // reset value back
                compressedData[i] = b;
            }
        }
    }

    @Test
    public void smokeTestRandomDataWithJdk() throws IOException
    {
        GzipCompressionProvider provider = new GzipCompressionProvider();
        ThreadLocalRandom random = ThreadLocalRandom.current();
        for (int len = 1; len < 100; len++)
        {
            byte[] data = new byte[len];
            for (int i = 0; i < 100; i++) {
                byte[] compressedData = provider.compress(null, data);
                byte[] jdkCompressedData = jdkCompress(data);
                assertTrue(Arrays.equals(compressedData, jdkCompressedData));
                byte[] decompressedData = provider.decompress(null, compressedData);
                assertTrue(Arrays.equals(decompressedData, data));
                // in the end of the iteration to test empty array first
                random.nextBytes(data);
            }
        }
    }

    private static byte[] jdkCompress(byte[] data) throws IOException
    {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (GZIPOutputStream out = new GZIPOutputStream(bytes)) {
            out.write(data);
            out.finish();
        }
        return bytes.toByteArray();
    }
}


text: [AWSからPush通知を受け取る](./push_notification.md)


text:
:- use_module(library(logicmoo_common)).
:- '$set_source_module'(mu).
% :- ensure_loaded(adv_loader).

% :- user:ensure_loaded(library(parser_sharing)).

:- ensure_loaded(adv_debug).
:- ensure_loaded(adv_help).
:- ensure_loaded(adv_util).
:- ensure_loaded(adv_io).

:- ensure_loaded(adv_model).
:- ensure_loaded(adv_percept).

:- ensure_loaded(adv_inst).
:- ensure_loaded(adv_edit).

:- ensure_loaded(adv_behaviour_tree).

%:- ensure_loaded(adv_axiom).
:- ensure_loaded(adv_implies).

%:- ensure_loaded(adv_abdemo).

:- ensure_loaded(adv_examine).
:- ensure_loaded(adv_action).
:- ensure_loaded(adv_agent).
:- ensure_loaded(adv_floyd).
:- ensure_loaded(adv_physics).
:- ensure_loaded(adv_plan).

:- ensure_loaded(adv_functors).
:- ensure_loaded(adv_eng2txt).
:- ensure_loaded(adv_log2eng).
:- ensure_loaded(adv_eng2cmd).

%:- ensure_loaded(adv_lexicon).

:- ensure_loaded(adv_quasiquote).

:- ensure_loaded(adv_state).

:- ensure_loaded(adv_portray).
:- ensure_loaded(adv_data).

:- ensure_loaded(adv_plugins).


text:
layout: post
title: "Two years data from Withings smart watch"
date: 2017-08-13
description: "The withings smart watch helps me find insights my health. How much I move and sleep."
categories:
  - visualization
tags:
  - run
  - python
  - chartjs
  - withings
calheatmap: true
chartjs: true
image:
  path: /assets/img/withings/main-16x9.jpg
  height: 788
  width: 1400
thumb:
  path: /assets/img/withings/main-thumb.jpg
  height: 200
  width: 300

---

The withings smart watch looks like a regular watch. It's very difficult to
tell that it has bluetooth and movement sensors inside. In addition it has long
duration battery and it's very elegant.

I have been using the watch during two years. Here you can find some of the
insights that the data that the watch collected tell me.

<amp-img src="/assets/img/withings/main.jpg" alt="Withings data" height="420" width="533" layout="responsive"></amp-img>

## Calendar heatmap of steps

This calendar plot shows the number of daily steps. Each box is a day. It's interactive, so you can hover your mouse to read the data. The colour meaning is the following:
- The white means that there are no steps that have been recorded that day.
- Light blue means that I didn't walk a lot that day.
- Dark blue means that I have been walking a lot that day.

I have been wearing the device very often, so you can notice that there are a lot of blue squares. It's also interesting to see holidays where I walk more than regular.

<button id="example-c-PreviousDomain-selector" class="button">Previous </button>
<button id="example-c-NextDomain-selector" class="button">Next month </button>

## Daily steps

This chart shows the number of daily steps in a more regular way. You might see the following:
- I have been walking more at the end of 2016, at the end of my PhD.
- My walking record is 37k steps, on 14 august 2016. It was on holidays at Italy.

<canvas id="scatterChart" width="400" height="200"></canvas>

## Steps per day

This chart shows the number of daily steps grouped by weekday. You might notice that Saturday is the day when I walk the most and Monday is a very lazy day.

<canvas id="barChart" width="400" height="200"></canvas>

## Steps per month

This chart shows the number of daily steps grouped by month. You might notice some seasonal effects.
- The summer is very active for me. Being July the month when I walk the most.
- I tend to be more lazy on winter. November is a month where I didn't walk a lot in two years.

<canvas id="barChartMonth" width="400" height="200"></canvas>

## Conclusions

This data helps me to know myself more. Mondays are not my days. Saturdays and Summer are the periods of the time when I walk more.

The code to process data and plot the chatjs graphs can be found in this [python notebook](https://gist.github.com/cristianpb/219069facc7a29e8bd2f4d9768096513).


text:
package org.apache.cassandra.thrift;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;

/**
 * Extends Thrift's TServerSocket to allow customization of various desirable TCP properties.
 */
public class TCustomServerSocket extends TServerTransport
{

    private static final Logger logger = LoggerFactory.getLogger(TCustomServerSocket.class);

    /**
     * Underlying serversocket object
     */
    private ServerSocket serverSocket = null;

    private final boolean keepAlive;
    private final Integer sendBufferSize;
    private final Integer recvBufferSize;

    /**
     * Allows fine-tuning of the server socket including keep-alive, reuse of addresses, send and receive buffer sizes.
     *
     * @param bindAddr
     * @param keepAlive
     * @param sendBufferSize
     * @param recvBufferSize
     * @throws TTransportException
     */
    public TCustomServerSocket(InetSocketAddress bindAddr, boolean keepAlive, Integer sendBufferSize,
            Integer recvBufferSize)
            throws TTransportException
    {
        try
        {
            // Make server socket
            serverSocket = new ServerSocket();
            // Prevent 2MSL delay problem on server restarts
            serverSocket.setReuseAddress(true);
            // Bind to listening port
            serverSocket.bind(bindAddr);
        }
        catch (IOException ioe)
        {
            serverSocket = null;
            throw new TTransportException("Could not create ServerSocket on address " + bindAddr.toString() + ".");
        }

        this.keepAlive = keepAlive;
        this.sendBufferSize = sendBufferSize;
        this.recvBufferSize = recvBufferSize;
    }

    public TCustomServerSocket(ServerSocket socket, boolean keepAlive, Integer sendBufferSize, Integer recvBufferSize)
    {
        this.serverSocket = socket;
        this.keepAlive = keepAlive;
        this.sendBufferSize = sendBufferSize;
        this.recvBufferSize = recvBufferSize;
    }

    @Override
    protected TCustomSocket acceptImpl() throws TTransportException
    {

        if (serverSocket == null)
            throw new TTransportException(TTransportException.NOT_OPEN, "No underlying server socket.");

        TCustomSocket tsocket = null;
        Socket socket = null;
        try
        {
            socket = serverSocket.accept();
            tsocket = new TCustomSocket(socket);
            tsocket.setTimeout(0);
        }
        catch (IOException iox)
        {
            throw new TTransportException(iox);
        }

        try
        {
            socket.setKeepAlive(this.keepAlive);
        }
        catch (SocketException se)
        {
            logger.warn("Failed to set keep-alive on Thrift socket.", se);
        }

        if (this.sendBufferSize != null)
        {
            try
            {
                socket.setSendBufferSize(this.sendBufferSize.intValue());
            }
            catch (SocketException se)
            {
                logger.warn("Failed to set send buffer size on Thrift socket.", se);
            }
        }

        if (this.recvBufferSize != null)
        {
            try
            {
                socket.setReceiveBufferSize(this.recvBufferSize.intValue());
            }
            catch (SocketException se)
            {
                logger.warn("Failed to set receive buffer size on Thrift socket.", se);
            }
        }

        return tsocket;
    }

    @Override
    public void listen() throws TTransportException
    {
        // Make sure not to block on accept
        if (serverSocket != null)
        {
            try
            {
                serverSocket.setSoTimeout(100);
            }
            catch (SocketException sx)
            {
                logger.error("Could not set socket timeout.", sx);
            }
        }
    }

    @Override
    public void close()
    {
        if (serverSocket != null)
        {
            try
            {
                serverSocket.close();
            }
            catch (IOException iox)
            {
                logger.warn("Could not close server socket.", iox);
            }
            serverSocket = null;
        }
    }

    @Override
    public void interrupt()
    {
        // The thread-safeness of this is dubious, but Java documentation suggests
        // that it is safe to do this from a different thread context
        close();
    }
}


text:
var express = require('express');
var router = express.Router();
var io = require('socket.io')();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index');
});
router.get('/rank', function(req, res, next) {
  res.render('rank');
});

module.exports = router;


text:
/**
 * Contains classes for loading, parsing YAML documents and building a
 * YAML specific DOM of {@link com.hazelcast.internal.yaml.YamlNode} instances
 * <p>
 * The YAML documents are loaded and parsed with the external SnakeYaml
 * parser, which supports YAML 1.2 documents, and the JSON schema.
 */
package com.hazelcast.internal.yaml;


text:
Modellgetriebene Softwareentwicklung (MGSWE, trnsl. Model-driven Software Development).
This project aims to provide a simple Domain Specific Language (DSL) for the creation of Spring-Boot REST Services
by utilising the Meta Programming System (MPS).

## Usage

* Install [MPS](https://www.jetbrains.com/mps/download) first. After the installation, clone this respository and open it with MPS.
* Write a script with the restgen language and build it.
* Clone an build the [RESTGenParser tool](https://github.com/M-a-x-G/RESTGenParser).
```
Script {
  settings {
    description: Example project
    group: de.example
    artifact: test
    version: 1.0
    base name: root
    packaging: jar
    java version: 1.8
    compile -> com.google.guava : guava : 19.0
  }

  DTO ( Response ){
    String : message
    Integer : statusCode
  }

  ModelAndDTO ( User ){
    Controller Methods: {Create | Read | Update | Delete}
    String : name
    Integer : age
    Boolean : active
  }
}
```
* Open the RESTGenParser tool and select the outputfile from MPS and a folder for the outgoing project and click generate.

## License
[MIT](https://github.com/M-a-x-G/MGSWE/blob/master/LICENSE)