text:
package org.apache.hadoop.yarn.server.timelineservice.storage.common;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.junit.Test;

/**
 * Unit tests for key converters for various tables' row keys.
 *
 */
public class TestKeyConverters {

  @Test
  public void testAppIdKeyConverter() {
    AppIdKeyConverter appIdKeyConverter = new AppIdKeyConverter();
    long currentTs = System.currentTimeMillis();
    ApplicationId appId1 = ApplicationId.newInstance(currentTs, 1);
    ApplicationId appId2 = ApplicationId.newInstance(currentTs, 2);
    ApplicationId appId3 = ApplicationId.newInstance(currentTs + 300, 1);
    String appIdStr1 = appId1.toString();
    String appIdStr2 = appId2.toString();
    String appIdStr3 = appId3.toString();
    byte[] appIdBytes1 = appIdKeyConverter.encode(appIdStr1);
    byte[] appIdBytes2 = appIdKeyConverter.encode(appIdStr2);
    byte[] appIdBytes3 = appIdKeyConverter.encode(appIdStr3);
    // App ids' should be encoded in a manner wherein descending order
    // is maintained.
    assertTrue(
        "Ordering of app ids' is incorrect",
        Bytes.compareTo(appIdBytes1, appIdBytes2) > 0
            && Bytes.compareTo(appIdBytes1, appIdBytes3) > 0
            && Bytes.compareTo(appIdBytes2, appIdBytes3) > 0);
    String decodedAppId1 = appIdKeyConverter.decode(appIdBytes1);
    String decodedAppId2 = appIdKeyConverter.decode(appIdBytes2);
    String decodedAppId3 = appIdKeyConverter.decode(appIdBytes3);
    assertTrue("Decoded app id is not same as the app id encoded",
        appIdStr1.equals(decodedAppId1));
    assertTrue("Decoded app id is not same as the app id encoded",
        appIdStr2.equals(decodedAppId2));
    assertTrue("Decoded app id is not same as the app id encoded",
        appIdStr3.equals(decodedAppId3));
  }

  @Test
  public void testEventColumnNameConverter() {
    String eventId = "=foo_=eve=nt=";
    byte[] valSepBytes = Bytes.toBytes(Separator.VALUES.getValue());
    byte[] maxByteArr =
        Bytes.createMaxByteArray(Bytes.SIZEOF_LONG - valSepBytes.length);
    byte[] ts = Bytes.add(valSepBytes, maxByteArr);
    Long eventTs = Bytes.toLong(ts);
    byte[] byteEventColName =
        new EventColumnName(eventId, eventTs, null).getColumnQualifier();
    KeyConverter<EventColumnName> eventColumnNameConverter =
        new EventColumnNameConverter();
    EventColumnName eventColName =
        eventColumnNameConverter.decode(byteEventColName);
    assertEquals(eventId, eventColName.getId());
    assertEquals(eventTs, eventColName.getTimestamp());
    assertNull(eventColName.getInfoKey());

    String infoKey = "f=oo_event_in=fo=_key";
    byteEventColName =
        new EventColumnName(eventId, eventTs, infoKey).getColumnQualifier();
    eventColName = eventColumnNameConverter.decode(byteEventColName);
    assertEquals(eventId, eventColName.getId());
    assertEquals(eventTs, eventColName.getTimestamp());
    assertEquals(infoKey, eventColName.getInfoKey());
  }

  @Test
  public void testLongKeyConverter() {
    LongKeyConverter longKeyConverter = new LongKeyConverter();
    confirmLongKeyConverter(longKeyConverter, Long.MIN_VALUE);
    confirmLongKeyConverter(longKeyConverter, -1234567890L);
    confirmLongKeyConverter(longKeyConverter, -128L);
    confirmLongKeyConverter(longKeyConverter, -127L);
    confirmLongKeyConverter(longKeyConverter, -1L);
    confirmLongKeyConverter(longKeyConverter, 0L);
    confirmLongKeyConverter(longKeyConverter, 1L);
    confirmLongKeyConverter(longKeyConverter, 127L);
    confirmLongKeyConverter(longKeyConverter, 128L);
    confirmLongKeyConverter(longKeyConverter, 1234567890L);
    confirmLongKeyConverter(longKeyConverter, Long.MAX_VALUE);
  }

  private void confirmLongKeyConverter(LongKeyConverter longKeyConverter,
      Long testValue) {
    Long decoded = longKeyConverter.decode(longKeyConverter.encode(testValue));
    assertEquals(testValue, decoded);
  }

  @Test
  public void testStringKeyConverter() {
    StringKeyConverter stringKeyConverter = new StringKeyConverter();
    String phrase = "QuackAttack now!";

    for (int i = 0; i < phrase.length(); i++) {
      String sub = phrase.substring(i, phrase.length());
      confirmStrignKeyConverter(stringKeyConverter, sub);
      confirmStrignKeyConverter(stringKeyConverter, sub + sub);
    }
  }

  private void confirmStrignKeyConverter(StringKeyConverter stringKeyConverter,
      String testValue) {
    String decoded =
        stringKeyConverter.decode(stringKeyConverter.encode(testValue));
    assertEquals(testValue, decoded);
  }

}


text:
const Joi = require('joi')
const validate = require('./validate')

//
// Define the schema
//
const schema = {
  team: Joi.string(),
  name: Joi.string(),
  display_name: Joi.string(),
  header: Joi.string().allow('').optional(),
  purpose: Joi.string().allow('').optional(),
  type: Joi.string().valid('O', 'P')
}

//
// Generate a valid object
//
module.exports = function (props) {
  return {
    type: 'channel',
    channel: validate(schema, props)
  }
}

redpajama_set_name: RedPajamaGithub


text:
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;

import com.makeagame.core.plugin.libgdx.LibgdxProcessor;
import com.makeagame.core.resource.process.RegisterFinder;

public class TestLibgdxProcess {

    RegisterFinder finder;

    @Test
    public void test() {
        /*
         * TEST FINDER
         */
        System.out.println("test finder");

        finder = new RegisterFinder();
        try {
            /* IMAGE */
            finder.register("image", packageData("image/bird.png", 0, 0, 128, 128));

            /* ATTRIBUTE */
            finder.register("attribute", packageData("data/bird.txt", "atr"));

            /* SOUND */
            finder.register("sound", packageData("sound/button-50.mp3", "snd"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONObject json = finder.find("attribute");
        System.out.println(json.toString());

        // ???
//        String path = "image/bird.png";
//        Texture texture = new Texture(Gdx.files.classpath("../resource/" + path));
//        LibgdxResImage libgdxImage = new LibgdxResImage(path);

        /*
         * TEST PROCESSOR
         */
        System.out.println("test processor");

        LibgdxProcessor process = new LibgdxProcessor(finder);

//        Resource<LibgdxResText> res = new Resource<LibgdxResText>("attribute");
//        process.handleResource(res);
//
//        System.out.println("res ID" + res.getID());
//        try {
//            System.out.println("res context " + res.getPayload().get());
//        } catch (ResourceNotReadyException e) {
//            e.printStackTrace();
//        }

    }

    static private JSONObject packageData(String path) throws JSONException {
        return new JSONObject().put("path", path);
    }

    static private JSONObject packageData(String path, int x, int y, int w, int h) throws JSONException {
        return packageData(path).put("type", "img").put("x", x).put("y", y).put("w", w).put("h", h);
    }

    static private JSONObject packageData(String path, String type) throws JSONException {
        return packageData(path).put("type", type);
    }

}


text:
package org.wso2.carbon.apimgt.migration.client._110Specific.dto;

public class AppKeyMappingDTO {
    private String applicationId;
    private String consumerKey;
    private String keyType;

    public String getApplicationId() {
        return applicationId;
    }

    public void setApplicationId(String applicationId) {
        this.applicationId = applicationId;
    }

    public String getConsumerKey() {
        return consumerKey;
    }

    public void setConsumerKey(String consumerKey) {
        this.consumerKey = consumerKey;
    }

    public String getKeyType() {
        return keyType;
    }

    public void setKeyType(String keyType) {
        this.keyType = keyType;
    }

}


text:
package q

import "github.com/oov/q/qutil"

var testModel = map[qutil.Dialect]struct {
	tester  Tester
	creates []string
	inserts []string
	drops   []string
}{
	MySQL: {
		tester: mySQLTest,
		creates: []string{
			`CREATE TABLE IF NOT EXISTS user(id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), age INT) DEFAULT CHARSET=utf8mb4`,
			`CREATE TABLE IF NOT EXISTS post(id INTEGER PRIMARY KEY AUTO_INCREMENT, user_id INTEGER REFERENCES user(id) ON DELETE CASCADE, title TEXT NOT NULL, at DATETIME NOT NULL) DEFAULT CHARSET=utf8mb4`,
			`CREATE TABLE IF NOT EXISTS tag(id INTEGER PRIMARY KEY AUTO_INCREMENT, value VARCHAR(255)) DEFAULT CHARSET=utf8mb4`,
			`CREATE TABLE IF NOT EXISTS posttag(post_id INTEGER NOT NULL REFERENCES post(id) ON DELETE CASCADE, tag_id INTEGER NOT NULL REFERENCES tag(id) ON DELETE CASCADE, PRIMARY KEY (post_id, tag_id)) DEFAULT CHARSET=utf8mb4`,
		},
		inserts: []string{
			`INSERT INTO user(id, name, age) VALUES (1, 'Shipon', 15)`,
			`INSERT INTO user(id, name, age) VALUES (2, 'Mr.TireMan', 44)`,
			`INSERT INTO post(id, user_id, title, at) VALUES (1, 1, '昨日見た夢の内容が凄い', '2015-12-12 20:19:18')`,
			`INSERT INTO post(id, user_id, title, at) VALUES (2, 2, '氷の上で滑るタイヤの原因とは?', '2015-12-12 21:19:18')`,
			`INSERT INTO post(id, user_id, title, at) VALUES (3, 1, '嘘じゃないんです', '2015-12-13 20:19:18')`,
			`INSERT INTO post(id, user_id, title, at) VALUES (4, 2, '最近仕事が辛い', '2015-12-13 21:19:18')`,
			`INSERT INTO tag(id, value) VALUES (1, 'Diary')`,
			`INSERT INTO tag(id, value) VALUES (2, 'Ad')`,
			`INSERT INTO tag(id, value) VALUES (3, 'ぼやき')`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (1, 1)`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (2, 2)`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (3, 1)`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (3, 3)`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (4, 3)`,
		},
		drops: []string{
			`DROP TABLE IF EXISTS posttag`,
			`DROP TABLE IF EXISTS post`,
			`DROP TABLE IF EXISTS user`,
			`DROP TABLE IF EXISTS tag`,
		},
	},
	PostgreSQL: {
		tester: postgreSQLTest,
		creates: []string{
			`CREATE TABLE IF NOT EXISTS "user"(id SERIAL PRIMARY KEY, name VARCHAR(255), age INT)`,
			`CREATE TABLE IF NOT EXISTS post(id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES "user"(id) ON DELETE CASCADE, title TEXT NOT NULL, at TIMESTAMP NOT NULL)`,
			`CREATE TABLE IF NOT EXISTS tag(id SERIAL PRIMARY KEY, value VARCHAR(255))`,
			`CREATE TABLE IF NOT EXISTS posttag(post_id INTEGER NOT NULL REFERENCES post(id) ON DELETE CASCADE, tag_id INTEGER NOT NULL REFERENCES tag(id) ON DELETE CASCADE, PRIMARY KEY (post_id, tag_id))`,
		},
		inserts: []string{
			`INSERT INTO "user"(id, name, age) VALUES (1, 'Shipon', 15)`,
			`INSERT INTO "user"(id, name, age) VALUES (2, 'Mr.TireMan', 44)`,
			`INSERT INTO post(id, user_id, title, at) VALUES (1, 1, '昨日見た夢の内容が凄い', '2015-12-12 20:19:18')`,
			`INSERT INTO post(id, user_id, title, at) VALUES (2, 2, '氷の上で滑るタイヤの原因とは?', '2015-12-12 21:19:18')`,
			`INSERT INTO post(id, user_id, title, at) VALUES (3, 1, '嘘じゃないんです', '2015-12-13 20:19:18')`,
			`INSERT INTO post(id, user_id, title, at) VALUES (4, 2, '最近仕事が辛い', '2015-12-13 21:19:18')`,
			`INSERT INTO tag(id, value) VALUES (1, 'Diary')`,
			`INSERT INTO tag(id, value) VALUES (2, 'Ad')`,
			`INSERT INTO tag(id, value) VALUES (3, 'ぼやき')`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (1, 1)`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (2, 2)`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (3, 1)`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (3, 3)`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (4, 3)`,
		},
		drops: []string{
			`DROP TABLE IF EXISTS posttag`,
			`DROP TABLE IF EXISTS post`,
			`DROP TABLE IF EXISTS "user"`,
			`DROP TABLE IF EXISTS tag`,
		},
	},
	SQLite: {
		tester: sqliteTest,
		creates: []string{
			`CREATE TABLE IF NOT EXISTS user(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255), age INT)`,
			`CREATE TABLE IF NOT EXISTS post(id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER REFERENCES user(id) ON DELETE CASCADE, title TEXT NOT NULL, at TIMESTAMP NOT NULL)`,
			`CREATE TABLE IF NOT EXISTS tag(id INTEGER PRIMARY KEY AUTOINCREMENT, value VARCHAR(255))`,
			`CREATE TABLE IF NOT EXISTS posttag(post_id INTEGER NOT NULL REFERENCES post(id) ON DELETE CASCADE, tag_id INTEGER NOT NULL REFERENCES tag(id) ON DELETE CASCADE, PRIMARY KEY (post_id, tag_id))`,
		},
		inserts: []string{
			`INSERT INTO user(id, name, age) VALUES (1, 'Shipon', 15)`,
			`INSERT INTO user(id, name, age) VALUES (2, 'Mr.TireMan', 44)`,
			`INSERT INTO post(id, user_id, title, at) VALUES (1, 1, '昨日見た夢の内容が凄い', '2015-12-12 20:19:18')`,
			`INSERT INTO post(id, user_id, title, at) VALUES (2, 2, '氷の上で滑るタイヤの原因とは?', '2015-12-12 21:19:18')`,
			`INSERT INTO post(id, user_id, title, at) VALUES (3, 1, '嘘じゃないんです', '2015-12-13 20:19:18')`,
			`INSERT INTO post(id, user_id, title, at) VALUES (4, 2, '最近仕事が辛い', '2015-12-13 21:19:18')`,
			`INSERT INTO tag(id, value) VALUES (1, 'Diary')`,
			`INSERT INTO tag(id, value) VALUES (2, 'Ad')`,
			`INSERT INTO tag(id, value) VALUES (3, 'ぼやき')`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (1, 1)`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (2, 2)`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (3, 1)`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (3, 3)`,
			`INSERT INTO posttag(post_id, tag_id) VALUES (4, 3)`,
		},
		drops: []string{
			`DROP TABLE IF EXISTS posttag`,
			`DROP TABLE IF EXISTS post`,
			`DROP TABLE IF EXISTS user`,
			`DROP TABLE IF EXISTS tag`,
		},
	},
}


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

    // Create a natural language search request
    MKLocalSearchRequest *searchRequest = [[MKLocalSearchRequest alloc] init];
    searchRequest.naturalLanguageQuery = @"The Eiffel Tower";

    // Create the object that actually does the search
    MKLocalSearch *search = [[MKLocalSearch alloc] initWithRequest:searchRequest];

    // Start the search, with a completion block
    [search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {

        // The Eiffel Tower should be the first map item returned
        if ([[response mapItems] count] > 0) {
            MKMapItem *firstItem = [[response mapItems] firstObject];

            // Center the map view on the found coordinate
            CLLocationCoordinate2D eiffelCoordinate = firstItem.placemark.coordinate;
            self.mapView.centerCoordinate = eiffelCoordinate;

            MKMapCamera *camera = [MKMapCamera cameraLookingAtCenterCoordinate:eiffelCoordinate fromEyeCoordinate:eiffelCoordinate eyeAltitude:900];
            camera.heading = 135;
            camera.pitch = 75;
            self.mapView.camera = camera;

            [UIView animateWithDuration:10 animations:^{
                camera.pitch = 0;
                self.mapView.camera = camera;
            }];

        }
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
Progress Indicator

<sky-progress-indicator
  id="waterfall-indicator"
  [messageStream]="progressMessageStream"
  [startingIndex]="2"
  (progressChanges)="updateIndex($event)"
  #progressIndicator
>

  <sky-progress-indicator-title>Setup my connection</sky-progress-indicator-title>

  <sky-progress-indicator-item
    title="Configure connection"
  >

      <button *ngIf="activeIndex === 0"
        class="sky-btn sky-btn-primary"
        type="button"
        (click)="configureConnection(true)"
      >
        Set connection
      </button>
      <button *ngIf="activeIndex > 0"
        class="sky-btn sky-btn-link"
        type="button"
        (click)="configureConnection(false)"
      >
        Edit connection
      </button>

  </sky-progress-indicator-item>

  <sky-progress-indicator-item
    title="Select remote server"
  >

= 1">
        <button *ngIf="activeIndex === 1"
          class="sky-btn sky-btn-primary"
          type="button"
          (click)="setServer(true)"
        >
          Select server
        </button>
        <button *ngIf="activeIndex > 1"
          class="sky-btn sky-btn-link"
          type="button"
          (click)="setServer(false)"
        >
          Change server
        </button>

  </sky-progress-indicator-item>

  <sky-progress-indicator-item
    title="Test connection"
  >

= 2">
        <button *ngIf="activeIndex === 2"
          class="sky-btn sky-btn-primary"
          type="button"
          (click)="testConnection(true)"
        >
          Test connection
        </button>
        <button *ngIf="activeIndex > 2"
          class="sky-btn sky-btn-link"
          type="button"
          (click)="testConnection(false)"
        >
          Retest connection
        </button>

  </sky-progress-indicator-item>

  <sky-progress-indicator-item
    title="Turn on connection"
  >

= 3">
        <button *ngIf="activeIndex === 3"
          class="sky-btn sky-btn-primary"
          type="button"
          (click)="alertMessage('Form completed')"
        >
          Turn on
        </button>

  </sky-progress-indicator-item>

  <sky-progress-indicator-reset-button
    [progressIndicator]="progressIndicator"
  >
    Erase all settings
  </sky-progress-indicator-reset-button>
</sky-progress-indicator>

Progress indicator passive

<button
  class="sky-btn sky-btn-link"
  skyPopoverPlacement="right"
  skyPopoverTrigger="mouseenter"
  type="button"
  [skyPopover]="myPopover1"
>
  In progress
</button>

<sky-popover #myPopover1>
  <sky-progress-indicator
    [isPassive]="true"
    [startingIndex]="1"
  >
    <sky-progress-indicator-item
      title="Received (02-19-2003)"
    >
    </sky-progress-indicator-item>
    <sky-progress-indicator-item
      title="Awaiting approval"
    >
    </sky-progress-indicator-item>
    <sky-progress-indicator-item
      title="HIDDEN TITLE"
    >
    </sky-progress-indicator-item>
  </sky-progress-indicator>
</sky-popover>


text:
/**
 * Created by USER on 6/3/15.
 */

/*
What is Polymorphism?
    The ability to call the same method on different objects and have each of them respond
    in their own way is called polymorphism.
    In OOP, we think of objects that are linked through inheritance has the same methods
    (override methods) and that the method being called up, is the method associated with the
    object and not the type of referance.
    This should not be a problem in Java Script as references (variables) in JavaScript is not
    type-set. We can assign any type of data to a variable in Javascript, and Javascript will
    know the object a variable refer to if it exists.

    Example:*/

function Person(age, weight) {
    this.age=age;
    this.weight=weight;
    this.getInfo=function() {
        return "I am " + this.age + " years old " +
            "and weighs " + this.weight +" kilo.";
    }
}
function Employee(age, weight, salary){
    this.salary=salary;
    this.age=age;
    this.weight=weight;
    this.getInfo=function() {
        return "I am " + this.age + " years old " +
            "and weighs " + this.weight +" kilo " +
            "and earns " + this.salary + " dollar.";
    }
}
Employee.prototype= new Person();
Employee.prototype.constructor=Employee;
// The argument, 'obj', can be of any kind
// which method, getInfo(), to be executed depend on the object
// that 'obj' refer to.
function showInfo(obj) {
    console.log(obj.getInfo());
}

var person = new Person(50,90);
var employee = new Employee(43,80,50000);
showInfo(person);
showInfo(employee);


text:
html,
body {
  height: 100%; }

#tab .dropdown-menu li:first-child {
  display: none;
  font-size: 1.2em;
  text-align: center;
  padding-bottom: 0.5em;
  border-bottom: thin solid #696969;
  margin-bottom: 2px; }
#tab .open a {
  border-color: transparent; }
@media screen and (max-width: 960px) {
  #tab .open li:first-child {
    display: block; } }
@media screen and (max-width: 960px) {
  #tab > li > a {
    padding: 0 2px; } }
#tab .icon {
  display: none;
  width: 32px;
  height: 32px;
  background-repeat: no-repeat; }
  @media screen and (max-width: 960px) {
    #tab .icon {
      display: inline-block; } }
#tab .index {
  background-image: url("../icon/index.png"); }
#tab .user {
  background-image: url("../icon/user.png"); }
#tab .group {
  background-image: url("../icon/group.png"); }
#tab .setting {
  background-image: url("../icon/setting.png"); }
#tab .statistic {
  background-image: url("../icon/statistic.png"); }
@media screen and (max-width: 960px) {
  #tab .text, #tab .caret {
    display: none; } }

#alert button {
  font-size: 1.1em;
  color: #fff; }
#alert.error-alert .modal-title {
  color: #a94442; }
#alert.error-alert button {
  background-color: #a94442; }
#alert.success-alert .modal-title {
  color: #3c763d; }
#alert.success-alert button {
  background-color: #3c763d; }

#system-zone-panel .add-row, #system-event-panel .add-row {
  text-align: center;
  font-size: 1.2em; }
#system-zone-panel .action-icons, #system-event-panel .action-icons {
  display: none;
  float: right; }
  #system-zone-panel .action-icons span, #system-event-panel .action-icons span {
    margin: 0 6px; }
#system-zone-panel .list-group-item:hover > .action-icons, #system-event-panel .list-group-item:hover > .action-icons {
  display: inline; }

#system-zone-panel .parent {
  font-size: 1.1em; }
#system-zone-panel .children {
  display: none; }
  #system-zone-panel .children ul {
    padding-left: 0; }
  #system-zone-panel .children .empty {
    line-height: 1.5em; }
#system-zone-panel .event ul {
  padding-left: 0;
  height: 200px;
  overflow: scroll; }
#system-zone-panel .event li {
  display: inline-block;
  width: 30%; }
  @media screen and (max-width: 960px) {
    #system-zone-panel .event li {
      width: 100%; } }
  #system-zone-panel .event li:hover .glyphicon {
    display: inline; }
#system-zone-panel .event .empty {
  width: 80%;
  font-size: 1.2em;
  line-height: 1.5em;
  text-align: center;
  display: block;
  margin: 10px auto; }
#system-zone-panel .event .glyphicon {
  float: right;
  display: none; }

#spinner {
  margin: 100px auto;
  width: 70px;
  height: 60px;
  text-align: center;
  font-size: 10px;
  position: fixed;
  z-index: 9999;
  top: 30%;
  left: 50%;
  background-color: #FFCC00;
  border-radius: 6px;
  display: none; }
  #spinner div {
    background-color: #67CF22;
    height: 100%;
    width: 6px;
    display: inline-block;
    -webkit-animation: stretchdelay 1.2s infinite ease-in-out;
    animation: stretchdelay 1.2s infinite ease-in-out; }
  #spinner .rect2 {
    -webkit-animation-delay: -1.1s;
    animation-delay: -1.1s; }
  #spinner .rect3 {
    -webkit-animation-delay: -1s;
    animation-delay: -1s; }
  #spinner .rect4 {
    -webkit-animation-delay: -0.9s;
    animation-delay: -0.9s; }
  #spinner .rect5 {
    -webkit-animation-delay: -0.8s;
    animation-delay: -0.8s; }
  #spinner p {
    font-size: 1.2em;
    color: red; }

@-webkit-keyframes stretchdelay {
  0%, 40%, 100% {
    -webkit-transform: scaleY(0.4); }
  20% {
    -webkit-transform: scaleY(1); } }
@keyframes stretchdelay {
  0%, 40%, 100% {
    transform: scaleY(0.4);
    -webkit-transform: scaleY(0.4); }
  20% {
    transform: scaleY(1);
    -webkit-transform: scaleY(1); } }
#custom-label {
  display: none; }

#my-report .login {
  margin-top: 20px; }

#report-contain .nav-tabs li {
  width: 50%;
  text-align: center; }
#report-contain .tab-pane {
  display: none; }
#report-contain .active {
  display: block; }
#report-contain .report-row {
  display: none; }
  #report-contain .report-row ul {
    padding-left: 0; }

#account-manage-panel .ga-tips {
  display: none; }
#account-manage-panel thead {
  font-size: 1.1em;
  line-height: 1.8em; }
#account-manage-panel .empty, #account-manage-panel thead {
  background-color: #696969;
  color: #fff; }
#account-manage-panel table {
  margin-top: 10px; }
#account-manage-panel tr:hover .glyphicon {
  visibility: visible; }
#account-manage-panel .glyphicon {
  visibility: hidden; }

#account-changepwd-panel {
  margin-top: 20px; }

#group-manage-panel .actions {
  visibility: hidden; }
  #group-manage-panel .actions .glyphicon {
    margin-right: 15px; }
#group-manage-panel tr:hover .actions {
  visibility: visible; }
#group-manage-panel thead {
  font-size: 1.1em;
  line-height: 1.8em; }
#group-manage-panel .mount .empty, #group-manage-panel thead {
  background-color: #696969;
  color: #fff; }
#group-manage-panel td {
  width: 33%; }
#group-manage-panel table {
  margin-top: 10px; }
#group-manage-panel .event-mount .select span {
  display: inline; }
#group-manage-panel .event-mount ul {
  height: 200px;
  overflow: scroll; }
  @media screen and (max-width: 1130px) {
    #group-manage-panel .event-mount ul {
      height: 150px; } }
#group-manage-panel .event-mount li {
  display: inline-block;
  width: 50%;
  float: left; }
  @media screen and (max-width: 960px) {
    #group-manage-panel .event-mount li {
      width: 100%;
      margin: 0; } }
#group-manage-panel .event-mount span {
  float: right;
  display: none; }
#group-manage-panel .event-mount .empty {
  line-height: 1.5em; }
#group-manage-panel #group-event-modal li:hover > .glyphicon {
  display: inline; }
#group-manage-panel #group-event-modal h5 {
  text-align: center; }

#group-member-panel .member ul {
  height: 200px;
  overflow: scroll; }
#group-member-panel .member .glyphicon {
  float: right;
  display: none; }
#group-member-panel .member li:hover .glyphicon {
  display: inline; }

#group-taskmode-panel .rules {
  margin-top: 20px; }
#group-taskmode-panel table {
  text-align: center; }
  #group-taskmode-panel table .event {
    width: 40%; }
  #group-taskmode-panel table .assign {
    width: 30%; }
  #group-taskmode-panel table .type {
    width: 15%; }
#group-taskmode-panel thead {
  font-size: 1.1em; }
#group-taskmode-panel h5, #group-taskmode-panel h6 {
  text-align: center; }
#group-taskmode-panel h6:hover {
  cursor: pointer; }
#group-taskmode-panel .create-rule-modal .member {
  height: 200px;
  overflow: scroll; }
  #group-taskmode-panel .create-rule-modal .member li {
    width: 50%;
    display: inline-block;
    float: left; }
  #group-taskmode-panel .create-rule-modal .member .select .glyphicon {
    display: inline; }
  #group-taskmode-panel .create-rule-modal .member .glyphicon {
    display: none;
    float: right; }

#task-assign-panel .time {
  text-align: center;
  font-size: 1.1em;
  border-bottom: 2px solid #696969; }
#task-assign-panel .empty {
  text-align: center;
  font-size: 1.5em;
  line-height: 4em; }

.task-attr {
  font-size: 1.1em; }

#task-assign-modal .modal-body > div {
  border-bottom: 2px solid #696969;
  margin-bottom: 10px; }
#task-assign-modal .describe {
  display: none; }
  #task-assign-modal .describe .content {
    height: 10%;
    overflow: scroll;
    word-wrap: break-word; }

#task-all-panel .mount {
  margin-top: 10px; }
  #task-all-panel .mount > div {
    display: none; }
#task-all-panel .report-time {
  text-align: center;
  font-size: 1.1em;
  border-bottom: 2px solid #696969; }

#task-complete-panel .empty {
  text-align: center;
  font-size: 1.5em;
  line-height: 4em; }
#task-complete-panel .report-time {
  text-align: center;
  font-size: 1.1em;
  border-bottom: 2px solid #696969; }

#index-panel h3 {
  text-align: center;
  margin-bottom: 20px; }
#index-panel span {
  font-size: 0.8em; }
#index-panel p {
  font-size: 1.2em;
  border-bottom: 2px solid #696969;
  margin-bottom: 40px; }
#index-panel .number {
  font-size: 1.2em; }
#index-panel h5 {
  text-align: center; }

.container {
  margin-top: 5px; }

#login-btn {
  width: 100%; }

.login-icon {
  background: url("../icon/login-user.png") no-repeat;
  width: 128px;
  height: 128px;
  margin: auto;
  margin-bottom: 20px; }

.tab-pane {
  display: none; }

.active {
  display: block; }

#alert .modal-title {
  line-height: 2.0em;
  text-align: center; }
#alert .error {
  color: #d9534f; }
#alert .success {
  color: #5cb85c; }
#alert .modal-header {
  padding: 0; }
#alert .modal-footer {
  padding: 5px; }
#alert .modal-body {
  font-size: 1.1em;
  text-align: center; }

.error-block {
  display: inline-block;
  font-size: 1em;
  margin-top: 5px; }

.nav-tabs {
  margin-bottom: 10px; }

.glyphicon {
  cursor: pointer; }

ul {
  padding-left: 0; }

.list-group-item:last-child, .list-group-item:first-child {
  border-radius: 0; }

/*# sourceMappingURL=main.css.map */


text:
<!DOCTYPE html>

  {% include head.html %}

    {% include header.html %}

        {{ content }}

    {% include footer.html %}


text:
import json
import datetime

from modules.um_assessments.service import Assessments
from modules.um_gobalo.service import GobaloAPI
from modules.um_course.service import Courses
from .exceptions import TooManyMissedDays
from .exceptions import NoClassAttendance

class StudentMixin(object):
    def acreditations_email(self):
        return self.get_field('acreditations_email')

    def original_email(self):
        return self.get_field('original_email')

    def complete_name(self):
        return self.name

    def get_field(self, field, default_value=None):
        fields = json.loads(self.additional_fields)
        return fields.get(field, default_value)

    def set_field(self, key, value):
        fields = json.loads(self.additional_fields)
        fields[key] = value
        self.additional_fields = json.dumps(fields)
        self.put()

    def get_scores(self):
        return json.loads(self.scores) if self.scores else {}

    def is_assessment_pass(self, asm_id):
        score = self.get_scores().get(asm_id, 0)
        asm = Assessments.find_unit_by_id(asm_id)
        return score >= float(asm.min_score)

    def has_attempted_assessment(self, asm_id):
        scores = self.get_scores()
        return scores.get(asm_id, None) is not None

    def get_course_progress(self):
        from modules.um_assessments.service import AsmAttempts
        from modules.um_assessments.service import AsmDates
        from modules.um_editions.service import Editions

        progress = {str(asm.unit_id): {'attempts': {}, 'score': None}
                    for asm in Courses.get_assessments()}

        scores = self.get_scores()
        for asm_id, score in scores.iteritems():
            progress[asm_id]['score'] = score

        student_edition = Editions.get_edition_of_student(self)
        student_attempts = AsmAttempts.get(self.email)

        edition_dates = AsmDates.get_by_edition(student_edition)
        for asm_date in edition_dates:
            progress_dates = progress.get(asm_date.assessment, {})
            att_left = student_attempts.attempts_left[str(asm_date.id)]
            key = asm_date.pseudo_key(dates_in_gmt1=True)
            progress_dates['attempts'][key] = att_left
            progress[asm_date.assessment] = progress_dates

        return progress

    def check_today_attended(self):
        attended_days = self.get_field(
            'attended_days',
            {'days': [], 'too_many_missed_days': False}
        )
        if attended_days['too_many_missed_days']:
            raise TooManyMissedDays()

        date = datetime.datetime.utcnow()
        # TODO: (martin) make the hour check generic somehow
        if date.hour <= 7:  # 08:00 in GMT+1
            date -= datetime.timedelta(days=1)

        if date.weekday() == 5:  # if it's a Saturday
            date -= datetime.timedelta(days=1)  # Make it a Friday
        elif date.weekday() == 6:  # if it's a Sunday
            date -= datetime.timedelta(days=2)  # Make it a Friday

        date_str = date.strftime('%Y-%m-%d')
        if date_str not in attended_days['days']:
            status = GobaloAPI.user_attended(self.original_email(), date)
            if status == 'ATTENDED':
                attended_days['days'].append(date_str)
                self.set_field('attended_days', attended_days)
            elif status == 'TOO_MANY_MISSES':
                attended_days['too_many_misses'] = True
                self.set_field('attended_days', attended_days)
                raise TooManyMissedDays()
            elif status == 'DIDNT_ATTEND':
                raise NoClassAttendance()


text:
/**
 * @class Ext.chart.Legend
 *
 * Defines a legend for a chart's series.
 * The 'chart' member must be set prior to rendering.
 * The legend class displays a list of legend items each of them related with a
 * series being rendered. In order to render the legend item of the proper series
 * the series configuration object must have `showInLegend` set to true.
 *
 * The legend configuration object accepts a `position` as parameter.
 * The `position` parameter can be `left`, `right`
 * `top` or `bottom`. For example:
 *
 *     legend: {
 *         position: 'right'
 *     },
 *
 * ## Example
 *
 *     @example
 *     var store = Ext.create('Ext.data.JsonStore', {
 *         fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
 *         data: [
 *             { 'name': 'metric one',   'data1': 10, 'data2': 12, 'data3': 14, 'data4': 8,  'data5': 13 },
 *             { 'name': 'metric two',   'data1': 7,  'data2': 8,  'data3': 16, 'data4': 10, 'data5': 3  },
 *             { 'name': 'metric three', 'data1': 5,  'data2': 2,  'data3': 14, 'data4': 12, 'data5': 7  },
 *             { 'name': 'metric four',  'data1': 2,  'data2': 14, 'data3': 6,  'data4': 1,  'data5': 23 },
 *             { 'name': 'metric five',  'data1': 27, 'data2': 38, 'data3': 36, 'data4': 13, 'data5': 33 }
 *         ]
 *     });
 *
 *     Ext.create('Ext.chart.Chart', {
 *         renderTo: Ext.getBody(),
 *         width: 500,
 *         height: 300,
 *         animate: true,
 *         store: store,
 *         shadow: true,
 *         theme: 'Category1',
 *         legend: {
 *             position: 'top'
 *         },
 *         axes: [
 *             {
 *                 type: 'Numeric',
 *                 position: 'left',
 *                 fields: ['data1', 'data2', 'data3', 'data4', 'data5'],
 *                 title: 'Sample Values',
 *                 grid: {
 *                     odd: {
 *                         opacity: 1,
 *                         fill: '#ddd',
 *                         stroke: '#bbb',
 *                         'stroke-width': 1
 *                     }
 *                 },
 *                 minimum: 0,
 *                 adjustMinimumByMajorUnit: 0
 *             },
 *             {
 *                 type: 'Category',
 *                 position: 'bottom',
 *                 fields: ['name'],
 *                 title: 'Sample Metrics',
 *                 grid: true,
 *                 label: {
 *                     rotate: {
 *                         degrees: 315
 *                     }
 *                 }
 *             }
 *         ],
 *         series: [{
 *             type: 'area',
 *             highlight: false,
 *             axis: 'left',
 *             xField: 'name',
 *             yField: ['data1', 'data2', 'data3', 'data4', 'data5'],
 *             style: {
 *                 opacity: 0.93
 *             }
 *         }]
 *     });
 */
Ext.define('Ext.chart.Legend', {

    /* Begin Definitions */

    requires: ['Ext.chart.LegendItem'],

    /* End Definitions */

    /**
     * @cfg {Boolean} visible
     * Whether or not the legend should be displayed.
     */
    visible: true,

    /**
     * @cfg {Boolean} update
     * If set to true the legend will be refreshed when the chart is.
     * This is useful to update the legend items if series are
     * added/removed/updated from the chart. Default is true.
     */
    update: true,

    /**
     * @cfg {String} position
     * The position of the legend in relation to the chart. One of: "top",
     * "bottom", "left", "right", or "float". If set to "float", then the legend
     * box will be positioned at the point denoted by the x and y parameters.
     */
    position: 'bottom',

    /**
     * @cfg {Number} x
     * X-position of the legend box. Used directly if position is set to "float", otherwise
     * it will be calculated dynamically.
     */
    x: 0,

    /**
     * @cfg {Number} y
     * Y-position of the legend box. Used directly if position is set to "float", otherwise
     * it will be calculated dynamically.
     */
    y: 0,

    /**
     * @cfg {String} labelColor
     * Color to be used for the legend labels, eg '#000'
     */
    labelColor: '#000',

    /**
     * @cfg {String} labelFont
     * Font to be used for the legend labels, eg '12px Helvetica'
     */
    labelFont: '12px Helvetica, sans-serif',

    /**
     * @cfg {String} boxStroke
     * Style of the stroke for the legend box
     */
    boxStroke: '#000',

    /**
     * @cfg {String} boxStrokeWidth
     * Width of the stroke for the legend box
     */
    boxStrokeWidth: 1,

    /**
     * @cfg {String} boxFill
     * Fill style for the legend box
     */
    boxFill: '#FFF',

    /**
     * @cfg {Number} itemSpacing
     * Amount of space between legend items
     */
    itemSpacing: 10,

    /**
     * @cfg {Number} padding
     * Amount of padding between the legend box's border and its items
     */
    padding: 5,

    // @private
    width: 0,
    // @private
    height: 0,

    /**
     * @cfg {Number} boxZIndex
     * Sets the z-index for the legend. Defaults to 100.
     */
    boxZIndex: 100,

    /**
     * Creates new Legend.
     * @param {Object} config  (optional) Config object.
     */
    constructor: function(config) {
        var me = this;
        if (config) {
            Ext.apply(me, config);
        }
        me.items = [];
        /**
         * Whether the legend box is oriented vertically, i.e. if it is on the left or right side or floating.
         * @type {Boolean}
         */
        me.isVertical = ("left|right|float".indexOf(me.position) !== -1);

        // cache these here since they may get modified later on
        me.origX = me.x;
        me.origY = me.y;
    },

    /**
     * @private Create all the sprites for the legend
     */
    create: function() {
        var me = this,
            seriesItems = me.chart.series.items,
            i, ln, series;

        me.createBox();

        if (me.rebuild !== false) {
            me.createItems();
        }

        if (!me.created && me.isDisplayed()) {
            me.created = true;

            // Listen for changes to series titles to trigger regeneration of the legend
            for (i = 0, ln = seriesItems.length; i < ln; i++) {
                series = seriesItems[i];
                series.on('titlechange', me.redraw, me);
            }
        }
    },

    /**
     * @private Redraws the Legend
     */
    redraw: function() {
        var me = this;

        me.create();
        me.updatePosition();
    },

    /**
     * @private Determine whether the legend should be displayed. Looks at the legend's 'visible' config,
     * and also the 'showInLegend' config for each of the series.
     */
    isDisplayed: function() {
        return this.visible && this.chart.series.findIndex('showInLegend', true) !== -1;
    },

    /**
     * @private Create the series markers and labels
     */
    createItems: function() {
        var me = this,
            seriesItems = me.chart.series.items,
            items = me.items,
            fields, i, li, j, lj, series, item;

        //remove all legend items
        me.removeItems();

        // Create all the item labels
        for (i = 0, li = seriesItems.length; i < li; i++) {
            series = seriesItems[i];

            if (series.showInLegend) {
                fields = [].concat(series.yField);

                for (j = 0, lj = fields.length; j < lj; j++) {
                    item = me.createLegendItem(series, j);
                    items.push(item);
                };
            }
        };

        me.alignItems();
    },

    /**
     * @private Removes all legend items.
     */
    removeItems: function() {
        var me = this,
            items = me.items,
            len = items ? items.length : 0,
            i;

        if (len) {
            for (i = 0; i < len; i++) {
                items[i].destroy();
            }
        };

        //empty array
        items.length = [];
    },

    /**
     * @private
     * Positions all items within Legend box.
     */
    alignItems: function() {
        var me = this,
            items = me.items,
            padding = me.padding,
            spacingOffset = 2,
            vertical = me.isVertical,
            mfloor = Math.floor,
            mmax = Math.max,
            dim, maxWidth, maxHeight, totalWidth, totalHeight, spacing;

        dim = me.updateItemDimensions();

        maxWidth    = dim.maxWidth,
        maxHeight   = dim.maxHeight,
        totalWidth  = dim.totalWidth,
        totalHeight = dim.totalHeight,
        spacing     = dim.spacing;

        // Store the collected dimensions for later
        me.width = mfloor((vertical ? maxWidth : totalWidth) + padding * 2);

        if (vertical && items.length === 1) {
            spacingOffset = 1;
        }

        me.height = mfloor((vertical ? totalHeight - spacingOffset * spacing : maxHeight) + (padding * 2));
        me.itemHeight = maxHeight;
    },

    updateItemDimensions: function() {
        var me = this,
            items = me.items,
            padding = me.padding,
            itemSpacing = me.itemSpacing,
            maxWidth = 0,
            maxHeight = 0,
            totalWidth = 0,
            totalHeight = 0,
            vertical = me.isVertical,
            mfloor = Math.floor,
            mmax = Math.max,
            spacing = 0,
            i, l, item, bbox, width, height;

        // Collect item dimensions and position each one
        // properly in relation to the previous item
        for (i = 0, l = items.length; i < l; i++) {
            item = items[i];

            bbox = item.getBBox();

            //always measure from x=0, since not all markers go all the way to the left
            width  = bbox.width;
            height = bbox.height;

            if (i === 0) {
                spacing = vertical ? padding + height / 2 : padding;
            }
            else {
                spacing = itemSpacing / (vertical ? 2 : 1);
            }

            // Set the item's position relative to the legend box
            item.x = mfloor(vertical ? padding : totalWidth + spacing);
            item.y = mfloor(vertical ? totalHeight + spacing : padding + height / 2);

            // Collect cumulative dimensions
            totalWidth  += width + spacing;
            totalHeight += height + spacing;
            maxWidth     = mmax(maxWidth, width);
            maxHeight    = mmax(maxHeight, height);
        };

        return {
            totalWidth:  totalWidth,
            totalHeight: totalHeight,
            maxWidth:    maxWidth,
            maxHeight:   maxHeight,
            spacing:     spacing
        };
    },

    /**
     * @private Creates single Legend Item
     */
    createLegendItem: function(series, yFieldIndex) {
        var me = this;

        return new Ext.chart.LegendItem({
            legend: me,
            series: series,
            surface: me.chart.surface,
            yFieldIndex: yFieldIndex
        });
    },

    /**
     * @private Get the bounds for the legend's outer box
     */
    getBBox: function() {
        var me = this;
        return {
            x: Math.round(me.x) - me.boxStrokeWidth / 2,
            y: Math.round(me.y) - me.boxStrokeWidth / 2,
            width: me.width,
            height: me.height
        };
    },

    /**
     * @private Create the box around the legend items
     */
    createBox: function() {
        var me = this,
            box, bbox;

        if (me.boxSprite) {
            me.boxSprite.destroy();
        }

        bbox = me.getBBox();
        //if some of the dimensions are NaN this means that we
        //cannot set a specific width/height for the legend
        //container. One possibility for this is that there are
        //actually no items to show in the legend, and the legend
        //should be hidden.
        if (isNaN(bbox.width) || isNaN(bbox.height)) {
            me.boxSprite = false;
            return;
        }

        box = me.boxSprite = me.chart.surface.add(Ext.apply({
            type: 'rect',
            stroke: me.boxStroke,
            "stroke-width": me.boxStrokeWidth,
            fill: me.boxFill,
            zIndex: me.boxZIndex
        }, bbox));

        box.redraw();
    },

    /**
     * @private Calculates Legend position with respect to other Chart elements.
     */
    calcPosition: function() {
        var me = this,
            x, y,
            legendWidth = me.width,
            legendHeight = me.height,
            padding = me.padding,
            chart = me.chart,
            chartBBox = chart.chartBBox,
            insets = chart.insetPadding,
            chartWidth = chartBBox.width - (insets * 2),
            chartHeight = chartBBox.height - (insets * 2),
            chartX = chartBBox.x + insets,
            chartY = chartBBox.y + insets,
            surface = chart.surface,
            mfloor = Math.floor;

        // Find the position based on the dimensions
        switch(me.position) {
            case "left":
                x = insets;
                y = mfloor(chartY + chartHeight / 2 - legendHeight / 2);
                break;
            case "right":
                x = mfloor(surface.width - legendWidth) - insets;
                y = mfloor(chartY + chartHeight / 2 - legendHeight / 2);
                break;
            case "top":
                x = mfloor(chartX + chartWidth / 2 - legendWidth / 2);
                y = insets;
                break;
            case "bottom":
                x = mfloor(chartX + chartWidth / 2 - legendWidth / 2);
                y = mfloor(surface.height - legendHeight) - insets;
                break;
            default:
                x = mfloor(me.origX) + insets;
                y = mfloor(me.origY) + insets;
        }

        return { x: x, y: y };
    },

    /**
     * @private Update the position of all the legend's sprites to match its current x/y values
     */
    updatePosition: function() {
        var me = this,
            items = me.items,
            pos, i, l, bbox;

        if (me.isDisplayed()) {
            // Find the position based on the dimensions
            pos = me.calcPosition();

            me.x = pos.x;
            me.y = pos.y;

            // Update the position of each item
            for (i = 0, l = items.length; i < l; i++) {
                items[i].updatePosition();
            };

            bbox = me.getBBox();

            //if some of the dimensions are NaN this means that we
            //cannot set a specific width/height for the legend
            //container. One possibility for this is that there are
            //actually no items to show in the legend, and the legend
            //should be hidden.
            if (isNaN(bbox.width) || isNaN(bbox.height)) {
                if (me.boxSprite) {
                    me.boxSprite.hide(true);
                }
            }
            else {
                if (!me.boxSprite) {
                    me.createBox();
                }

                // Update the position of the outer box
                me.boxSprite.setAttributes(bbox, true);
                me.boxSprite.show(true);
            }
        }
    },

    /** toggle
     * @param {Boolean} show Whether to show or hide the legend.
     *
     */
    toggle: function(show) {
      var me = this,
          i = 0,
          items = me.items,
          len = items.length;

      if (me.boxSprite) {
          if (show) {
              me.boxSprite.show(true);
          } else {
              me.boxSprite.hide(true);
          }
      }

      for (; i < len; ++i) {
          if (show) {
            items[i].show(true);
          } else {
              items[i].hide(true);
          }
      }

      me.visible = show;
    }
});


text:
package org.apache.ignite.plugin;

/**
 * Marker interface for all Ignite plugins.
 */
public interface IgnitePlugin {
    // No-op.
}


text:
<?php

class WPML_PB_Config_Import_Shortcode {

	const PB_SHORTCODE_SETTING = 'pb_shortcode';

	/** @var  WPML_ST_Settings $st_settings */
	private $st_settings;

	public function __construct( WPML_ST_Settings $st_settings ) {
		$this->st_settings = $st_settings;
	}

	public function add_hooks() {
		add_filter( 'wpml_config_array', array( $this, 'wpml_config_filter' ) );
	}

	public function wpml_config_filter( $config_data ) {
		$old_shortcode_data = $this->get_settings();

		$shortcode_data = array();
		if ( isset ( $config_data['wpml-config']['shortcodes']['shortcode'] ) ) {
			foreach ( $config_data['wpml-config']['shortcodes']['shortcode'] as $data ) {
				$attributes = array();
				if ( isset( $data['attributes']['attribute'] ) ) {
					$single_attribute = false;
					foreach ( $data['attributes']['attribute'] as $attribute ) {
						if ( is_string( $attribute ) ) {
							$single_attribute   = true;
							$attribute_value    = $attribute;
							$attribute_encoding = '';
						} else if ( isset( $attribute['value'] ) ) {
							$attribute_value = $attribute['value'];
						}
						if ( $attribute_value ) {
							if ( $single_attribute ) {
								if ( isset( $attribute['encoding'] ) ) {
									$attribute_encoding = $attribute['encoding'];
								}
							} else {
								$attribute_encoding = isset( $attribute['attr']['encoding'] ) ? $attribute['attr']['encoding'] : '';
								$attributes[]       = array(
									'value'    => $attribute_value,
									'encoding' => $attribute_encoding
								);
							}
						}
					}
					if ( $single_attribute ) {
						$attributes[] = array(
							'value'    => $attribute_value,
							'encoding' => $attribute_encoding
						);
					}
				}
				$shortcode_data[] = array(
					'tag'        => array(
						'value'    => $data['tag']['value'],
						'encoding' => isset( $data['tag']['attr']['encoding'] ) ? $data['tag']['attr']['encoding'] : '',
					),
					'attributes' => $attributes,
				);
			}
		}

		if ( $shortcode_data != $old_shortcode_data ) {
			$this->st_settings->update_setting( self::PB_SHORTCODE_SETTING, $shortcode_data, true );
		}

		return $config_data;
	}

	public function get_settings() {
		return $this->st_settings->get_setting( self::PB_SHORTCODE_SETTING );
	}

	public function has_settings() {
		$settings = $this->get_settings();

		return ! empty( $settings );
	}
}


text:
import datetime
import time

import iso8601
import psycopg2
from temba_client.v2 import TembaClient

RAPIDPRO_URL = "https://rapidpro.prd.momconnect.co.za/"
RAPIDPRO_TOKEN = ""

DB = {
    "dbname": "ndoh_rapidpro",
    "user": "ndoh_rapidpro",
    "port": 7000,
    "host": "localhost",
    "password": "",
}

if __name__ == "__main__":
    rapidpro_client = TembaClient(RAPIDPRO_URL, RAPIDPRO_TOKEN)
    conn = psycopg2.connect(**DB)

    cursor = conn.cursor("contacts")
    mapping_cursor = conn.cursor()

    mapping_cursor.execute(
        """
        SELECT key, uuid
        FROM contacts_contactfield
        WHERE org_id=5
        """
    )
    field_mapping = dict(mapping_cursor)

    now = datetime.date.today()

    print("Processing contacts...")  # noqa
    cursor.execute(
        """
        SELECT
            distinct contacts_contact.id,
            contacts_contact.uuid,
            contacts_contact.fields,
            contacts_contactgroup.id,
            contacts_contact.created_on
        FROM contacts_contactgroup,
            campaigns_campaign,
            contacts_contactgroup_contacts
                left outer join campaigns_eventfire
                on campaigns_eventfire.contact_id =
                    contacts_contactgroup_contacts.contact_id,
            contacts_contact
        WHERE contacts_contactgroup.org_id = 5
            and contacts_contactgroup.id in (324, 325)
        AND campaigns_campaign.group_id = contacts_contactgroup.id
        and contacts_contactgroup_contacts.contactgroup_id = contacts_contactgroup.id
        and campaigns_eventfire.contact_id is null
        and contacts_contactgroup_contacts.contact_id = contacts_contact.id
        """
    )

    total = 0
    updated = 0
    contact_id = 0

    start, d_print = time.time(), time.time()
    for (contact_id, contact_uuid, fields, group_id, created_on) in cursor:
        should_receive_msgs = False
        fields_to_update = {}

        for date_field in ("baby_dob1", "baby_dob2", "baby_dob3"):
            date_value = fields.get(field_mapping[date_field], {}).get("datetime")
            text_value = fields.get(field_mapping[date_field], {}).get("text")

            if date_value:
                date_obj = iso8601.parse_date(date_value)

                delta = datetime.date.today() - date_obj.date()
                if delta.days <= 730:
                    should_receive_msgs = True
                    fields_to_update[date_field] = text_value

        if should_receive_msgs:
            updated += 1
            rapidpro_client.update_contact(contact_uuid, fields=fields_to_update)

        if time.time() - d_print > 1:
            print(  # noqa
                f"\rProcessed {updated}/{total} contacts at "
                f"{total/(time.time() - start):.0f}/s - ({contact_id})",
                end="",
            )
            d_print = time.time()

        total += 1

    print(  # noqa
        f"\rProcessed {updated}/{total} contacts at "
        f"{total/(time.time() - start):.0f}/s - ({contact_id})"
    )


text:
package lud.naiveGaussian.totalRecords;

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Reducer;

public class total_records_reducer extends Reducer<LongWritable, LongWritable, LongWritable, LongWritable> {

	private Long countRows = (long) 0;

	public void reduce(LongWritable key, Iterable<LongWritable> values, Context context)
			throws IOException, InterruptedException {
		for(LongWritable val:values){
			this.countRows += val.get();
		}
	}

	@Override
	public void cleanup(Context context) throws IOException, InterruptedException{

		context.write(new LongWritable(0), new LongWritable(this.countRows));
	}

}


text:
<?php

use yii\db\Migration;

/**
 * Handles the creation for table `tb_bn_archivos_url`.
 */
class m161016_194811_create_TB_BN_ARCHIVOS_URL_table extends Migration
{
    /**
     * @inheritdoc
     */
    public function safeUp()
    {
        $this->createTable('tb_bn_archivos_url', [
            'Codigo' => $this->primaryKey(),
            'CodigoSolicitud' => $this->integer()->notNull(),
            'codigoTipoSolicitud' => $this->integer()->notNull(),
            'Ruta' => $this->string(255),
            'NombreDocumento' => $this->string(255),
            'Formato' => $this->string(50),
        ]);
        $this->addForeignKey('fk_ARCHIVOS_SOLICITUD','tb_bn_archivos_url','CodigoSolicitud','tb_bn_solicitud_descargo','CodigoSolicitud');
        $this->addForeignKey('fk_ARCHIVOS_TIPO_SOLICITUD','tb_bn_archivos_url','codigoTipoSolicitud','tb_bn_tipos_solicitudes','codigoTipoSolicitud');
    }

    /**
     * @inheritdoc
     */
    public function down()
    {
        $this->dropTable('tb_bn_archivos_url');
    }
}


text:
require 'rubygems'
require 'active_record'

require File.dirname(__FILE__) + '/app/models.rb'
require File.dirname(__FILE__) + '/app/controllers.rb'
require File.dirname(__FILE__) + '/db/db_schema.rb'

path_to_sqlite_db = "db/scorekeeper.db"

#ActiveRecord::Base.logger = Logger.new(STDERR)
#ActiveRecord::Base.colorize_logging = true
if File.exists?('db/scorekeeper.db')
  ActiveRecord::Base.establish_connection(:adapter => "sqlite3",:database  => path_to_sqlite_db )
  start
else
  ActiveRecord::Base.establish_connection(:adapter => "sqlite3",:database  => path_to_sqlite_db )
  create_db_schema
  start
end


text:
var Heap = require('./Heap');
var Debugger = require('./Debugger');

/**
 * Represents the load queue for assets.
 */
Queue = (function() {

  var heap = new Heap(),
      skipOnErrorFlag = false,
      connections = 0,
      maxConnections = 6,
      callbacks = {

        /**
         * Callback for when a file in the queue has been loaded
         */
        onFileLoaded: function() {
          Debugger.log("[Connections: " + connections + "] - File loaded");
          connections--;
          start();
        },

        onFileLoadFailed: function() {
          Debugger.log("[Connections: " + connections + "] - File load failed");

          if(skipOnErrorFlag) {
            connections--;
            start();
          }
        },

      };

  /**
   * Skip 404s
   */
  function skipOnError (val) {
    skipOnErrorFlag = val;
  }

  /**
   * Gets the queue's next priority value.
   */
  function getNextHighestPriority() {
    return heap.getNextHighestPriority();
  }

  /**
   * Sets the queue's maximum number of concurrent requests.
   * @param {number} newMaxConnections The maximum number of in-flight requests.
   */
  function setMaxConnections(newMaxConnections) {
    maxConnections = newMaxConnections;
  }

  /**
   * Adds a file to the queue.
   * @param {RemoteFile} remoteFile The file to enqueue.
   * @param {boolean} startGetting Whether or not to try and get immediately.
   */
  function add(remoteFile, startGetting) {

    // ensure we have a priority, and
    // go with a LIFO approach
    // - thx courage@
    if(typeof remoteFile.priority === "undefined") {
      remoteFile.priority = heap.getNextHighestPriority();
    }

    heap.add(remoteFile);

    if(startGetting) {
      start();
    }
  }

  /**
   * Start requesting items from the queue.
   */
  function start() {
    while(connections < maxConnections) {
      nextFile = heap.remove();

      if(nextFile !== null) {
        nextFile.addEventListener('loaded', callbacks.onFileLoaded);
        nextFile.addEventListener('remoteunavailable', callbacks.onFileLoadFailed);
        nextFile.load();
        Debugger.log("[Connections: " + connections + "] - Loading " + nextFile.src);
        connections++;
      } else {
        Debugger.log("[Connections: " + connections + "] - No more images queued");
        break;
      }
    }
  }

  /**
   * Clears the queue.
   */
  function clear() {
    heap.clear();
  }

  return {
    getNextHighestPriority: getNextHighestPriority,
    setMaxConnections: setMaxConnections,
    add: add,
    clear: clear,
    start: start,
    skipOnError: skipOnError,
  };

})();

module.exports =  Queue;


text:
require 'active_model'

# This the module which makes any class behave like ActiveModel.
module MailForm
  module Shim
    def self.included(base)
      base.class_eval do
        extend ActiveModel::Naming
        extend ActiveModel::Translation
        extend ActiveModel::Callbacks
        include ActiveModel::Validations
        include ActiveModel::Conversion

        extend MailForm::Shim::ClassMethods
        define_model_callbacks :deliver
      end
    end

    module ClassMethods
      def i18n_scope
        :mail_form
      end
    end

    # Initialize assigning the parameters given as hash.
    def initialize(params = {})
      params.each_pair do |attr, value|
        send("#{attr}=", value) if respond_to?("#{attr}=", true)
      end unless params.blank?
    end

    # Always return true so when using form_for, the default method will be post.
    def new_record?
      true
    end

    def persisted?
      false
    end

    # Always return nil so when using form_for, the default method will be post.
    def id
      nil
    end

    # Create just check validity, and if so, trigger callbacks.
    def deliver
      if valid?
        run_callbacks :deliver
      else
        false
      end
    end
    alias :save :deliver
  end
end


text:
Data Views Config Builders
==========================

.. automodule:: citrination_client.views.base_data_view_builder
    :members:

.. automodule:: citrination_client.views.data_view_builder
    :members:

.. automodule:: citrination_client.views.advanced_data_view_builder
    :members:

.. automodule:: citrination_client.views.descriptors.descriptor
    :members:
    :undoc-members:

.. automodule:: citrination_client.views.descriptors.alloy_composition_descriptor
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: citrination_client.views.descriptors.categorical_descriptor
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: citrination_client.views.descriptors.formulation_descriptor
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: citrination_client.views.descriptors.inorganic_descriptor
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: citrination_client.views.descriptors.organic_descriptor
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: citrination_client.views.descriptors.real_descriptor
    :members:
    :undoc-members:
    :show-inheritance:


text:
from __future__ import absolute_import
from __future__ import division

import click

from guild import click_util
from . import packages_delete

@click.command()
@packages_delete.delete_params
@click_util.use_args
@click_util.render_doc
def uninstall(args):
    """{{ packages_delete.delete_packages }}"""

    from . import packages_impl

    packages_impl.uninstall_packages(args)


text:
package play.utils

import scala.collection.immutable.ListMap
import scala.collection.mutable

object OrderPreserving {
  def groupBy[K, V](seq: Seq[(K, V)])(f: ((K, V)) => K): Map[K, Seq[V]] = {
    // This mutable map will not retain insertion order for the seq, but it is fast for retrieval. The value is
    // a builder for the desired Seq[String] in the final result.
    val m = mutable.Map.empty[K, mutable.Builder[V, Seq[V]]]

    // Run through the seq and create builders for each unique key, effectively doing the grouping
    for ((key, value) <- seq) m.getOrElseUpdate(key, Seq.newBuilder[V]) += value

    // Create a builder for the resulting ListMap. Note that this one is immutable and will retain insertion order
    val b = ListMap.newBuilder[K, Seq[V]]

    // Note that we are NOT going through m (didn't retain order) but we are iterating over the original seq
    // just to get the keys so we can look up the values in m with them. This is how order is maintained.
    for ((k, v) <- seq.iterator) b += k -> m.getOrElse(k, Seq.newBuilder[V]).result()

    // Get the builder to produce the final result
    b.result()
  }
}


text:
#include "includes.h"
#include "ncoffsets.h"

#ifdef ENABLE_JAVA

extern List* vlenconstants;  /* List<Constant*>;*/

/* Forward*/
static void genjjni_primdata(Symbol*, Datasrc*, Datalist*, char*, Bytebuffer*);
static void genjjni_data(Symbol* sym, Datasrc*, Datalist*, char*, Bytebuffer*);
static void genjjni_fieldarray(Symbol*, Datasrc*, Dimset*, int, char*, Bytebuffer*);
static void genjjni_arraydatar(Symbol* basetype,
	      Datasrc* src,
	      Odometer* odom,
	      Putvar* closure,
	      int index,
	      int checkpoint,
	      Bytebuffer* code);

static void jopaquestring(Symbol* tsym, Constant* prim, Constant* target);
static int genjjni_putmemory(struct Symbol*, char*, Bytebuffer*, Bytebuffer*);
static int jalignment(Symbol* tsym);
static int jvlenalignment(void);

/**************************************************/
/* Code for generating Java language data lists*/
/**************************************************/
/* Datalist rules: see the rules on the man page */

/* Specialty wrappers for genjjni_data */
void
genjjni_attrdata(Symbol* asym, Bytebuffer* databuf)
{
    Datasrc* src;
    int typecode = asym->typ.basetype->typ.typecode;
    char* memname = "memory";

    if(asym->data == NULL) return;
    if(typecode == NC_CHAR) {
        gen_charattr(asym,databuf);
    } else {
        src = datalist2src(asym->data);
        while(srcmore(src)) {
            genjjni_data(asym->typ.basetype,src,NULL,memname,databuf);
	}
    }
}

void
genjjni_scalardata(Symbol* vsym, Bytebuffer* databuf)
{
    Datasrc* src;
    char* memname = "memory";

    if(vsym->data == NULL) return;
    src = datalist2src(vsym->data);
    genjjni_data(vsym->typ.basetype,src,
		   vsym->var.special._Fillvalue,memname,databuf);
    if(srcmore(src)) {
        semerror(srcline(src),"Extra data at end of datalist");
    }
}

void
genjjni_fillvalue(Symbol* tsym, Datalist* fillsrc, Datasrc* src,
               char* memname, Bytebuffer* databuf)
{
    Datalist* list = NULL;

    ASSERT(tsym->objectclass == NC_TYPE);
    list = fillsrc;
    if(list == NULL) list = getfiller(tsym);
    srcpushlist(src,list);
    genjjni_data(tsym,src,NULL,memname,databuf);
    srcpop(src);
}

void
genjjni_arraydata(Symbol* vsym, Putvar* closure, Bytebuffer* databuf)
{
    Datasrc* src;
    Datalist* list;
    int i,checkpoint;
    nc_type typecode = vsym->typ.basetype->typ.typecode;

    if(vsym->data == NULL) return;

    list = vsym->data;
    ASSERT(list->dimdata != NULL);

    src = datalist2src(list);

    /* Locate checkpoint */
    checkpoint=0;
    for(i=0;i<vsym->typ.dimset.ndims;i++) {
	if(vsym->typ.dimset.dimsyms[i]->dim.size == NC_UNLIMITED) {
	    checkpoint = i;
	    break;
	}
    }

    if(typecode == NC_CHAR)
        gen_chararray(vsym,closure,databuf);
    else {
        genjjni_arraydatar(vsym,src,list->dimdata,closure,0,checkpoint,databuf);
    }
    commify(databuf);
}

static void
genjjni_arraydatar(Symbol* vsym,
	      Datasrc* src,
	      Odometer* odom,
	      Putvar* closure,
	      int index,
	      int checkpoint,
	      Bytebuffer* databuf)
{
    int i;
    int rank = odom->rank;
    int lastdim = (index == (rank - 1)); /* last dimension*/
    int firstdim = (index == 0);
    int docheckpoint = (closure != NULL && index == checkpoint);
    int declsize = odom->dims[index].declsize;
    int isunlimited = (declsize == 0);
    Symbol* basetype = vsym->typ.basetype;
    Datalist* fillsrc = vsym->var.special._Fillvalue;
    Constant* con;
    nc_type typecode = basetype->typ.typecode;
    char* memname = "memory";

    ASSERT(index >= 0 && index < rank);
    odom->dims[index].index = 0; /* reset*/

    if(isunlimited) {
	Constant* con;
        if(!firstdim) {
	    if(!issublist(src)) {
	        semerror(srcline(src),"Unlimited data must be enclosed in {..}");
	        return;
	    }
	    srcpush(src); /* enter the unlimited data */
	}
	while((con=srcpeek(src))!=NULL) {
	    if(lastdim) {
		if(isprimplus(typecode)) {
		    bbCat(databuf," ");
                    genjjni_primdata(basetype,src,fillsrc,memname,databuf);
		} else
                    genjjni_data(basetype,src,fillsrc,memname,databuf);
	    } else {
                genjjni_arraydatar(vsym,src,odom,closure,index+1,
                                               checkpoint,databuf);
	    }
	    odom->dims[index].index++;
	    if(docheckpoint) {
                closure->putvar(closure,odom,databuf);
	    }
	}
        odom->dims[index].datasize = odom->dims[index].index;
	if(!firstdim) srcpop(src);
    } else { /* !isunlimited*/
	for(i=0;i<declsize;i++) {
	    con = srcpeek(src);
            if(lastdim) {
		if(isprimplus(typecode)) {
		    bbCat(databuf," ");
                    genjjni_primdata(basetype,src,fillsrc,memname,databuf);
	        } else
                    genjjni_data(basetype,src,fillsrc,memname,databuf);
            } else { /* ! lastdim*/
               (void)genjjni_arraydatar(vsym,src,odom,closure,
                                        index+1,checkpoint,
					databuf);
            }
            odom->dims[index].index++;
            if(docheckpoint) {
                closure->putvar(closure,odom,databuf);
            }
	}
    }
}

/**************************************************/
/* This is the general datalist processing procedure */
static void
genjjni_data(Symbol* tsym, Datasrc* datasrc, Datalist* fillsrc,
		char* memname, Bytebuffer* databuf)
{
    int usecmpd;
    Constant* con = srcpeek(datasrc);
    Bytebuffer* constdata = NULL;
    nc_type typecode = tsym->typ.typecode;

    if(con == NULL || con->nctype == NC_FILLVALUE) {
	srcnext(datasrc);
	genjjni_fillvalue(tsym,fillsrc,datasrc,memname,databuf);
	return;
    }

    switch (tsym->subclass) {

    case NC_ENUM:
    case NC_OPAQUE:
    case NC_PRIM:
	if(issublist(datasrc)) {
	    semerror(srcline(datasrc),"Expected primitive found {..}");
	}
	bbCat(databuf," ");
	genjjni_primdata(tsym,datasrc,NULL,memname,databuf);
	break;

    case NC_COMPOUND: {
	int i;
        if(!issublist(datasrc)) {
	    semerror(srcline(datasrc),
		     "Compound data must be enclosed in {..}");
        }
	srcpush(datasrc);
        for(i=0;i<listlength(tsym->subnodes);i++) {
            Symbol* field = (Symbol*)listget(tsym->subnodes,i);
	    genjjni_data(field,datasrc,fillsrc,memname,databuf);
	}
        srcpop(datasrc);
	} break;

    case NC_VLEN: {
	char stmt[C_MAX_STMT];
        Constant* cp;
	char vlenname[1024];

        if(!issublist(datasrc)) {
	    semerror(srcline(datasrc),"Vlen data must be enclosed in {..}");
        }
        cp = srcnext(datasrc);
        sprintf(vlenname,"vlen_%u",cp->value.compoundv->vlen.uid);
	/* Use special alignment */
        nprintf(stmt,sizeof(stmt),"Memory.align(%s,%d);\n",
		vlenname,jvlenalignment());
        bbCat(databuf,stmt);
        /* generate and store the nc_vlen_t instance*/
        sprintf(stmt,"Memory.put_vlen(%s,new long[]{%lld, %s_addr});\n",
		memname,
		(long long)cp->value.compoundv->vlen.count,
		vlenname);
        bbCat(databuf,stmt);
        } break;

    case NC_FIELD:
	/* enclose in braces if and only if field is an array */
	usecmpd = (issublist(datasrc) && tsym->typ.dimset.ndims > 0);
	if(usecmpd) srcpush(datasrc);
	constdata = bbNew();
	if(tsym->typ.dimset.ndims > 0) {
            genjjni_fieldarray(tsym->typ.basetype,datasrc,&tsym->typ.dimset,0,
                            memname,constdata);
	} else {
	    genjjni_data(tsym->typ.basetype,datasrc,NULL,memname,constdata);
	}
	/* If this was a primitive valued field, then generate a
           Memory.put_XXX call
        */
	if(isprimplus(typecode)) {
	    genjjni_putmemory(tsym,memname,databuf,constdata);
	} else /* It is already one or more Memory.put_XX  calls */
	    bbAppendn(databuf,bbContents(constdata),bbLength(constdata));
	if(usecmpd) srcpop(datasrc);
	bbFree(constdata);
	bbNull(databuf);
	break;

    default: PANIC1("genjjni_data: unexpected subclass %d",tsym->subclass);
    }
}

/* Used only for structure field arrays*/
static void
genjjni_fieldarray(Symbol* basetype, Datasrc* src, Dimset* dimset, int index,
		char* memname, Bytebuffer* databuf)
{
    int i;
    Symbol* dim = dimset->dimsyms[index];
    unsigned int size = dim->dim.size;
    int lastdim = (index == (dimset->ndims - 1)); /* last dimension*/
    int typecode = basetype->typ.typecode;

    if(typecode == NC_CHAR) {
	/* Collect the char field in a separate buffer */
	Bytebuffer* fieldbuf = bbNew();
        gen_charfield(src,dimset,index,fieldbuf);
	/* Add to the existing data buf using Memory */
	jquotestring(fieldbuf,'"');
	bbCat(databuf," ");
	bbCat(databuf,bbContents(fieldbuf));
	bbFree(fieldbuf);
    } else {
        ASSERT(size != 0);
        for(i=0;i<size;i++) {
	    bbCat(databuf," ");
            if(lastdim) {
	        if(isprimplus(typecode)) {
		    bbCat(databuf," ");
		    genjjni_primdata(basetype,src,NULL,memname,databuf);
		} else
	            genjjni_data(basetype,src,NULL,memname,databuf);
            } else { /* !lastdim*/
	        genjjni_fieldarray(basetype,src,dimset,index+1,memname,databuf);
    	    }
	}
    }
}

void
genjjni_vlendata(List* vlenconstants, Bytebuffer* databuf)
{
    int i,count;
    Datasrc* vlensrc;
    char tmp[C_MAX_STMT];
    char memname[1024];
    Bytebuffer* vlenbuf = bbNew();

    for(i=0;i<listlength(vlenconstants);i++) {
	Constant* cmpd = (Constant*)listget(vlenconstants,i);
	Symbol* tsym = cmpd->value.compoundv->vlen.schema;
        Symbol* basetype = tsym->typ.basetype;
	int typecode = basetype->typ.typecode;

        sprintf(memname,"vlen_%u",cmpd->value.compoundv->vlen.uid);

	count = 0;
	vlensrc = datalist2src(cmpd->value.compoundv);
 	bbClear(vlenbuf);
	if(typecode == NC_CHAR) {
   	    /* Collect the char sequence in a separate buffer */
            gen_charseq(vlensrc,vlenbuf);
	    count = bbLength(vlenbuf);
	    /* Add to the existing data buf as a single constant */
   	    jquotestring(vlenbuf,'"');
	    /* Insert into the Memory buffer */
            genjjni_putmemory(basetype,memname,databuf,vlenbuf);
	} else {
  	    while(srcmore(vlensrc)) {
                genjjni_data(tsym->typ.basetype,vlensrc,NULL,memname,vlenbuf);
	        count++;
	    }
	    ASSERT(count == cmpd->value.compoundv->vlen.count);
	    /* Hack to handle user-defined vs primitive basetypes */
	    if(isprimplus(typecode)) {
		genjjni_putmemory(basetype,memname,databuf,vlenbuf);
	    } else { /* constdata should have the necessary Memory.put ops */
	        bbCat(databuf,bbContents(vlenbuf));
	    }
	    /* Now store the address */
            sprintf(tmp,"%s_addr = Memory.address(%s);\n",
			memname,memname);
	    bbCat(databuf,tmp);
        }
    }
    bbFree(vlenbuf);
}

void
genjjni_vlenconstants(List* vlenconstants, Bytebuffer* databuf)
{
    int i;
    char tmp[C_MAX_STMT];
    char memname[1024];

    for(i=0;i<listlength(vlenconstants);i++) {
	Constant* cmpd = (Constant*)listget(vlenconstants,i);

        sprintf(memname,"vlen_%u",cmpd->value.compoundv->vlen.uid);
	/* Define the memory buffer and a place to stick its address */
        sprintf(tmp,"static long %s = Memory.create();\n",memname);
	bbCat(databuf,tmp);
        sprintf(tmp,"static long %s_addr = 0L;\n",memname);
	bbCat(databuf,tmp);
    }
}

/**************************************************/
static void
genjjni_primdata(Symbol* tsym, Datasrc* src, Datalist* filler,
		char* memname, Bytebuffer* databuf)
{
    Constant target, *prim;

    prim = srcnext(src);

    if(prim == NULL || prim->nctype == NC_FILLVALUE) {
	genjjni_fillvalue(tsym,filler,src,memname,databuf);
	return;
    }

    target.nctype = tsym->typ.typecode;

    if(prim == NULL) {
#ifdef GENFILL
        /* generate a fill value*/
	nc_getfill(&target);
	/* fall thru*/
#else
	return;
#endif
    }

    ASSERT(prim->nctype != NC_COMPOUND);

    switch (target.nctype) {
        case NC_ECONST:
	    if(tsym->subclass != NC_ENUM) {
	        semerror(prim->lineno,"Conversion to enum not supported (yet)");
	        nc_getfill(&target);
	    } else {
	        target.nctype = NC_ECONST;
		convert1(prim,&target);
	    }
   	    break;
        case NC_OPAQUE:
            target.nctype = NC_STRING;
	    jopaquestring(tsym,prim,&target);
	    break;
        case NC_CHAR:
	    /* Hack to handle the char case as a string */
	    target = cloneconstant(prim);
	    break;
        default:
	    convert1(prim,&target);
	    break;
    }
    /* add hack for java bug in converting floats */
    if(target.nctype == NC_FLOAT) bbCat(databuf," (float)");
    bbCat(databuf,jconst(&target));
}

/* Convert an opaque to a java string */
static void
jopaquestring(Symbol* tsym, Constant* prim, Constant* target)
{
    int i;
    static char hexdigits[] = "0123456789ABCDEF";
    char* op = prim->value.opaquev.stringv;
    size_t oplen = prim->value.opaquev.len;
    unsigned char* p;
    char* opstring;

    ASSERT((oplen%2) == 0);

    opstring = (char*)ecalloc(oplen*(2+4));
    opstring[0]='\0';

    p=(unsigned char*)op;
    for(i=0;i<oplen;i++,p++) {
	char tmp[8];
	unsigned int b = *p;
	char digit1 = hexdigits[(b & 0x0f)];
	char digit2 = hexdigits[((b>>4) & 0x0f)];
	strcpy(tmp,"\\u00");
	tmp[5] = digit2;
	tmp[6] = digit1;
	tmp[7] = '\0';
	strcat(opstring,tmp);
    }
    target->value.stringv.stringv = opstring;
    target->value.stringv.len = strlen(opstring);
}

static int
jalignment(Symbol* tsym)
{
    nc_type nctype = tsym->typ.typecode;
    int alignment = 0;
    if(nctype == NC_ECONST)
        alignment = nctypealignment(tsym->typ.typecode);
    else if(usingclassic && nctype == NC_STRING)
        alignment = nctypealignment(NC_CHAR);
    else if(nctype == NC_CHAR)
        alignment = nctypealignment(NC_CHAR);
    else
        alignment = nctypealignment(nctype);
    return alignment;
}

static int
genjjni_putmemory(Symbol* tsym, char* memname, Bytebuffer* databuf, Bytebuffer* constbuf)
{
    char stmt[1024];
    nc_type typecode = tsym->typ.typecode;

    commify(constbuf);
    nprintf(stmt,sizeof(stmt),"Memory.align(%s,%d);\n",
		memname,jalignment(tsym));
    bbCat(databuf,stmt);

    if(typecode == NC_CHAR) {
        nprintf(stmt,sizeof(stmt),"Memory.put_%sarray(%s,",
		jstype(typecode),memname);
        bbCat(databuf,stmt);
        bbAppendn(databuf,bbContents(constbuf),bbLength(constbuf));
        bbCat(databuf,");\n");
    } else {
        nprintf(stmt,sizeof(stmt),"Memory.put_%sarray(%s,new %s[]{",
	    jstype(typecode),
	    memname,
	    jarraytype(typecode));
        bbCat(databuf,stmt);
        bbAppendn(databuf,bbContents(constbuf),bbLength(constbuf));
        bbCat(databuf,"});\n");
    }
    return NC_NOERR;
}

static int
jvlenalignment(void)
{
    return nctypealignment(NC_VLEN);
}

#endif /*ENABLE_JAVA*/


text:
title: Netlify Drop
date: 2015-05-16 22:38:00 +0000
posted_date: 2015-05-16 22:38:00 +0000
featured: false
slug: bitballoon
tools:
- "Hosting-Deployment"
description: Drag'n Drop deployment for static sites
urls:
  website: https://app.netlify.com/drop
  github: https://github.com/BitBalloon
  twitter: ''
  other: ''
license: Commercial
related_tools:
- tool/netlify.md
tags:
- services
- free
language: ''
resources: []
cat_test: ''
weight: ''
data_model: ''

---
BitBalloon was the ancestor from [Netlify](/tool/netlify/), it's a simpler version aimed at people who just need to drag and drop a static project to get it online[.](https://www.netlify.com/blog/2018/08/14/announcing-netlify-drop---the-simplicity-of-bitballoon-with-the-added-power-of-netlify/)

[Bitballoon is now **Netlify Drop**](https://www.netlify.com/blog/2018/08/14/announcing-netlify-drop---the-simplicity-of-bitballoon-with-the-added-power-of-netlify/)


text:
<?php

namespace PackageFinder\Enum;

class PackageTypeEnum
{
    const SSW = 'SSW';
    const CORREIOS = 'Correios';

    static $list = [
        self::SSW => self::SSW,
        self::CORREIOS => self::CORREIOS,
    ];
}


text:
define(["require", "exports", "module", "./mathUtils","./LinearInterpolation"], function(require, exports, module) {

var mathUtils = require('./mathUtils'),
    LinearInterpolation = require('./LinearInterpolation');

var _Range = function(min,max){
	this.min = min;
	this.max = max;
};
_Range.prototype.toString = function(){
	return "{ min: "+this.min+ ", max: "+this.max+"}";
};

/**
 * @class This class maps values from one interval into another. By default the mapping
 * is using linear projection, but can be changed by using alternative
 * {@link math.InterpolateStrategy} implementations to achieve a
 * non-regular mapping.
 *
 * @member toxi
 *
 * @description Creates a new instance to map values between the 2 number ranges
 * specified. By default linear projection is used.
 * @param {Number} minIn
 * @param {Number} maxIn
 * @param {Number} minOut
 * @param {Number} maxOut
 */
var ScaleMap = function(minIn, maxIn, minOut, maxOut) {
	if(arguments.length == 1 && arguments[0].input !== undefined && arguments[0].output !== undefined){ //opts object
		var arg = arguments[0];
		minOut = arg.output.min;
		maxOut = arg.output.max;
        maxIn = arg.input.max;
        minIn = arg.input.min;
	}
	this.mapFunction = new LinearInterpolation();
	this.setInputRange(minIn, maxIn);
	this.setOutputRange(minOut, maxOut);
};

ScaleMap.prototype = {

    /**
     * Computes mapped value in the target interval and ensures the input value
     * is clipped to source interval.
     *
     * @param val
     * @return mapped value
     */
   getClippedValueFor: function(val) {
        var t = mathUtils.clipNormalized( ((val - this._in.min) / this._interval));
        return this.mapFunction.interpolate(0, this.mapRange, t) + this._out.min;
    },

    /**
     * @return the middle value of the input range.
     */
    getInputMedian: function() {
        return (this._in.min + this._in.max) * 0.5;
    },

    /**
     * @return the in
     */
    getInputRange: function() {
        return this._in;
    },

    /**
     * @return the mapped middle value of the output range. Depending on the
     *         mapping function used, this value might be different to the one
     *         returned by {@link #getOutputMedian()}.
     */
    getMappedMedian: function() {
        return this.getMappedValueFor(0.5);
    },

    /**
     * Computes mapped value in the target interval. Does check if input value
     * is outside the input range.
     *
     * @param val
     * @return mapped value
     */
    getMappedValueFor: function(val) {
        var t = ((val - this._in.min) / this._interval);
        return this.mapFunction.interpolate(0,  this.mapRange, t) + this._out.min;
    },

    /**
     * @return the middle value of the output range
     */
    getOutputMedian:function() {
        return (this._out.min + this._out.max) * 0.5;
    },

    /**
     * @return the output range
     */
    getOutputRange: function() {
        return this._out;
    },

    /**
     * Sets new minimum & maximum values for the input range
     *
     * @param min
     * @param max
     */
    setInputRange: function(min,max) {
        this._in = new _Range(min,max);
        this._interval = max - min;
    },

    /**
     * Overrides the mapping function used for the scale conversion.
     *
     * @param func
     *            interpolate strategy implementation
     */
    setMapFunction: function(func) {
        this.mapFunction = func;
    },

    /**
     * Sets new minimum & maximum values for the output/target range
     *
     * @param min
     *            new min output value
     * @param max
     *            new max output value
     */
    setOutputRange: function(min, max) {
        this._out = new _Range(min, max);
        this.mapRange = max - min;
    },

    toString: function(){
		return "ScaleMap, inputRange: "+this._in.toString() + " outputRange: "+this._out.toString();
    }
};

module.exports = ScaleMap;
});


text:
# Feathers Hooks

[![Build Status](https://travis-ci.org/feathersjs/feathers-hooks.png?branch=master)](https://travis-ci.org/feathersjs/feathers-hooks)

> Before and after service method call hooks for easy authorization and processing.

## Getting Started

To install feathers-hooks from [npm](https://www.npmjs.org/), run:

```bash
$ npm install feathers-hooks --save
```

Finally, to use the plugin in your Feathers app:

```javascript
var feathers = require('feathers');
var hooks = require('feathers-hooks');

var app = feathers().configure(hooks());
```

## Examples

The repository contains the following working examples:

- [authorization.js](https://github.com/feathersjs/feathers-hooks/blob/master/examples/authorization.js) - A simple demo showing how to use hooks for authorization (and post-processing the results) where the user is set via a ?user=username query parameter.
- [timestamp.js](https://github.com/feathersjs/feathers-hooks/blob/master/examples/timestamp.js) - A demo that adds a `createdAt` and `updatedAt` timestamp when creating or updating a Todo using hooks.

## Using hooks

Feathers hooks are a form of [Aspect Oriented Programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming) that allow you to decouple things like authorization and pre- or post processing from your services logic.

You can add as many `before` and `after` hooks to any Feathers service method as you want (they will be executed in the order they have been registered). There are two ways to use hooks. Either after registering the service by calling `service.before(beforeHooks)` or `service.after(afterHooks)` or by adding a `before` or `after` object with your hooks to the service.

Lets assume a Feathers application initialized like this:

```js
var feathers = require('feathers');
var hooks = require('feathers-hooks');

var app = feathers()
    .configure(hooks())
    .use('/todos', {
       todos: [],

       get: function(id, params, callback) {
         for(var i = 0; i < this.todos.length; i++) {
          if(this.todos[i].id === id) {
            return callback(null, this.todos[i]);
          }
         }

         callback(new Error('Todo not found'));
       },

       // Return all todos from this service
       find: function(params, callback) {
         callback(null, this.todos);
       },

       // Create a new Todo with the given data
       create: function(data, params, callback) {
         data.id = this.todos.length;
         this.todos.push(data);

         callback(null, data);
       }
     });

app.listen(8000);

// Get the wrapped service object which will be used in the other exapmles
var todoService = app.lookup('todos');
```

### `service.before(beforeHooks)`

`before` hooks allow to pre-process service call parameters. They will be called with the hook object
and a callback which should be called with any errors or no arguments or `null` and the modified hook object.
The hook object contains information about the intercepted method and for `before` hooks can have the following properties:

- __method__ - The method name
- __type__ - The hook type (`before` or `after`)
- __callback__ - The original callback (can be replaced but shouldn't be called in your hook)
- __params__ - The service method parameters
- __data__ - The request data (for `create`, `update` and `patch`)
- __id__ - The id (for `get`, `remove`, `update` and `patch`)

All properties of the hook object can be modified and the modified data will be used for the actual service method
call. This is very helpful for pre-processing parameters and massaging data when creating or updating.

The following example checks if a user has been passed to the services `find` method and returns an error if not
and also adds a `createdAt` property to a newly created todo:

```js
todoService.before({
  find: function (hook, next) {
    if (!hook.params.user) {
      return next(new Error('You are not logged in'));
    }

    next();
  },

  create: function(hook, next) {
    hook.data.createdAt = new Date();

    next();
    // Or
    next(null, hook);
  }
});
```

### `service.after(afterHooks)`

`after` hooks will be called with a similar hook object than `before` hooks but additionally contain a `result`
property with the service call results:

- __method__ - The method name
- __type__ - The hook type (`before` or `after`)
- __result__ - The service call result data
- __callback__ - The original callback (can be replaced but shouldn't be called in your hook)
- __params__ - The service method parameters
- __data__ - The request data (for `create`, `update` and `patch`)
- __id__ - The id (for `get`, `remove`, `update` and `patch`)

In any `after` hook, only modifications to the `result` object will have any effect. This is a good place to filter or
post-process the data retrieved by a service and also add some additional authorization that needs the actual data.

The following example filters the data returned by a `find` service call based on a users company id
and checks if the current user is allowed to retrieve the data returned by `get` (that is, they have the same company id):

```js
todoService.after({
  find: function (hook, next) {
    // Manually filter the find results
    hook.result = _.filter(hook.result, function (current) {
      return current.companyId === params.user.companyId;
    });

    next();
  },

  get: function (hook, next) {
    if (hook.result.companyId !== hook.params.user.companyId) {
      return next(new Error('You are not authorized to access this information'));
    }

    next();
  }
});
```

### As service properties

You can also add `before` and `after` hooks to your initial service object right away by setting the `before` and
`after` properties to the hook object. The following example has the same effect as the previous examples:

```js
var TodoService = {
	todos: [],

	get: function (id, params, callback) {
		for (var i = 0; i < this.todos.length; i++) {
			if (this.todos[i].id === id) {
				return callback(null, this.todos[i]);
			}
		}

		callback(new Error('Todo not found'));
	},

	// Return all todos from this service
	find: function (params, callback) {
		callback(null, this.todos);
	},

	// Create a new Todo with the given data
	create: function (data, params, callback) {
		data.id = this.todos.length;
		this.todos.push(data);

		callback(null, data);
	},

	before: {
		find: function (hook, next) {
			if (!hook.params.user) {
				return next(new Error('You are not logged in'));
			}

			next();
		},

		create: function (hook, next) {
			hook.data.createdAt = new Date();

			next();
			// Or
			next(null, hook);
		}
	},

	after: {
		find: function (hook, next) {
			// Manually filter the find results
			hook.result = _.filter(hook.result, function (current) {
				return current.companyId === params.user.companyId;
			});

			next();
		},

		get: function (hook, next) {
			if (hook.result.companyId !== hook.params.user.companyId) {
				return next(new Error('You are not authorized to access this information'));
			}

			next();
		}
	}
}
```

### Promises

All hooks can return a [Promise](http://promises-aplus.github.io/promises-spec/) object instead of calling the callback. The promises return value will *not* be used. Using [Q](https://github.com/kriskowal/q) it would look like:

```js
todoService.before({
  find: function (hook) {
    return Q(/* ... */);
  }
});
```

If you want to change the hook object just chain the returned promise using `.then`:

```js
todoService.before({
  find: function (hook) {
    return Q(/* ... */).then(function(result) {
      hook.params.message = 'Ran through promise hook';
      hook.data.result = result;
    });
  }
});
```

If a promise fails, the error will be propagated immediately.

## Changelog

__0.3.0__

- Allows hooks to return a promise ([#3](https://github.com/feathersjs/feathers-hooks/issues/3), [#4](https://github.com/feathersjs/feathers-hooks/issues/4))

__0.2.0__

- API change to use hook objects instead of function parameters ([#1](https://github.com/feathersjs/feathers-hooks/issues/1))

__0.1.0__

- Initial release

## Author

- [David Luecke](https://github.com/daffl)

## License

Copyright (c) 2014 David Luecke

Licensed under the [MIT license](LICENSE).


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

    <style name="ripple_confi" >
        <item name="lysr_rippleAlpha">0.3</item>
        <item name="lysr_rippleFadeDuration">5</item>
    </style>
</resources>


text:
package com.example.pengyuanfan.fablix.viewHolder;

import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by pengyuanfan on 6/9/2016.
 */
public class PagerHolder {
    View mvLVPager;
    Button prev;
    Button next;
    TextView max;
    TextView cur;

    public View getMvLVPager() {
        return mvLVPager;
    }

    public void setMvLVPager(View mvLVPager) {
        this.mvLVPager = mvLVPager;
    }

    public Button getPrev() {
        return prev;
    }

    public void setPrev(Button prev) {
        this.prev = prev;
    }

    public Button getNext() {
        return next;
    }

    public void setNext(Button next) {
        this.next = next;
    }

    public TextView getMax() {
        return max;
    }

    public void setMax(TextView max) {
        this.max = max;
    }

    public TextView getCur() {
        return cur;
    }

    public void setCur(TextView cur) {
        this.cur = cur;
    }

    public void setPage(int curpage, int maxpage){
        getCur().setText(Integer.toString(curpage));
        getMax().setText(Integer.toString(maxpage));
        getPrev().setEnabled(true);
        getNext().setEnabled(true);
        if(curpage==1){
            getPrev().setEnabled(false);
        }
        if(curpage==maxpage){
            getNext().setEnabled(false);
        }
    }
}


text:
import sys

if sys.version_info < (3, 7):
    from ._templateitemname import TemplateitemnameValidator
    from ._name import NameValidator
    from ._label import LabelValidator
    from ._colorscale import ColorscaleValidator
    from ._cmin import CminValidator
    from ._cmax import CmaxValidator
else:
    from _plotly_utils.importers import relative_import

    __all__, __getattr__, __dir__ = relative_import(
        __name__,
        [],
        [
            "._templateitemname.TemplateitemnameValidator",
            "._name.NameValidator",
            "._label.LabelValidator",
            "._colorscale.ColorscaleValidator",
            "._cmin.CminValidator",
            "._cmax.CmaxValidator",
        ],
    )


text:
using System;

namespace Sce.Sled.Shared.Services
{
    /// <summary>
    /// SLED project watcher service EventArgs class
    /// </summary>
    public class SledProjectWatcherServiceEventArgs : EventArgs
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="absolutePath">Absolute path to project</param>
        public SledProjectWatcherServiceEventArgs(string absolutePath)
        {
            AbsolutePath = absolutePath;
        }

        /// <summary>
        /// Absolute path to project that changed
        /// </summary>
        public readonly string AbsolutePath;
    }

    /// <summary>
    /// SLED project watcher service interface
    /// </summary>
    public interface ISledProjectWatcherService
    {
        /// <summary>
        /// Event triggered when the project file is changed
        /// </summary>
        event EventHandler<SledProjectWatcherServiceEventArgs> FileChangedEvent;

        /// <summary>
        /// Event triggered when the project file's attribute is changed
        /// </summary>
        event EventHandler<SledProjectWatcherServiceEventArgs> AttributeChangedEvent;
    }
}


text:
import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import { FormattedMessage } from 'react-intl';

// Import Style
import styles from './CalendarListItem.css';

function CalendarListItem(props) {
  return (

        <Link to={`/calendars/${props.calendar.slug}-${props.calendar.cuid}`} >
          {props.calendar.title}
        </Link>

<FormattedMessage id="by" /> {props.calendar.name}

{props.calendar.content}

<FormattedMessage id="deletecalendar" />

  );
}

CalendarListItem.propTypes = {
  calendar: PropTypes.shape({
    name: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
    content: PropTypes.string.isRequired,
    slug: PropTypes.string.isRequired,
    cuid: PropTypes.string.isRequired,
  }).isRequired,
  onDelete: PropTypes.func.isRequired,
};

export default CalendarListItem;


text:
package org.deftserver.web.http;

import java.io.IOException;

import com.google.common.collect.Maps;

public class MalFormedHttpRequest extends HttpRequest {

	public static final MalFormedHttpRequest instance;
	static {
		try {
			instance = new MalFormedHttpRequest();
		} catch (IOException e) {
			throw new IllegalStateException("MalFormedHttpRequest instance couldn't be created");
		}
	}

	/* Dummy HttpRequest that represents a malformed client HTTP request */
	private MalFormedHttpRequest() throws IOException {
		super(-1, "GET / Malformed request\r\n", Maps.<String, String>newHashMap(), null);
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Favotrichophyton caballinum Neveu-Lem.

### Remarks
null